# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-tool-call-whose-declared-capability-schema-was-mutated-in-flight-between-manifest-fetch-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-tool-call-whose-declared-capability-schema-was-mutated-in-flight-between-manifest-fetch-and-invocation.warrant.json
# Markdown SHA-256:   74198534e8a43efa41c28cdf8c2cad52892be585ffaa6d43f782c0830b7426d1
# Code AST SHA-256:   4fa96847e4933fcc67c24d6f61e17a1fd56bc47d1b3d3bc45d5c33cbc52554c9
# Verified Classes:   ManifestDriftError, CapabilityEscalationError, ManifestPin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when the tool manifest in force at execution differs from the
    manifest the agent planned against. Fail-closed: the call must not proceed."""


class CapabilityEscalationError(ManifestDriftError):
    """Raised when drift specifically widens side-effect class (e.g. read-only
    hint dropped, or a write parameter added) — a strictly worse subclass."""


@dataclass(frozen=True)
class ManifestPin:
    tool_name: str
    schema_hash: str
    read_only: bool
    param_names: frozenset


def hash_manifest(tool: dict) -> str:
    # Canonical, order-independent hash of the security-relevant fields only.
    # Description is included because it is the injection surface.
    relevant = {
        "name": tool["name"],
        "description": tool.get("description", ""),
        "inputSchema": tool.get("inputSchema", {}),
        "readOnlyHint": tool.get("annotations", {}).get("readOnlyHint", False),
    }
    blob = json.dumps(relevant, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def pin_at_plan_time(tool: dict) -> ManifestPin:
    return ManifestPin(
        tool_name=tool["name"],
        schema_hash=hash_manifest(tool),
        read_only=tool.get("annotations", {}).get("readOnlyHint", False),
        param_names=frozenset(tool.get("inputSchema", {}).get("properties", {}).keys()),
    )


def verify_before_call(pin: ManifestPin, current_tool: dict) -> None:
    """Called immediately before tools/call is dispatched. Must run in the
    harness, not in the model's reasoning, because the model's belief is
    exactly what the attacker mutated."""
    if current_tool["name"] != pin.tool_name:
        raise ManifestDriftError(
            f"tool identity changed: planned {pin.tool_name!r}, "
            f"server now serves {current_tool['name']!r}"
        )

    current_hash = hash_manifest(current_tool)
    if current_hash == pin.schema_hash:
        return  # invariant holds: plan-time schema == execution-time schema

    # Drift detected. Classify it before raising, so the audit log records
    # whether this was also a capability escalation.
    current_ro = current_tool.get("annotations", {}).get("readOnlyHint", False)
    current_params = frozenset(
        current_tool.get("inputSchema", {}).get("properties", {}).keys()
    )
    escalated = (pin.read_only and not current_ro) or bool(
        current_params - pin.param_names
    )

    detail = (
        f"manifest for {pin.tool_name!r} mutated in-flight: "
        f"planned_hash={pin.schema_hash[:12]} current_hash={current_hash[:12]} "
        f"read_only {pin.read_only}->{current_ro} "
        f"params {sorted(pin.param_names)}->{sorted(current_params)}"
    )
    if escalated:
        raise CapabilityEscalationError(detail + " [capability widened]")
    raise ManifestDriftError(detail)


def dispatch_tool_call(pin: ManifestPin, current_tool: dict, args: dict) -> dict:
    # verify first; never send the JSON-RPC request on mismatch
    verify_before_call(pin, current_tool)
    # ... send tools/call here ...
    return {"ok": True}
