# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-bind-a-dynamically-loaded-tool-manifest-the-post-negotiation-mutation-window-in-skill-injection-attacks.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-bind-a-dynamically-loaded-tool-manifest-the-post-negotiation-mutation-window-in-skill-injection-attacks.warrant.json
# Markdown SHA-256:   547bb3147753c6c7af9cf9b10005baf2ef8483bc53088cad9bcf4481b2458548
# Code AST SHA-256:   5607193fe0a6f44739d886e9868d8d3d0fc785bdfe5e0804dca4298d43845867
# Verified Classes:   ManifestDriftError, IntentHashMismatchError, ToolBinding, ToolCallIntent, AgentRuntime
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestDriftError(RuntimeError):
    """Raised when a tool descriptor mutates under a stable identifier."""


class IntentHashMismatchError(RuntimeError):
    """Raised when a tool-call intent is executed against a drifted binding."""


def descriptor_hash(descriptor: dict) -> str:
    # Hash the full instruction-bearing surface, not just name+schema.
    surface = {
        "name": descriptor["name"],
        "description": descriptor.get("description", ""),
        "input_schema": descriptor.get("input_schema", {}),
        "defaults": descriptor.get("defaults", {}),
        "examples": descriptor.get("examples", []),
        "enum_docs": descriptor.get("enum_docs", {}),
    }
    blob = json.dumps(surface, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class ToolBinding:
    name: str
    descriptor: dict
    negotiated_hash: str


@dataclass
class ToolCallIntent:
    tool_name: str
    args: dict
    formed_under_hash: str


@dataclass
class AgentRuntime:
    bindings: dict[str, ToolBinding] = field(default_factory=dict)

    def negotiate(self, descriptors: list[dict]) -> None:
        for d in descriptors:
            h = descriptor_hash(d)
            self.bindings[d["name"]] = ToolBinding(d["name"], d, h)

    def refresh(self, descriptors: list[dict]) -> None:
        # A refresh is a validation event. Drift is a new negotiation,
        # never a silent rebind.
        for d in descriptors:
            name = d["name"]
            incoming = descriptor_hash(d)
            existing = self.bindings.get(name)
            if existing is None:
                self.bindings[name] = ToolBinding(name, d, incoming)
                continue
            if existing.negotiated_hash != incoming:
                raise ManifestDriftError(
                    f"tool '{name}' descriptor drifted: "
                    f"{existing.negotiated_hash[:12]} -> {incoming[:12]}; "
                    f"refusing silent rebind, re-negotiation required"
                )

    def execute(self, intent: ToolCallIntent) -> dict:
        binding = self.bindings.get(intent.tool_name)
        if binding is None:
            raise IntentHashMismatchError(
                f"intent references unknown tool '{intent.tool_name}'"
            )
        if binding.negotiated_hash != intent.formed_under_hash:
            # The intent was reasoned about under a different descriptor.
            # Executing it now runs a different operation than intended.
            raise IntentHashMismatchError(
                f"intent for '{intent.tool_name}' formed under "
                f"{intent.formed_under_hash[:12]} but live binding is "
                f"{binding.negotiated_hash[:12]}; refusing execution"
            )
        return {"tool": intent.tool_name, "args": intent.args, "status": "ok"}
