# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-pinned-mcp-tool-schema-after-a-signed-manifest-has-been-re-resolved-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-pinned-mcp-tool-schema-after-a-signed-manifest-has-been-re-resolved-mid-session.warrant.json
# Markdown SHA-256:   9a0cf89bd97ce7e14e4b0eee34269dac2d23a8694060561a9badff89ee9b26e0
# Code AST SHA-256:   d5e5cfb949f7ebc32b5f16fd700c23be091527009e47ce64ff3626f86201aa0a
# Verified Classes:   SchemaContinuityFault, PinnedTool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaContinuityFault(RuntimeError):
    """Raised when a live tool schema diverges from the pinned schema mid-context.

    This is NOT a tool execution error and MUST NOT be retried at the tool layer.
    It signals that the agent's plan was built against a schema that no longer
    describes the live tool. Propagate to the planner for re-pin or abort.
    """


@dataclass(frozen=True)
class PinnedTool:
    name: str
    structural_hash: str  # sha256 of canonical structural schema
    manifest_rev: str
    publisher_key_id: str


def canonical_structural_hash(schema: dict) -> str:
    """Hash only semantically load-bearing structure: types, required fields, enums.

    Strips descriptions, titles, examples, and key order so that cosmetic
    republication does not trip continuity. Any change to required-ness, type,
    or enum domain DOES change the hash.
    """
    def normalize(node):
        if isinstance(node, dict):
            keep = {}
            for k in ("type", "required", "enum", "items", "properties", "additionalProperties"):
                if k in node:
                    keep[k] = normalize(node[k])
            return keep
        if isinstance(node, list):
            return [normalize(x) for x in node]
        return node

    canon = json.dumps(normalize(schema), sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canon.encode("utf-8")).hexdigest()


def assert_schema_continuity(pinned: PinnedTool, live_schema: dict, live_rev: str) -> None:
    """Dispatch-time gate. Call before every tool invocation in a pinned context."""
    live_hash = canonical_structural_hash(live_schema)
    if live_hash != pinned.structural_hash:
        raise SchemaContinuityFault(
            f"Tool '{pinned.name}' schema drifted mid-context: "
            f"pinned={pinned.structural_hash[:12]}@{pinned.manifest_rev} "
            f"live={live_hash[:12]}@{live_rev}. "
            f"Plan built against pinned schema is invalid from this step. "
            f"Do not retry at tool layer; re-pin and re-plan or abort."
        )
