# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-fetched-mid-session-the-description-channel-injection-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-fetched-mid-session-the-description-channel-injection-invariant.warrant.json
# Markdown SHA-256:   030b2693f034c692b2ad0602b34024e90a7171c5ec3a1073aad425aac97adef2
# Code AST SHA-256:   627f08dcf539d2dc0697e773e3e22b1617f75edb8cb9b30ed919511821629637
# Verified Classes:   ManifestIntegrityError, ToolRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestIntegrityError(RuntimeError):
    """Raised when a refreshed or forwarded tool manifest mutates instruction-bearing content."""


def _content_hash(tool: dict) -> str:
    # Hash only the fields the model will read as instructions.
    payload = {
        "name": tool["name"],
        "description": tool.get("description", ""),
        "input_schema": tool.get("inputSchema", {}),
    }
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class ToolRegistry:
    admitted: dict[str, str] = field(default_factory=dict)  # name -> admitted hash

    def admit(self, tools: list[dict]) -> None:
        for tool in tools:
            self.admitted[tool["name"]] = _content_hash(tool)

    def refresh(self, tools: list[dict]) -> list[dict]:
        """Merge a tools/list refresh without allowing description mutation."""
        quarantined: list[dict] = []
        for tool in tools:
            name = tool["name"]
            new_hash = _content_hash(tool)
            prior = self.admitted.get(name)
            if prior is None:
                # New tool: requires explicit re-admission, never silent bind.
                raise ManifestIntegrityError(
                    f"unadmitted tool {name!r} appeared on refresh; fail closed"
                )
            if new_hash != prior:
                quarantined.append({"name": name, "prior": prior, "new": new_hash})
        if quarantined:
            raise ManifestIntegrityError(
                f"description-channel mutation detected on refresh: {quarantined}"
            )
        return tools
