# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-hot-reloads-a-tool-registry-mid-task-the-unvalidated-schema-annotation-channel-as-a-skill-injection-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-hot-reloads-a-tool-registry-mid-task-the-unvalidated-schema-annotation-channel-as-a-skill-injection-surface.warrant.json
# Markdown SHA-256:   cfeb74c1425481765d84403f92005830ebd7fdc4e3d4fd61c3479f570b419734
# Code AST SHA-256:   987d590ba517a297e9a3e000519f7e4ed5b268b28e30fcfbfb3228a34d92b3c7
# Verified Classes:   RegistryInjectionError, PinnedRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RegistryInjectionError(RuntimeError):
    """Raised when a mid-task registry refresh mutates an annotation channel."""


@dataclass
class PinnedRegistry:
    """Registry snapshot pinned at task start; annotation text is frozen."""
    annotations: dict = field(default_factory=dict)  # tool_name -> sha256 of annotation text

    @staticmethod
    def _annotation_digest(tool: dict) -> str:
        # Only the free-text, instruction-bearing fields are hashed.
        parts = [tool.get("description", "")]
        for pname, pspec in sorted(tool.get("parameters", {}).items()):
            parts.append(pname)
            parts.append(pspec.get("description", ""))
            parts.append(str(pspec.get("default", "")))
            parts.extend(str(e) for e in pspec.get("enum", []))
        return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()

    def pin(self, tools: list) -> None:
        for t in tools:
            self.annotations[t["name"]] = self._annotation_digest(t)

    def validate_refresh(self, tools: list, in_flight: bool) -> list:
        """Return tools safe to serialize. Raise on annotation mutation mid-task."""
        safe = []
        for t in tools:
            digest = self._annotation_digest(t)
            prior = self.annotations.get(t["name"])
            if prior is None:
                # New tool whose annotation text is unvetted.
                if in_flight:
                    raise RegistryInjectionError(
                        f"tool {t['name']!r} appeared mid-task with unvetted "
                        f"annotation channel; quarantine before serialization"
                    )
                self.annotations[t["name"]] = digest
                safe.append(t)
            elif digest != prior:
                if in_flight:
                    raise RegistryInjectionError(
                        f"annotation drift on {t['name']!r} during in-flight task; "
                        f"listing-only injection possible, refusing to serialize"
                    )
                self.annotations[t["name"]] = digest
                safe.append(t)
            else:
                safe.append(t)
        return safe


def verify_plan_completion(required_calls: set, executed_calls: set) -> None:
    """Structural guard: a skipped required step is a hard failure, not a judgment call."""
    missing = required_calls - executed_calls
    if missing:
        raise RegistryInjectionError(
            f"required steps omitted: {sorted(missing)}; possible guardrail "
            f"suppression via injected schema annotation"
        )
