# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-unsigned-skill-manifest-substitution-during-hot-reload-of-an-agent-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-unsigned-skill-manifest-substitution-during-hot-reload-of-an-agent-tool-registry.warrant.json
# Markdown SHA-256:   490e6c0ddad404681f15b3e833afbe623115f78c15031176c050521f06d4ee77
# Code AST SHA-256:   38299a525316383ee72f74ddcd96e3fa82bcab09c8083d6a5e34e07234b0b9cb
# Verified Classes:   ManifestSubstitutionError, ToolManifest, EpisodeToolLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class ManifestSubstitutionError(RuntimeError):
    """Raised when a reloaded tool manifest diverges from the digest the
    model was conditioned on during the current episode."""


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    input_schema: Mapping
    handler_ref: str

    def canonical_digest(self) -> str:
        body = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "input_schema": self.input_schema,
                "handler_ref": self.handler_ref,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(body).hexdigest()


class EpisodeToolLedger:
    """Records the digest of every tool the model was conditioned on.
    Hot-reload must consult this before swapping any handler."""

    def __init__(self) -> None:
        self._pinned: dict[str, str] = {}

    def pin(self, manifest: ToolManifest) -> None:
        self._pinned[manifest.name] = manifest.canonical_digest()

    def verify_reload(self, incoming: ToolManifest) -> None:
        pinned = self._pinned.get(incoming.name)
        if pinned is None:
            # Tool not referenced this episode: safe to stage.
            return
        current = incoming.canonical_digest()
        if current != pinned:
            raise ManifestSubstitutionError(
                f"tool '{incoming.name}' digest changed mid-episode: "
                f"pinned={pinned[:12]} incoming={current[:12]}; "
                f"refusing handler swap — requires episode reset"
            )


def hot_reload(
    ledger: EpisodeToolLedger,
    incoming: list[ToolManifest],
) -> dict[str, str]:
    """Returns dispatch table only if every referenced tool is digest-stable.
    Fails closed on any substitution of a conditioned tool."""
    dispatch: dict[str, str] = {}
    for manifest in incoming:
        ledger.verify_reload(manifest)
        dispatch[manifest.name] = manifest.handler_ref
    return dispatch
