# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-skill-registry-reload-as-a-trust-boundary-transition-rather-than-a-cache-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-skill-registry-reload-as-a-trust-boundary-transition-rather-than-a-cache-refresh.warrant.json
# Markdown SHA-256:   4498928777064f89d7c1b436a66c2086cc291380688ed763a920bf9d6459059d
# Code AST SHA-256:   45b825c15eb707a1d98a563ea86127d7dc3d01c4c888ce30046eac7f1c99d3bc
# Verified Classes:   SkillInjectionError, SkillEntry, SkillRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Dict, Optional


class SkillInjectionError(RuntimeError):
    """Raised when a registry reload would admit an unvetted skill entry."""
    pass


@dataclass(frozen=True)
class SkillEntry:
    name: str
    entrypoint: str
    schema: str
    digest: str = field(default="")

    def compute_digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.name.encode())
        h.update(self.entrypoint.encode())
        h.update(self.schema.encode())
        return h.hexdigest()


class SkillRegistry:
    """Registry that enforces the trust-boundary invariant on reload.

    The init snapshot is the authority set. Any reload entry whose digest is
    absent from the init snapshot, or differs from the init snapshot's digest
    for that name, is quarantined and never becomes invocable without an
    explicit approval callback.
    """

    def __init__(self, init_entries: Dict[str, SkillEntry]):
        self._authority: Dict[str, str] = {
            name: e.compute_digest() for name, e in init_entries.items()
        }
        self._live: Dict[str, SkillEntry] = dict(init_entries)
        self._quarantine: Dict[str, SkillEntry] = {}

    def reload(
        self,
        incoming: Dict[str, SkillEntry],
        approve: Optional[Callable[[SkillEntry], bool]] = None,
    ) -> None:
        for name, entry in incoming.items():
            digest = entry.compute_digest()
            authorized = self._authority.get(name)

            if authorized is not None and authorized == digest:
                # Unchanged entry: safe to refresh in place.
                self._live[name] = entry
                continue

            if authorized is not None and authorized != digest:
                # Mutation of a known skill: quarantine, do not overwrite.
                self._quarantine[name] = entry
                self._live.pop(name, None)
                continue

            # New entry with no init-snapshot authority.
            if approve is not None and approve(entry):
                self._authority[name] = digest
                self._live[name] = entry
            else:
                self._quarantine[name] = entry

    def resolve(self, name: str) -> SkillEntry:
        if name in self._quarantine:
            raise SkillInjectionError(
                f"skill {name!r} is quarantined; refusing to invoke unvetted entry"
            )
        if name not in self._live:
            raise SkillInjectionError(f"skill {name!r} not present in live registry")
        entry = self._live[name]
        if self._authority.get(name) != entry.compute_digest():
            raise SkillInjectionError(
                f"skill {name!r} digest diverged from authority snapshot at invoke time"
            )
        return entry
