# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-unsigned-skill-manifests-from-mutating-a-live-agent-tool-registry-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-unsigned-skill-manifests-from-mutating-a-live-agent-tool-registry-mid-episode.warrant.json
# Markdown SHA-256:   3e4c9389355f2fd8024061383be67d06cc29f0dccc8224604f93530b7ed48e7a
# Code AST SHA-256:   ea94cbd36ad1cb4cea5719f51fdcd5705f18f5f5c64557032541c97647d9c706
# Verified Classes:   RegistryDriftError, ToolRef
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class RegistryDriftError(RuntimeError):
    """Raised when a tool call resolves outside the episode's pinned registry snapshot."""


@dataclass(frozen=True)
class ToolRef:
    name: str
    content_hash: str
    schema_digest: str


def snapshot_id(tools: list[ToolRef]) -> str:
    payload = "|".join(
        f"{t.name}:{t.content_hash}:{t.schema_digest}"
        for t in sorted(tools, key=lambda t: t.name)
    )
    return hashlib.sha256(payload.encode()).hexdigest()


def resolve_call(
    pinned: dict[str, ToolRef],
    pinned_snapshot_id: str,
    live_snapshot_id: str,
    requested_name: str,
    requested_hash: str,
    call_snapshot_id: str,
) -> ToolRef:
    if call_snapshot_id != pinned_snapshot_id:
        raise RegistryDriftError(
            f"call carried snapshot {call_snapshot_id!r}, episode pinned {pinned_snapshot_id!r}"
        )
    if live_snapshot_id != pinned_snapshot_id:
        raise RegistryDriftError(
            f"live registry drifted to {live_snapshot_id!r}; halt and re-plan at checkpoint"
        )
    ref = pinned.get(requested_name)
    if ref is None:
        raise RegistryDriftError(f"tool {requested_name!r} not in pinned snapshot")
    if ref.content_hash != requested_hash:
        raise RegistryDriftError(
            f"name collision: {requested_name!r} pinned {ref.content_hash!r}, "
            f"call requested {requested_hash!r}"
        )
    return ref
