# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-description-that-was-valid-at-discovery-but-mutated-before-invocation-the-manifest-mutation-window-in-dynamic-s.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-description-that-was-valid-at-discovery-but-mutated-before-invocation-the-manifest-mutation-window-in-dynamic-s.warrant.json
# Markdown SHA-256:   72d4ca24da697f1335223e1ade4042656824f901b3f8f1c9a579383aaeb8265d
# Code AST SHA-256:   45edef5bda30e797622291186960bbc14cdc6b4a879fbcf61d5faf8734de34d3
# Verified Classes:   ManifestMutationError, TrustTuple
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestMutationError(RuntimeError):
    """Raised when a tool's trusted content tuple no longer matches the registry."""
    pass


@dataclass(frozen=True)
class TrustTuple:
    server_identity: str
    tool_name: str
    description_hash: str
    schema_hash: str


def _hash(obj) -> str:
    canonical = json.dumps(obj, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def make_tuple(server_identity: str, tool: dict) -> TrustTuple:
    return TrustTuple(
        server_identity=server_identity,
        tool_name=tool["name"],
        description_hash=_hash(tool.get("description", "")),
        schema_hash=_hash(tool.get("inputSchema", {})),
    )


def verify_manifest(
    server_identity: str,
    fetched_tools: list[dict],
    approval_ledger: dict[str, TrustTuple],
) -> list[dict]:
    """Return only tools whose full content tuple matches the ledger.

    Any tool whose description or schema mutated since approval is quarantined;
    a schema-identical but description-changed tool raises rather than silently
    passing, because the description is control input to the reasoning loop.
    """
    approved = []
    for tool in fetched_tools:
        current = make_tuple(server_identity, tool)
        prior = approval_ledger.get(current.tool_name)

        if prior is None:
            # Never seen: not trusted, do not invoke.
            continue

        if prior.schema_hash != current.schema_hash:
            # Schema drift is loud and expected; require re-approval.
            raise ManifestMutationError(
                f"schema changed for {current.tool_name!r} on {server_identity!r}"
            )

        if prior.description_hash != current.description_hash:
            # The dangerous case: same schema, mutated description bytes.
            raise ManifestMutationError(
                f"description mutated for {current.tool_name!r} on "
                f"{server_identity!r} without schema change; quarantining"
            )

        if prior.server_identity != current.server_identity:
            raise ManifestMutationError(
                f"tool {current.tool_name!r} resolved to unexpected server "
                f"{current.server_identity!r} (expected {prior.server_identity!r})"
            )

        approved.append(tool)
    return approved
