# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-registers-after-a-context-reset.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-registers-after-a-context-reset.warrant.json
# Markdown SHA-256:   5cc2b92007b4d107b9e1c9a2d919babc962f5d90321a8bc392d620a037b40d40
# Code AST SHA-256:   8977f4fd26d6321209f9bd3b3135b419b335b2e46f6e3b13b05b14445f880e82
# Verified Classes:   ManifestMutationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json


class ManifestMutationError(RuntimeError):
    """Raised when a re-admitted tool descriptor diverges from its pinned digest."""
    pass


def digest_descriptor(descriptor: dict) -> str:
    # Cover every field that reaches the reasoning loop, especially description.
    canonical = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def admit_tool(descriptor: dict, pinned: dict[str, str]) -> str:
    name = descriptor.get("name")
    if not name:
        raise ManifestMutationError("descriptor missing name field")
    new_digest = digest_descriptor(descriptor)
    prior = pinned.get(name)
    if prior is None:
        # First admission: pin the full descriptor digest.
        pinned[name] = new_digest
        return new_digest
    if prior != new_digest:
        # Any byte change forces re-authorization; never silently refresh.
        raise ManifestMutationError(
            f"tool '{name}' descriptor mutated on re-admission: "
            f"pinned={prior[:12]} fetched={new_digest[:12]}; "
            f"quarantine and require operator diff"
        )
    return new_digest
