# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-validated-capability-poisoning-via-post-handshake-manifest-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-validated-capability-poisoning-via-post-handshake-manifest-drift.warrant.json
# Markdown SHA-256:   90d88122ff3c7aedb79c7ff399ec24b561d12b64a2e2a6db4ded418aa83755a8
# Code AST SHA-256:   96d198e2eb9de5424e16e0600e6cb3f526ba8e87a7748f2f80ce0d8aadf14e39
# Verified Classes:   ManifestDriftError, Attestation, ManifestGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestDriftError(RuntimeError):
    """Raised when a re-fetched manifest diverges from its attested content hash."""
    pass


# Fields the model can read as instruction. These MUST be inside the trust boundary.
INSTRUCTION_BEARING = ("name", "description", "input_schema", "examples", "enum_labels")
# Fields whose change voids the binding outright (contract, not prose).
CONTRACT_FIELDS = ("name", "input_schema")


def content_hash(manifest: dict) -> str:
    blob = json.dumps(
        {k: manifest.get(k) for k in INSTRUCTION_BEARING},
        sort_keys=True,
        separators=(",", ":"),
    ).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class Attestation:
    tool_name: str
    approved_hash: str
    approved_manifest: dict


@dataclass
class ManifestGate:
    attestations: dict = field(default_factory=dict)

    def approve(self, manifest: dict) -> Attestation:
        att = Attestation(
            tool_name=manifest["name"],
            approved_hash=content_hash(manifest),
            approved_manifest=dict(manifest),
        )
        self.attestations[manifest["name"]] = att
        return att

    def on_refetch(self, live_manifest: dict) -> dict:
        """Called on every poll/reconnect/handoff. Returns the manifest safe to
        surface to the planner, or raises if drift requires quarantine."""
        name = live_manifest["name"]
        att = self.attestations.get(name)
        if att is None:
            raise ManifestDriftError(f"tool {name!r} was never attested")

        live_hash = content_hash(live_manifest)
        if live_hash == att.approved_hash:
            return live_manifest  # byte-identical, reuse verdict

        # Drift detected. Classify it.
        contract_changed = any(
            live_manifest.get(f) != att.approved_manifest.get(f)
            for f in CONTRACT_FIELDS
        )
        if contract_changed:
            raise ManifestDriftError(
                f"tool {name!r}: contract fields changed under a live binding; "
                f"binding void, full re-review required before any call"
            )

        # Schema/identity intact but instruction-bearing prose drifted.
        # This is the silent-poisoning case: do NOT surface live text to planner.
        raise ManifestDriftError(
            f"tool {name!r}: instruction-bearing fields drifted "
            f"(attested={att.approved_hash[:12]} live={live_hash[:12]}); "
            f"quarantine and re-approve — returning attested description stub"
        )


def safe_description(gate: ManifestGate, live_manifest: dict) -> str:
    """Planner-facing accessor: always returns attested prose, never live drift."""
    try:
        gate.on_refetch(live_manifest)
        return live_manifest["description"]
    except ManifestDriftError:
        # Fail closed: serve the last approved text, not the attacker's.
        return gate.attestations[live_manifest["name"]].approved_manifest["description"]
