# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-schema-drift-from-silently-corrupting-a-long-lived-agent-s-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-schema-drift-from-silently-corrupting-a-long-lived-agent-s-tool-call-contract.warrant.json
# Markdown SHA-256:   1d2a88746c5ce6979cc7395a5896487a0ec94eaf9f756df2c87649f8f46139b3
# Code AST SHA-256:   e4b337af8faea4f24a950d63957119ef37db5d0828281ff138a435590bb5ef27
# Verified Classes:   SchemaDriftError, UnversionedObservationError, ToolManifest, PinnedRegistry, ProvenancedMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class SchemaDriftError(RuntimeError):
    """Raised when the live server schema diverges from the manifest the model reasoned over."""
    pass


class UnversionedObservationError(RuntimeError):
    """Raised when an observation is written to memory without schema provenance."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    server: str
    tool: str
    version: str
    schema: dict[str, Any]
    semantics_notes: str

    @property
    def hash(self) -> str:
        blob = json.dumps(
            {"v": self.version, "s": self.schema, "n": self.semantics_notes},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(blob).hexdigest()[:16]


@dataclass
class PinnedRegistry:
    """Host-side registry that pins the manifest hash the model reasoned over."""
    pinned: dict[tuple[str, str], ToolManifest] = field(default_factory=dict)

    def pin(self, m: ToolManifest) -> None:
        self.pinned[(m.server, m.tool)] = m

    def dispatch(
        self,
        server: str,
        tool: str,
        args: dict[str, Any],
        live_manifest: ToolManifest,
    ) -> dict[str, Any]:
        key = (server, tool)
        if key not in self.pinned:
            raise SchemaDriftError(
                f"no pinned manifest for {server}.{tool}; refusing to dispatch blind"
            )
        pinned = self.pinned[key]
        if pinned.hash != live_manifest.hash:
            # The model reasoned over `pinned`; the server will validate against `live`.
            # Dispatch would be schema-valid on both sides but semantically divergent.
            raise SchemaDriftError(
                f"schema drift on {server}.{tool}: model reasoned over {pinned.hash} "
                f"(v{pinned.version}), server now advertises {live_manifest.hash} "
                f"(v{live_manifest.version}). Re-negotiate before dispatch."
            )
        return {"dispatched_against": pinned.hash, "args": args}


@dataclass
class ProvenancedMemory:
    """Episodic store that refuses observations lacking (tool, schema_hash) provenance."""
    entries: list[dict[str, Any]] = field(default_factory=list)

    def record(self, observation: dict[str, Any], tool: str, schema_hash: str) -> None:
        if not tool or not schema_hash:
            raise UnversionedObservationError(
                "observation written without (tool, schema_hash) provenance; "
                "cannot be invalidated on future schema deprecation"
            )
        self.entries.append(
            {"obs": observation, "tool": tool, "schema_hash": schema_hash}
        )

    def invalidate_deprecated(self, deprecated_hashes: set[str]) -> int:
        before = len(self.entries)
        self.entries = [e for e in self.entries if e["schema_hash"] not in deprecated_hashes]
        return before - len(self.entries)
