# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-execute-a-poisoned-tool-schema-after-a-registry-hot-reload-and-how-do-we-bound-the-skill-injection-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-execute-a-poisoned-tool-schema-after-a-registry-hot-reload-and-how-do-we-bound-the-skill-injection-surface.warrant.json
# Markdown SHA-256:   9919caa1485c8f708d42ce60260b609119d8bf64736838ddc88464f21f936410
# Code AST SHA-256:   603c254db4f1d924792a1e81ccfd98281168f6e70c9b1530becf39cc750c7d80
# Verified Classes:   SchemaDriftError, PinnedRegistry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class SchemaDriftError(RuntimeError):
    """Raised when a tool definition mutates mid-episode under a stable name."""
    pass


def _canonical_hash(tool: dict[str, Any]) -> str:
    payload = json.dumps(
        {
            "name": tool["name"],
            "description": tool.get("description", ""),
            "inputSchema": tool.get("inputSchema", {}),
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


@dataclass
class PinnedRegistry:
    pinned: dict[str, str] = field(default_factory=dict)
    quarantined: set[str] = field(default_factory=set)

    def pin_episode(self, tools: list[dict[str, Any]]) -> None:
        self.pinned = {t["name"]: _canonical_hash(t) for t in tools}
        self.quarantined.clear()

    def admit_reload(self, incoming: list[dict[str, Any]]) -> list[dict[str, Any]]:
        """Return tools safe to expose to the model this episode.

        Any tool whose name is already pinned but whose hash changed is
        quarantined and excluded. New names are admitted only if they carry
        no collision with a quarantined name.
        """
        safe: list[dict[str, Any]] = []
        for tool in incoming:
            name = tool["name"]
            new_hash = _canonical_hash(tool)

            if name in self.pinned and self.pinned[name] != new_hash:
                self.quarantined.add(name)
                raise SchemaDriftError(
                    f"Tool '{name}' mutated mid-episode "
                    f"(pinned={self.pinned[name][:12]} new={new_hash[:12]}); "
                    f"quarantined pending re-attestation."
                )

            if name in self.quarantined:
                continue

            if name not in self.pinned:
                self.pinned[name] = new_hash
            safe.append(tool)
        return safe
