# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-description-schema-as-executable-code-rather-than-as-a-contract-and-refuse-to-bind-a-tool-whose-parame.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-description-schema-as-executable-code-rather-than-as-a-contract-and-refuse-to-bind-a-tool-whose-parame.warrant.json
# Markdown SHA-256:   f88a05fbb5c3b561308ef88fc7794a45dddad80d344769ac9f6f5a36113fec71
# Code AST SHA-256:   9346de49c2db80376d35992b95e899a26bbe3dabde812ce402dbce392ff4d510
# Verified Classes:   SchemaDivergenceError, PinnedSchema
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SchemaDivergenceError(RuntimeError):
    """Raised when a tool schema mutates between discovery and invocation."""
    pass


@dataclass(frozen=True)
class PinnedSchema:
    tool_name: str
    digest: str
    frozen: dict[str, Any]


def _digest(schema: dict[str, Any]) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def pin_at_discovery(tool_name: str, schema: dict[str, Any]) -> PinnedSchema:
    return PinnedSchema(tool_name=tool_name, digest=_digest(schema), frozen=schema)


def bind_arguments(
    pinned: PinnedSchema,
    fresh_schema: dict[str, Any],
    proposed_args: dict[str, Any],
) -> dict[str, Any]:
    """Bind arguments only if the fresh schema matches the pinned one.

    Any divergence — description, enum, default, or parameter set — aborts
    the call and forces re-planning against the new schema. The model must
    re-read mutated free-text before it can influence argument construction.
    """
    fresh_digest = _digest(fresh_schema)

    if fresh_digest != pinned.digest:
        raise SchemaDivergenceError(
            f"Tool '{pinned.tool_name}' schema mutated between discovery "
            f"({pinned.digest[:12]}) and invocation ({fresh_digest[:12]}). "
            f"Refusing to bind arguments; re-plan required."
        )

    allowed = set(fresh_schema.get("properties", {}).keys())
    stray = set(proposed_args.keys()) - allowed
    if stray:
        raise SchemaDivergenceError(
            f"Arguments reference fields absent from pinned schema: {sorted(stray)}"
        )

    return proposed_args
