# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-shadowing-drift-when-a-lazily-reloaded-mcp-tool-registry-silently-rebinds-a-previously-warranted-tool-name.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-shadowing-drift-when-a-lazily-reloaded-mcp-tool-registry-silently-rebinds-a-previously-warranted-tool-name.warrant.json
# Markdown SHA-256:   ee901b61bb8243c0d3d04333e0b4c0c3ec7abe11ec58c627a5223c8e287b6286
# Code AST SHA-256:   7b547effdf9eb5bb9b9e2eed1503c539f22463d318fdef761450f18ca5611cba
# Verified Classes:   CapabilityShadowError, ToolManifest, ToolWarrant, Registry, ExecutionGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilityShadowError(RuntimeError):
    """Raised when a tool name resolves to a manifest generation
    different from the one the current plan was warranted against."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    schema: dict
    origin: str
    side_effect_class: str

    def digest(self) -> str:
        payload = json.dumps(
            {"schema": self.schema,
             "origin": self.origin,
             "side_effect_class": self.side_effect_class},
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class ToolWarrant:
    name: str
    digest: str
    origin: str


@dataclass
class Registry:
    _manifests: dict = field(default_factory=dict)

    def load(self, manifest: ToolManifest) -> None:
        self._manifests[manifest.name] = manifest

    def resolve(self, name: str) -> ToolManifest:
        return self._manifests[name]


class ExecutionGate:
    """Enforces the (name, digest, origin) invariant at call time."""

    def __init__(self, registry: Registry):
        self.registry = registry

    def warrant(self, name: str) -> ToolWarrant:
        m = self.registry.resolve(name)
        return ToolWarrant(name=m.name, digest=m.digest(), origin=m.origin)

    def execute(self, warrant: ToolWarrant, args: dict) -> dict:
        current = self.registry.resolve(warrant.name)
        if current.digest() != warrant.digest or current.origin != warrant.origin:
            raise CapabilityShadowError(
                f"tool '{warrant.name}' rebound since warrant: "
                f"warranted digest={warrant.digest[:12]} origin={warrant.origin}, "
                f"current digest={current.digest()[:12]} origin={current.origin}; "
                f"re-warrant required before execution"
            )
        return {"tool": warrant.name, "args": args, "status": "executed"}


def run_plan(gate: ExecutionGate, plan: list) -> list:
    """A plan is a list of (warrant, args). Any shadow aborts the plan."""
    results = []
    for warrant, args in plan:
        results.append(gate.execute(warrant, args))
    return results


# --- reproduction of the observed trace ---
registry = Registry()
registry.load(ToolManifest(
    name="run_tests",
    schema={"command": {"enum": ["unit", "lint", "integration"]}},
    origin="local-runner-v1",
    side_effect_class="local-exec",
))
gate = ExecutionGate(registry)

# Agent plans against the v1 contract and holds the warrant across a checkpoint.
planned_warrant = gate.warrant("run_tests")

# Lazy reload between checkpoint and resume: same name, new contract.
registry.load(ToolManifest(
    name="run_tests",
    schema={"command": {"type": "string"}},   # free-form shell
    origin="remote-runner-v2",
    side_effect_class="network-exec",
))

# Turn 41: agent re-issues the call believing the old enum guard still holds.
try:
    run_plan(gate, [(planned_warrant, {"command": "pytest --co -q"})])
except CapabilityShadowError as e:
    # Correct behavior: hard stop, re-warrant, do not execute.
    print(f"BOUNDED: {e}")
