# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-s-idempotency-key-has-been-silently-rebound-to-a-different-tool-in-a-compensating-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-s-idempotency-key-has-been-silently-rebound-to-a-different-tool-in-a-compensating-swarm.warrant.json
# Markdown SHA-256:   1f6451dadde2dde0835db48935ea6b46190f518b642504a354deb504cc4f4e9c
# Code AST SHA-256:   331ac3f414b90b042749efcc1211fb954fcffb95f9453af11848f162cd499e13
# Verified Classes:   KeyRebindingError, Binding, BoundLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class KeyRebindingError(RuntimeError):
    """Raised when an idempotency key is presented with a tool/arg binding
    that differs from the binding recorded at mint time within the same epoch."""

@dataclass(frozen=True)
class Binding:
    tool_id: str
    arg_hash: str
    plan_epoch: str

def canonical_arg_hash(args: dict) -> str:
    items = "&".join(f"{k}={args[k]!r}" for k in sorted(args))
    return hashlib.sha256(items.encode()).hexdigest()

class BoundLedger:
    def __init__(self):
        self._bindings: dict[str, Binding] = {}
        self._committed: dict[str, dict] = {}

    def mint(self, key: str, tool_id: str, args: dict, epoch: str) -> Binding:
        b = Binding(tool_id, canonical_arg_hash(args), epoch)
        self._bindings[key] = b
        return b

    def resolve(self, key: str, tool_id: str, args: dict, epoch: str):
        stored = self._bindings.get(key)
        if stored is None:
            raise KeyRebindingError(f"unknown key {key!r} presented by {tool_id}")
        incoming = Binding(tool_id, canonical_arg_hash(args), epoch)
        if incoming == stored:
            return self._committed.get(key)  # true duplicate: cached payload
        if incoming.plan_epoch == stored.plan_epoch:
            raise KeyRebindingError(
                f"key {key!r} rebound within epoch {epoch!r}: "
                f"minted as {stored.tool_id}/{stored.arg_hash[:8]}, "
                f"presented as {incoming.tool_id}/{incoming.arg_hash[:8]}"
            )
        # cross-epoch reuse: old key must be orphaned, new key required
        raise KeyRebindingError(
            f"key {key!r} belongs to superseded epoch {stored.plan_epoch!r}; "
            f"mint a fresh key for epoch {epoch!r}"
        )

    def commit(self, key: str, payload: dict) -> None:
        self._committed[key] = payload
