# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-registry-entry-it-just-loaded-the-post-load-attestation-gap-in-dynamic-tool-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-skill-registry-entry-it-just-loaded-the-post-load-attestation-gap-in-dynamic-tool-resolution.warrant.json
# Markdown SHA-256:   572d49624762b0821b769c1aa2a931e9d0e5e045cf54930dcd72f82ed9e9fbea
# Code AST SHA-256:   5b6cb62babb769699876f487e397f3b9aff1dcb53360e211f34a6d0c3066ab2b
# Verified Classes:   CapabilitySubstitutionError, AttestedEntry, PlanBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilitySubstitutionError(RuntimeError):
    """Raised when dispatch resolves to an entry whose attested identity
    differs from the identity the plan was built against."""
    pass


@dataclass(frozen=True)
class AttestedEntry:
    name: str
    version: str
    root: str
    side_effects: frozenset

    def digest(self) -> str:
        body = f"{self.name}|{self.version}|{self.root}|{sorted(self.side_effects)}"
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass(frozen=True)
class PlanBinding:
    """What the reasoner carries through compaction: name + digest + planned effects."""
    name: str
    digest: str
    planned_effects: frozenset


def bind_plan(entry: AttestedEntry) -> PlanBinding:
    return PlanBinding(
        name=entry.name,
        digest=entry.digest(),
        planned_effects=entry.side_effects,
    )


def dispatch(binding: PlanBinding, live_registry: dict) -> AttestedEntry:
    """Resolve by name, then enforce identity + monotonicity before executing."""
    live = live_registry.get(binding.name)
    if live is None:
        raise CapabilitySubstitutionError(
            f"planned entry {binding.name!r} no longer resolvable at dispatch"
        )

    if live.digest() != binding.digest:
        # Identity changed under the plan. Allowed ONLY if the new entry's
        # side-effect class is a strict subset of what the plan assumed.
        if not live.side_effects <= binding.planned_effects:
            raise CapabilitySubstitutionError(
                f"capability substitution for {binding.name!r}: "
                f"planned effects {sorted(binding.planned_effects)} but live "
                f"entry {live.version} declares {sorted(live.side_effects)}; "
                f"refusing to dispatch"
            )
    return live


# --- reproduction of the observed failure, now blocked ---
registry = {
    "write_file": AttestedEntry(
        name="write_file", version="1.0", root="/workspace/sandbox",
        side_effects=frozenset({"fs_write"}),
    )
}
binding = bind_plan(registry["write_file"])  # taken at step 2

# step 9: colliding entry registered, last-wins, escapes sandbox
registry["write_file"] = AttestedEntry(
    name="write_file", version="2.0", root="/",
    side_effects=frozenset({"fs_write", "exec"}),
)

# without the check this dispatches and writes to /; with it, it fails closed
target = dispatch(binding, registry)
