# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-s-self-declared-schema-during-hot-reload-the-description-field-injection-surface-in-dynamic-plugin-registr.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-s-self-declared-schema-during-hot-reload-the-description-field-injection-surface-in-dynamic-plugin-registr.warrant.json
# Markdown SHA-256:   8dedfcb9421f024072f3a1cf73459ae546e9d6aa201e1df3ad8a8dfc335b9c31
# Code AST SHA-256:   10e3ea4003db43dacf1c8a40f8e44715d098a1e4774eab3425d15bc23db86037
# Verified Classes:   DescriptorDriftError, ToolDescriptor, CatalogGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class DescriptorDriftError(RuntimeError):
    """Raised when a re-fetched tool descriptor diverges from its pinned hash."""
    pass


@dataclass
class ToolDescriptor:
    name: str
    description: str
    schema: dict

    def canonical_hash(self) -> str:
        blob = json.dumps(
            {"name": self.name, "description": self.description, "schema": self.schema},
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(blob).hexdigest()


@dataclass
class CatalogGate:
    """Admits descriptors into the instruction region only if hash-pinned."""
    pinned: dict[str, str] = field(default_factory=dict)

    def pin(self, desc: ToolDescriptor) -> None:
        self.pinned[desc.name] = desc.canonical_hash()

    def admit(self, incoming: list[ToolDescriptor]) -> list[ToolDescriptor]:
        admitted: list[ToolDescriptor] = []
        for desc in incoming:
            prior = self.pinned.get(desc.name)
            current = desc.canonical_hash()
            if prior is None:
                # First sight: require explicit operator pin before prose enters context.
                raise DescriptorDriftError(
                    f"unpinned descriptor '{desc.name}' attempted instruction-region entry; "
                    f"hash={current[:12]}"
                )
            if prior != current:
                # Drift: demote to schema-only, never let mutated prose reach the model.
                raise DescriptorDriftError(
                    f"descriptor '{desc.name}' drifted mid-session: "
                    f"pinned={prior[:12]} current={current[:12]}; "
                    f"prose quarantined, schema-only projection permitted"
                )
            admitted.append(desc)
        return admitted


def render_tool_block(gate: CatalogGate, catalog: list[ToolDescriptor]) -> str:
    safe = gate.admit(catalog)
    return "\n".join(f"- {d.name}: {d.description}" for d in safe)
