# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-dynamically-loaded-skill-by-name-after-a-registry-mutation-and-the-descriptor-to-handler-binding-is-re-hydrat.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-dynamically-loaded-skill-by-name-after-a-registry-mutation-and-the-descriptor-to-handler-binding-is-re-hydrat.warrant.json
# Markdown SHA-256:   962af67563a75024a6906207f36056abc264bcf850c604336a943eb8866377f0
# Code AST SHA-256:   7e81cee728d3c0b0468d9c57d4e4614a9fae51b69fb66fe059a6cfe9043b0c71
# Verified Classes:   SkillIdentityMismatch, SkillDescriptor, PendingCall, SkillRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any, Callable


class SkillIdentityMismatch(RuntimeError):
    """Raised when a pending skill call resolves to a descriptor whose
    identity differs from the one the planner reasoned about."""
    pass


@dataclass(frozen=True)
class SkillDescriptor:
    name: str
    schema: dict[str, Any]
    handler_digest: str

    def identity(self) -> str:
        payload = f"{self.name}|{sorted(self.schema.items())}|{self.handler_digest}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class PendingCall:
    name: str
    args: dict[str, Any]
    planned_identity: str  # captured at plan time


class SkillRegistry:
    def __init__(self) -> None:
        self._descriptors: dict[str, SkillDescriptor] = {}
        self._handlers: dict[str, Callable[..., Any]] = {}

    def register(self, desc: SkillDescriptor, handler: Callable[..., Any]) -> None:
        # A mutation (including additive schema changes) changes identity.
        self._descriptors[desc.name] = desc
        self._handlers[desc.name] = handler

    def resolve(self, name: str) -> tuple[SkillDescriptor, Callable[..., Any]]:
        if name not in self._descriptors:
            raise SkillIdentityMismatch(f"skill {name!r} no longer present in registry")
        return self._descriptors[name], self._handlers[name]


def plan_call(registry: SkillRegistry, name: str, args: dict[str, Any]) -> PendingCall:
    desc, _ = registry.resolve(name)
    return PendingCall(name=name, args=args, planned_identity=desc.identity())


def dispatch(registry: SkillRegistry, call: PendingCall) -> Any:
    desc, handler = registry.resolve(call.name)
    if desc.identity() != call.planned_identity:
        # Additive schema change or handler swap across the plan-execute boundary.
        raise SkillIdentityMismatch(
            f"descriptor identity changed for {call.name!r}: "
            f"planned {call.planned_identity[:12]}.. "
            f"resolved {desc.identity()[:12]}.."
        )
    return handler(**call.args)


# --- Demonstrating the failure and the guardrail ---

def _send_v1(to: str, subject: str, body: str) -> str:
    return f"sent to {to}"

def _send_v2(to: str, subject: str, body: str, bcc: str | None = None) -> str:
    return f"sent to {to} bcc={bcc}"

reg = SkillRegistry()
reg.register(
    SkillDescriptor("send_email", {"to": "str", "subject": "str", "body": "str"}, "h0"),
    _send_v1,
)

call = plan_call(reg, "send_email", {"to": "alice@corp", "subject": "Q3", "body": "..."})

# Registry mutation inside the plan-to-dispatch window (hot-reload / attacker publish).
reg.register(
    SkillDescriptor(
        "send_email",
        {"to": "str", "subject": "str", "body": "str", "bcc": "str?"},
        "h1",
    ),
    _send_v2,
)

try:
    dispatch(reg, call)
except SkillIdentityMismatch as exc:
    print(f"BLOCKED: {exc}")
