# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-shadowing-in-dynamically-loaded-tool-registries-where-a-late-bound-skill-silently-overrides-a-trusted-tool-s.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-shadowing-in-dynamically-loaded-tool-registries-where-a-late-bound-skill-silently-overrides-a-trusted-tool-s.warrant.json
# Markdown SHA-256:   99e7479077b6e7e63d368ef25fc6f7c95706be6529caf4b9aea5ca5d3c12d6fd
# Code AST SHA-256:   30afd348bbc96f377b738a016f2b1bb3cdf520f852d8845128a362d02f80d89e
# Verified Classes:   ContractShadowed, ContractHandle, FrozenRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ContractShadowed(RuntimeError):
    """Raised when a live tool name resolves to a different binding identity
    than the one the planner was issued at session start."""
    pass


@dataclass(frozen=True)
class ContractHandle:
    name: str
    schema_digest: str
    impl_digest: str
    signer: str

    def identity(self) -> str:
        blob = f"{self.name}|{self.schema_digest}|{self.impl_digest}|{self.signer}"
        return hashlib.sha256(blob.encode()).hexdigest()


class FrozenRegistry:
    """Session-frozen binding table. Names map to immutable contract handles.
    Late loads may ADD names; they may not REBIND a live name without a
    signed rebind warrant."""

    def __init__(self, initial: dict[str, ContractHandle]):
        self._bindings = dict(initial)

    def issue(self, name: str) -> ContractHandle:
        if name not in self._bindings:
            raise KeyError(f"unknown tool {name!r}")
        return self._bindings[name]

    def load(self, handle: ContractHandle, rebind_warrant: str | None = None) -> None:
        incumbent = self._bindings.get(handle.name)
        if incumbent is None:
            self._bindings[handle.name] = handle          # additive: safe
            return
        if incumbent.identity() == handle.identity():
            return                                        # idempotent
        if rebind_warrant is None:
            raise ContractShadowed(
                f"refusing to rebind live name {handle.name!r}: "
                f"incumbent={incumbent.identity()[:12]} "
                f"candidate={handle.identity()[:12]} "
                f"(schema match does not authorize substitution)"
            )
        self._bindings[handle.name] = handle              # explicit, signed


def dispatch(registry: FrozenRegistry, planned: ContractHandle, args: dict) -> str:
    """Resolve by identity, not by name. Fail closed on any drift."""
    resolved = registry.issue(planned.name)
    if resolved.identity() != planned.identity():
        raise ContractShadowed(
            f"dispatch of {planned.name!r} blocked: planner held "
            f"{planned.identity()[:12]} but registry now resolves "
            f"{resolved.identity()[:12]}"
        )
    return f"executed {planned.name} with {sorted(args)}"
