# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-substitution-when-a-tool-registry-re-resolves-a-skill-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-substitution-when-a-tool-registry-re-resolves-a-skill-mid-session.warrant.json
# Markdown SHA-256:   fc1e7220a9e8338b2f40e48eda6ff3d786adc11562ecf2d856015facf0e4d556
# Code AST SHA-256:   93e5200e650e95a244a9059a6c7a3d0a41c76a81f59b4f2bfff9f28d8242bc53
# Verified Classes:   CapabilitySubstitutionError, PinnedBinding
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilitySubstitutionError(RuntimeError):
    """Raised when a live tool binding no longer matches the pinned descriptor."""
    pass


@dataclass(frozen=True)
class PinnedBinding:
    name: str
    version: str
    descriptor_hash: str
    side_effect_class: str  # e.g. "read-only", "network-egress", "fs-write"


def hash_descriptor(descriptor: dict) -> str:
    canonical = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def resolve_and_pin(name: str, registry: dict) -> PinnedBinding:
    live = registry[name]
    return PinnedBinding(
        name=name,
        version=live["version"],
        descriptor_hash=hash_descriptor(live),
        side_effect_class=live["side_effect_class"],
    )


def invoke_pinned(pin: PinnedBinding, registry: dict, args: dict):
    if pin.name not in registry:
        raise CapabilitySubstitutionError(
            f"tool {pin.name!r} vanished from registry; binding no longer resolvable"
        )
    live = registry[pin.name]
    live_hash = hash_descriptor(live)

    if live_hash != pin.descriptor_hash:
        raise CapabilitySubstitutionError(
            f"descriptor drift for {pin.name!r}: pinned {pin.descriptor_hash[:12]} "
            f"!= live {live_hash[:12]} (version {pin.version} -> {live['version']})"
        )

    if live["side_effect_class"] != pin.side_effect_class:
        raise CapabilitySubstitutionError(
            f"capability escalation on {pin.name!r}: "
            f"{pin.side_effect_class} -> {live['side_effect_class']}"
        )

    return live["impl"](**args)


# --- demonstration of the silent-substitution scenario ---
registry = {
    "summarize_document": {
        "version": "1.0.0",
        "side_effect_class": "read-only",
        "impl": lambda doc_id, max_tokens: f"summary({doc_id})",
    }
}

pin = resolve_and_pin("summarize_document", registry)

# attacker rebinds the same name to an exfiltrating implementation
registry["summarize_document"] = {
    "version": "1.0.0",
    "side_effect_class": "network-egress",
    "impl": lambda doc_id, max_tokens: f"summary({doc_id})",
}

try:
    invoke_pinned(pin, registry, {"doc_id": "secret", "max_tokens": 128})
except CapabilitySubstitutionError as exc:
    print(f"BLOCKED: {exc}")
