# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-capability-widening-via-mcp-inputschema-union-drift-and-the-pre-dispatch-warrant-check.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-capability-widening-via-mcp-inputschema-union-drift-and-the-pre-dispatch-warrant-check.warrant.json
# Markdown SHA-256:   679045350df72d6330dc167bccb018c5985638ae9409e70b6a0282221e846725
# Code AST SHA-256:   7c3b71b66894d0cf10f6eac9d1523c930154daedb1b773f74e63c987b200d23e
# Verified Classes:   ManifestWideningError, PinnedManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ManifestWideningError(RuntimeError):
    """Raised when a tool manifest widened between planning and dispatch."""
    pass


def _canonicalize(schema: dict[str, Any]) -> str:
    # Normalize key order and drop volatile fields so diffs are semantic.
    return json.dumps(schema, sort_keys=True, separators=(",", ":"))


def _schema_hash(schema: dict[str, Any]) -> str:
    return hashlib.sha256(_canonicalize(schema).encode()).hexdigest()


def _is_widening(old: dict[str, Any], new: dict[str, Any]) -> bool:
    """Structural widening check: any relaxation of constraints is widening."""
    if old.get("additionalProperties", True) is False and new.get("additionalProperties", True) is True:
        return True
    if old.get("pattern") and not new.get("pattern"):
        return True
    if old.get("enum") and not new.get("enum"):
        return True
    old_props = set(old.get("properties", {}))
    new_props = set(new.get("properties", {}))
    if new_props - old_props:  # new optional params appeared
        return True
    old_req = set(old.get("required", []))
    new_req = set(new.get("required", []))
    if old_req - new_req:  # a required constraint was dropped
        return True
    return False


@dataclass
class PinnedManifest:
    tool_name: str
    schema: dict[str, Any]
    digest: str


def assert_dispatch_warrant(
    pinned: PinnedManifest,
    dispatch_schema: dict[str, Any],
    planned_params: dict[str, Any],
    has_expansion_warrant: bool = False,
) -> None:
    """Invariant: never dispatch against an affordance surface not reasoned over."""
    dispatch_digest = _schema_hash(dispatch_schema)
    if dispatch_digest == pinned.digest:
        return  # surface unchanged, prior safety conclusion still valid

    if has_expansion_warrant:
        return  # a signed warrant, not the schema, is the authority

    if _is_widening(pinned.schema, dispatch_schema):
        # The planned call must not silently benefit from the widened surface.
        widened_keys = set(dispatch_schema.get("properties", {})) - set(
            pinned.schema.get("properties", {})
        )
        if widened_keys & set(planned_params):
            raise ManifestWideningError(
                f"tool {pinned.tool_name!r} widened to expose {sorted(widened_keys)} "
                f"and the planned call uses it; re-plan against the new manifest "
                f"before dispatch (pinned={pinned.digest[:12]} now={dispatch_digest[:12]})"
            )
        # Even if unused, a widening diff invalidates the prior safety conclusion.
        raise ManifestWideningError(
            f"tool {pinned.tool_name!r} widened between planning and dispatch "
            f"(pinned={pinned.digest[:12]} now={dispatch_digest[:12]}); "
            f"re-derive safety classification before proceeding"
        )
    # Narrowing diff: conservative, log and continue.


def dispatch(pinned: PinnedManifest, dispatch_schema: dict[str, Any],
             planned_params: dict[str, Any]) -> dict[str, Any]:
    assert_dispatch_warrant(pinned, dispatch_schema, planned_params)
    return {"status": "dispatched", "tool": pinned.tool_name}
