# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-tool-registry-swap-that-silently-rebinds-a-trusted-skill-name-to-an-injected-handler.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-tool-registry-swap-that-silently-rebinds-a-trusted-skill-name-to-an-injected-handler.warrant.json
# Markdown SHA-256:   c6ebd203a930c56940891c06b3a9746dba7818d852eb7b75936452b356d11568
# Code AST SHA-256:   afabc020b8397e1cc7ae9c058d4d4986fc3f4cc9838cebba301772d7492235e9
# Verified Classes:   SkillBindingViolation, ResolvedSkill
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillBindingViolation(RuntimeError):
    """Raised when a skill name resolves to a handler whose content hash
    differs from the hash the agent bound when it reasoned about the skill."""


@dataclass(frozen=True)
class ResolvedSkill:
    name: str
    version: str
    handler: str
    content_hash: str


def resolve_and_verify(
    name: str,
    bound: ResolvedSkill,
    live_registry: dict[str, ResolvedSkill],
) -> ResolvedSkill:
    """Call-time gate: the name must still map to the exact identity the
    agent planned against. A version bump or handler swap under a stable
    name is a continuity violation, not a retryable miss."""
    live = live_registry.get(name)
    if live is None:
        raise SkillBindingViolation(
            f"skill {name!r} vanished from registry after binding "
            f"(bound hash {bound.content_hash[:12]})"
        )
    expected = hashlib.sha256(
        f"{live.version}|{live.handler}".encode()
    ).hexdigest()
    if live.content_hash != bound.content_hash or expected != bound.content_hash:
        raise SkillBindingViolation(
            f"skill {name!r} rebound beneath live plan: "
            f"bound {bound.version}/{bound.content_hash[:12]} -> "
            f"live {live.version}/{live.content_hash[:12]}; "
            f"invalidate all plan steps referencing this name and re-plan"
        )
    return live


def invoke(bound: ResolvedSkill, registry: dict[str, ResolvedSkill], args: dict) -> dict:
    live = resolve_and_verify(bound.name, bound, registry)
    # Only reached if identity is unchanged; dispatch to the verified handler.
    return {"handler": live.handler, "args": args}
