# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-reloaded-toolkit-descriptor-level-skill-injection-across-hot-swapped-agent-tool-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-reloaded-toolkit-descriptor-level-skill-injection-across-hot-swapped-agent-tool-registries.warrant.json
# Markdown SHA-256:   1fb9659dac91b2c052cdaab2ef72aba74c1702bba13886386f6fc71d8a25838a
# Code AST SHA-256:   7924dc720a93381687cc3e870c146d6c546ee534325013cd172d94651fbb6b2a
# Verified Classes:   DescriptorDriftError, TrustRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorDriftError(RuntimeError):
    """Raised when a hot-swapped tool descriptor diverges from its approved bytes."""
    pass


@dataclass(frozen=True)
class TrustRecord:
    name: str
    descriptor_hash: str


def hash_descriptor(descriptor: dict) -> str:
    # Hash the full semantic payload, not just name + schema shape.
    canonical = json.dumps(
        {
            "name": descriptor["name"],
            "inputSchema": descriptor.get("inputSchema", {}),
            "description": descriptor.get("description", ""),
            "examples": descriptor.get("examples", []),
            "annotations": descriptor.get("annotations", {}),
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def reconcile_refresh(
    trust_cache: dict[str, TrustRecord],
    refreshed: list[dict],
    quarantine: set[str],
) -> list[dict]:
    """Return only descriptors safe to expose to the planner.

    Any name whose descriptor bytes changed since approval is quarantined:
    the slot is withheld AND its new prose is never shown to the model.
    """
    admitted: list[dict] = []
    for desc in refreshed:
        name = desc["name"]
        new_hash = hash_descriptor(desc)
        record = trust_cache.get(name)

        if record is None:
            quarantine.add(name)
            continue

        if record.descriptor_hash != new_hash:
            quarantine.add(name)
            # Do NOT pass the mutated description through "for context".
            raise DescriptorDriftError(
                f"descriptor drift on trusted slot {name!r}: "
                f"approved={record.descriptor_hash[:12]} "
                f"observed={new_hash[:12]}; slot quarantined, "
                f"planner must not receive new prose until re-approval"
            )

        admitted.append(desc)
    return admitted
