# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-skill-manifest-and-keep-executing-after-the-schema-it-validated-against-has-been-swapped.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-skill-manifest-and-keep-executing-after-the-schema-it-validated-against-has-been-swapped.warrant.json
# Markdown SHA-256:   985c55d03543d1a2a9f3d857dd4c103b8020e69e0c7a99c6c80f44c8a9956866
# Code AST SHA-256:   6235befcd80bac50cc52d52a93f23bf35a847dafd6ad865d76b9390145a9dfee
# Verified Classes:   SchemaDriftError, Manifest, PinnedCatalog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftError(RuntimeError):
    """Raised when a tool call is constructed against a schema that no longer
    matches the manifest the execution endpoint will validate against."""


@dataclass(frozen=True)
class Manifest:
    tool: str
    params: dict
    description: str

    def hash(self) -> str:
        canonical = json.dumps(
            {"tool": self.tool, "params": self.params, "description": self.description},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode()).hexdigest()


class PinnedCatalog:
    """Holds the manifest hash the planner was last validated against and
    refuses to let a call leave if the live manifest has drifted."""

    def __init__(self, live_fetch):
        self._fetch = live_fetch
        self._pinned: dict[str, str] = {}

    def pin(self, tool: str) -> str:
        h = self._fetch(tool).hash()
        self._pinned[tool] = h
        return h

    def build_call(self, tool: str, args: dict) -> dict:
        live = self._fetch(tool)
        pinned_hash = self._pinned.get(tool)
        if pinned_hash is None:
            raise SchemaDriftError(f"tool {tool!r} was never pinned before use")
        if live.hash() != pinned_hash:
            raise SchemaDriftError(
                f"manifest for {tool!r} drifted mid-session: "
                f"pinned {pinned_hash[:12]}… live {live.hash()[:12]}…; "
                f"refusing to emit call constructed from stale schema"
            )
        unknown = set(args) - set(live.params)
        if unknown:
            # A tolerant server would silently drop these and apply a default.
            raise SchemaDriftError(
                f"call to {tool!r} carries fields absent from live schema: {sorted(unknown)}"
            )
        return {
            "tool": tool,
            "args": args,
            "schema_hash": pinned_hash,
            # Descriptions are data, never instructions.
            "description_is_untrusted": True,
        }


def execute(catalog: PinnedCatalog, tool: str, args: dict) -> dict:
    call = catalog.build_call(tool, args)
    # ... transport send ...
    return call
