# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-registry-resident-skill-that-mutates-its-own-capability-manifest-between-load-and-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-registry-resident-skill-that-mutates-its-own-capability-manifest-between-load-and-first-invocation.warrant.json
# Markdown SHA-256:   09ce813fa949ab4c4391e7070b309927bc989bcd5126cdd8898aa910d091d6a0
# Code AST SHA-256:   a661d054fcaff77f90b77b8ba325cf079582a36c6726fe67bd4b06609e3c8c7f
# Verified Classes:   DescriptorDriftError, Descriptor, PinnedRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptorDriftError(RuntimeError):
    """Raised when the live registry descriptor no longer matches the
    descriptor the agent reasoned over at plan time."""


@dataclass(frozen=True)
class Descriptor:
    name: str
    schema: dict
    declared_side_effect: str  # e.g. "read_only", "writes_fs", "network"

    def content_hash(self) -> str:
        payload = repr((self.name, sorted(self.schema.items()),
                        self.declared_side_effect)).encode()
        return hashlib.sha256(payload).hexdigest()


class PinnedRegistry:
    """Registry that refuses to serve a descriptor whose content has drifted
    from the hash the caller pinned at plan time."""

    def __init__(self, entries: dict[str, Descriptor]):
        self._entries = dict(entries)

    def mutate(self, name: str, new: Descriptor) -> None:
        # Simulates a hot-reload / publisher push between load and invoke.
        self._entries[name] = new

    def invoke(self, name: str, pinned_hash: str, args: dict) -> dict:
        live = self._entries.get(name)
        if live is None:
            raise DescriptorDriftError(f"skill {name!r} vanished from registry")
        if live.content_hash() != pinned_hash:
            raise DescriptorDriftError(
                f"skill {name!r} descriptor drifted between load and invoke: "
                f"pinned={pinned_hash[:12]} live={live.content_hash()[:12]} "
                f"side_effect {live.declared_side_effect!r} differs from plan"
            )
        # Only reached when the descriptor the agent reasoned over is the one
        # that executes. Dispatch is now safe to perform.
        return {"name": name, "args": args, "executed_side_effect": live.declared_side_effect}


def plan_and_invoke(registry: PinnedRegistry, name: str, args: dict) -> dict:
    # Load-time: agent reads descriptor and pins its content hash.
    loaded = registry._entries[name]
    pinned = loaded.content_hash()
    # ... agent reasons over `loaded`, builds `args`, logs side-effect class ...

    # Attack window: registry mutates to a schema-superset with new side effect.
    registry.mutate(name, Descriptor(
        name=name,
        schema={**loaded.schema, "output_path": {"type": "string"}},
        declared_side_effect="writes_fs",
    ))

    # Invoke-time: pin is enforced, drift is caught before dispatch.
    return registry.invoke(name, pinned, args)
