# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-manifest-whose-declared-schema-is-stable-but-whose-natural-language-description-field-mutates.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-manifest-whose-declared-schema-is-stable-but-whose-natural-language-description-field-mutates.warrant.json
# Markdown SHA-256:   4cc4af8cc7d5d177e536dbbf28ad99554a94b66e3e55b785e70e81eb58358036
# Code AST SHA-256:   e9e40df568baa7ac7258743e0c216891451adfae6b70e73443c1c3229744e4b7
# Verified Classes:   ManifestDescriptionDriftError, AdmittedTool, ToolRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field


class ManifestDescriptionDriftError(RuntimeError):
    """Raised when a re-acquired tool manifest's instruction-bearing text
    differs from the snapshot admitted at discovery, even though its
    parameter schema is unchanged."""
    pass


def _normalize(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()


def _instruction_fingerprint(manifest: dict) -> str:
    """Fingerprint every string the model reads as instruction:
    the tool description and each parameter description."""
    parts = [manifest.get("name", ""), _normalize(manifest.get("description", ""))]
    for pname in sorted(manifest.get("parameters", {}).get("properties", {})):
        pdesc = manifest["parameters"]["properties"][pname].get("description", "")
        parts.append(f"{pname}:{_normalize(pdesc)}")
    return hashlib.sha256("\x00".join(parts).encode("utf-8")).hexdigest()


def _schema_fingerprint(manifest: dict) -> str:
    """Structural fingerprint only: names, types, required. Blind to text."""
    params = manifest.get("parameters", {})
    shape = {
        "name": manifest.get("name"),
        "properties": {
            k: v.get("type") for k, v in params.get("properties", {}).items()
        },
        "required": sorted(params.get("required", [])),
    }
    return hashlib.sha256(repr(sorted(shape.items())).encode("utf-8")).hexdigest()


@dataclass
class AdmittedTool:
    name: str
    schema_fp: str
    instruction_fp: str


@dataclass
class ToolRegistry:
    admitted: dict = field(default_factory=dict)

    def admit(self, manifest: dict) -> None:
        self.admitted[manifest["name"]] = AdmittedTool(
            name=manifest["name"],
            schema_fp=_schema_fingerprint(manifest),
            instruction_fp=_instruction_fingerprint(manifest),
        )

    def verify_on_reacquire(self, manifest: dict) -> None:
        name = manifest.get("name")
        prior = self.admitted.get(name)
        if prior is None:
            raise ManifestDescriptionDriftError(
                f"tool {name!r} re-acquired but never admitted; refusing to load"
            )
        if _schema_fingerprint(manifest) != prior.schema_fp:
            raise ManifestDescriptionDriftError(
                f"tool {name!r} schema changed on re-acquire; trust void"
            )
        if _instruction_fingerprint(manifest) != prior.instruction_fp:
            # Schema identical, instruction text mutated: the attack signature.
            raise ManifestDescriptionDriftError(
                f"tool {name!r} description mutated while schema stayed stable; "
                f"quarantine and require out-of-band re-admission"
            )


def load_or_quarantine(registry: ToolRegistry, manifest: dict) -> str:
    try:
        registry.verify_on_reacquire(manifest)
        return "admitted"
    except ManifestDescriptionDriftError:
        return "quarantined"
