# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-verified-toolkit-manifest-and-the-live-tool-descriptors-it-dispatches-against.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-verified-toolkit-manifest-and-the-live-tool-descriptors-it-dispatches-against.warrant.json
# Markdown SHA-256:   6de6759705b3637aa863a9fea884231303aef2a73bb4ddebddd5e2edb881b298
# Code AST SHA-256:   70e65b663bc089f9a6d268a44a0a94996eab77c504470e046f37f1d58e74cb56
# Verified Classes:   DescriptorTrustViolation, VerifiedDescriptor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptorTrustViolation(RuntimeError):
    """Raised when a tool descriptor reaches the model without a covering verification event."""


@dataclass(frozen=True)
class VerifiedDescriptor:
    name: str
    descriptor_hash: str  # sha256 over name+description+inputSchema canonical form


def descriptor_hash(name: str, description: str, input_schema: str) -> str:
    payload = f"{name}\x00{description}\x00{input_schema}".encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def splice_descriptors_into_context(
    refreshed: list[dict],
    verified: dict[str, VerifiedDescriptor],
) -> list[dict]:
    """
    Guardrail: every descriptor entering the model context must have a
    verification event covering its mutable fields (description, inputSchema).
    Name-scoped verification is insufficient; a name match with a changed
    descriptor hash is an unverified state transition.
    """
    admitted = []
    for d in refreshed:
        name = d["name"]
        h = descriptor_hash(name, d.get("description", ""), d.get("inputSchema", ""))
        v = verified.get(name)
        if v is None:
            raise DescriptorTrustViolation(
                f"tool {name!r} presented to model with no verification event"
            )
        if v.descriptor_hash != h:
            raise DescriptorTrustViolation(
                f"tool {name!r} descriptor mutated after verification "
                f"(verified={v.descriptor_hash[:12]}, live={h[:12]}); "
                f"re-verify before splice"
            )
        admitted.append(d)
    return admitted
