# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-fetched-mcp-tool-manifest-the-manifest-drift-injection-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-fetched-mcp-tool-manifest-the-manifest-drift-injection-window.warrant.json
# Markdown SHA-256:   97f4fd45ce7e753f0493ea9caa0f4da6a178d157b1735122f9b797994f495123
# Code AST SHA-256:   afc5c6cae08a47a8eca9dc2de034ce30ce0494d184504b7533617da8b7e616ae
# Verified Classes:   ManifestDriftError, EnrolledTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when a re-fetched tool manifest diverges from the enrolled trust anchor."""
    pass


@dataclass(frozen=True)
class EnrolledTool:
    name: str
    description: str
    input_schema: dict

    def digest(self) -> str:
        # Bind trust to ALL instruction-bearing fields, not just the schema.
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "inputSchema": self.input_schema,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def reconcile_manifest(
    enrolled: dict[str, EnrolledTool],
    fetched: list[dict],
    *,
    allow_description_drift: bool = False,
) -> dict[str, EnrolledTool]:
    """
    Reconcile a freshly fetched tools/list against the enrollment anchor.
    Any drift in a field the model consumes as instruction is a re-enrollment
    event, not a cache refresh.
    """
    reconciled: dict[str, EnrolledTool] = {}
    for raw in fetched:
        candidate = EnrolledTool(
            name=raw["name"],
            description=raw.get("description", ""),
            input_schema=raw.get("inputSchema", {}),
        )
        prior = enrolled.get(candidate.name)

        if prior is None:
            # New tool appearing mid-life: always quarantine, never auto-adopt.
            raise ManifestDriftError(
                f"tool {candidate.name!r} not in enrollment; quarantine pending review"
            )

        if prior.digest() != candidate.digest():
            schema_changed = prior.input_schema != candidate.input_schema
            desc_changed = prior.description != candidate.description
            if desc_changed and not schema_changed and allow_description_drift:
                # Explicit opt-in only; default path never reaches here.
                reconciled[candidate.name] = candidate
                continue
            raise ManifestDriftError(
                f"manifest drift on {candidate.name!r}: "
                f"description_changed={desc_changed} schema_changed={schema_changed}; "
                f"re-enrollment required, refusing to call under stale trust"
            )

        reconciled[candidate.name] = candidate

    return reconciled
