# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-hot-load-a-tool-whose-capability-manifest-is-self-attested-and-how-does-post-load-schema-mutation-byp.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-hot-load-a-tool-whose-capability-manifest-is-self-attested-and-how-does-post-load-schema-mutation-byp.warrant.json
# Markdown SHA-256:   e7a4ab8199d0d9ff74c23e88839465421d97e545cf387d0d189f279b9d6654d5
# Code AST SHA-256:   0ffe9aa243c849d64c6a3bb2fa62549d3213f4cb4ce04da3b93081515bd2ad3e
# Verified Classes:   ManifestMutationError, SchemaPin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestMutationError(RuntimeError):
    """Raised when a tool's manifest or schema changed after the planner's trust decision."""
    pass


@dataclass(frozen=True)
class SchemaPin:
    tool_id: str
    manifest_sha256: str
    schema_sha256: str


def _hash(obj) -> str:
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()


def pin_at_plan_time(tool_id: str, manifest: dict) -> SchemaPin:
    return SchemaPin(
        tool_id=tool_id,
        manifest_sha256=_hash(manifest),
        schema_sha256=_hash(manifest["schema"]),
    )


def dispatch_with_pin(pin: SchemaPin, live_manifest: dict, args: dict) -> dict:
    live_manifest_hash = _hash(live_manifest)
    live_schema_hash = _hash(live_manifest["schema"])

    if live_manifest_hash != pin.manifest_sha256:
        raise ManifestMutationError(
            f"tool {pin.tool_id!r}: manifest mutated after plan "
            f"(pinned {pin.manifest_sha256[:12]}, live {live_manifest_hash[:12]}); "
            f"trust classification is stale, re-plan required"
        )
    if live_schema_hash != pin.schema_sha256:
        raise ManifestMutationError(
            f"tool {pin.tool_id!r}: schema mutated after plan "
            f"(pinned {pin.schema_sha256[:12]}, live {live_schema_hash[:12]}); "
            f"argument contract invalidated"
        )

    declared = set(live_manifest["schema"].get("properties", {}).keys())
    supplied = set(args.keys())
    undeclared = supplied - declared
    if undeclared:
        raise ManifestMutationError(
            f"tool {pin.tool_id!r}: args {sorted(undeclared)} not in pinned schema"
        )

    return {"tool_id": pin.tool_id, "args": args, "schema_sha256": live_schema_hash}
