# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-escalation-when-a-dynamic-tool-registry-re-registers-a-skill-name-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-escalation-when-a-dynamic-tool-registry-re-registers-a-skill-name-mid-session.warrant.json
# Markdown SHA-256:   7fd441d63b2f98a7777c21668b041926d71da13b255e1549fbf5c62e2a71486a
# Code AST SHA-256:   0502788bb62b0648f3c6654b9c2333fa800fe37c9390466646b4e45d9b3df6dc
# Verified Classes:   SkillBindingError, SkillHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillBindingError(RuntimeError):
    """Raised when a pinned skill handle no longer matches the live registry entry."""
    pass


@dataclass(frozen=True)
class SkillHandle:
    name: str
    version: str
    content_hash: str
    warrant: dict  # egress class, author, required-param set
    registry_generation: int


def resolve_handle(registry, name: str, planner_warrant: dict) -> SkillHandle:
    entry = registry.current(name)
    return SkillHandle(
        name=name,
        version=entry.version,
        content_hash=entry.content_hash,
        warrant=planner_warrant,
        registry_generation=registry.generation,
    )


def dispatch(registry, handle: SkillHandle, args: dict):
    live = registry.current(handle.name)

    # Invariant 1: content identity must match the body the planner reasoned about.
    if live.content_hash != handle.content_hash:
        raise SkillBindingError(
            f"content hash drift for {handle.name}: "
            f"pinned={handle.content_hash} live={live.content_hash}"
        )

    # Invariant 2: the trust warrant must be unchanged. Egress widening or
    # schema loosening (a previously-required param now optional) is an
    # injection signal, not a benign version bump.
    if live.warrant.get("egress") != handle.warrant.get("egress"):
        raise SkillBindingError(
            f"egress class changed for {handle.name}: "
            f"{handle.warrant.get('egress')} -> {live.warrant.get('egress')}"
        )
    if not set(handle.warrant.get("required", set())).issubset(live.required_params):
        raise SkillBindingError(
            f"schema loosened for {handle.name}: required params "
            f"{handle.warrant.get('required')} no longer enforced"
        )

    # Invariant 3: generation fencing — if the registry advanced since the
    # planner last observed it, the call is stale and must be re-justified.
    if registry.generation != handle.registry_generation:
        raise SkillBindingError(
            f"stale handle for {handle.name}: registry generation "
            f"{handle.registry_generation} -> {registry.generation}; bounce to planner"
        )

    return live.callable(**args)
