# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-tool-manifest-whose-declared-schema-is-a-strict-superset-of-the-capability-it-actually-needs-to-execute.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-tool-manifest-whose-declared-schema-is-a-strict-superset-of-the-capability-it-actually-needs-to-execute.warrant.json
# Markdown SHA-256:   3b3e15a5ef4841d674d189cc4a5591ab4278de9463943c853c5de6f2647a38fb
# Code AST SHA-256:   a400bb9a400fcbd92c735f6ada7a7915b19a806fc7f80bef4af255708a65c8b0
# Verified Classes:   SchemaDriftOnResumeError, PinnedTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SchemaDriftOnResumeError(RuntimeError):
    """Raised when a checkpointed plan is resumed against a tool whose
    canonical schema hash differs from the hash pinned at plan construction."""


@dataclass(frozen=True)
class PinnedTool:
    name: str
    schema_hash: str
    schema: dict[str, Any]


def canonical_hash(schema: dict[str, Any]) -> str:
    # Canonical form: sorted keys, no whitespace, no float ambiguity.
    blob = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def pin_at_plan_time(tool: dict[str, Any]) -> PinnedTool:
    return PinnedTool(
        name=tool["name"],
        schema_hash=canonical_hash(tool["inputSchema"]),
        schema=tool["inputSchema"],
    )


def resume_plan(
    plan_tools: list[PinnedTool],
    live_manifest: dict[str, dict[str, Any]],
) -> list[PinnedTool]:
    """Re-validate a checkpointed plan against the live registry.

    Identity-stable resume (name + description only) is rejected here:
    a superset schema that adds callback_url or include_private passes
    name/description checks but changes the grammar the model will use
    on the next planning step.
    """
    revalidated: list[PinnedTool] = []
    for pinned in plan_tools:
        live = live_manifest.get(pinned.name)
        if live is None:
            raise SchemaDriftOnResumeError(
                f"tool {pinned.name!r} removed from registry mid-plan"
            )
        live_hash = canonical_hash(live["inputSchema"])
        if live_hash != pinned.schema_hash:
            added = set(live["inputSchema"].get("properties", {})) - set(
                pinned.schema.get("properties", {})
            )
            raise SchemaDriftOnResumeError(
                f"tool {pinned.name!r} schema drifted on resume: "
                f"pinned={pinned.schema_hash[:12]} live={live_hash[:12]} "
                f"added_properties={sorted(added)}"
            )
        revalidated.append(pinned)
    return revalidated
