# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-registry-injection-that-arrives-after-its-own-capability-snapshot-was-sealed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-registry-injection-that-arrives-after-its-own-capability-snapshot-was-sealed.warrant.json
# Markdown SHA-256:   c79822fad2069f305f43e5c68669ae1d8742e388246b7e9eb88eada4f45dade2
# Code AST SHA-256:   e57eb0aa78121a3349830195321dd9040cabdfb917487242585fa9547d2be3b5
# Verified Classes:   SkillRegistryInjectionError, ToolEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SkillRegistryInjectionError(RuntimeError):
    """Raised when a planned tool resolves against a post-snapshot-mutated registry entry."""


@dataclass(frozen=True)
class ToolEntry:
    name: str
    description: str
    input_schema: dict
    provenance: str

    def content_hash(self) -> str:
        # Hash covers description + schema + provenance, NOT just the name.
        blob = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "input_schema": self.input_schema,
                "provenance": self.provenance,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(blob).hexdigest()


def resolve_pinned(
    planned_name: str,
    snapshot: dict[str, ToolEntry],
    live_registry: dict[str, ToolEntry],
) -> ToolEntry:
    """Resolve a planned tool call against the sealed snapshot, detecting registry drift.

    Invariant: a tool named in the active plan may only execute against the
    entry whose content_hash matches the snapshot the plan was validated over.
    """
    if planned_name not in snapshot:
        raise SkillRegistryInjectionError(
            f"tool {planned_name!r} was never in the sealed snapshot; plan is invalid"
        )

    sealed = snapshot[planned_name]
    sealed_hash = sealed.content_hash()

    if planned_name not in live_registry:
        raise SkillRegistryInjectionError(
            f"tool {planned_name!r} removed from registry after snapshot; refusing name-similar fallback"
        )

    live = live_registry[planned_name]
    live_hash = live.content_hash()

    if live_hash != sealed_hash:
        # Description/schema/provenance drift on a planned tool = injection surface.
        raise SkillRegistryInjectionError(
            f"content_hash drift for planned tool {planned_name!r}: "
            f"snapshot={sealed_hash[:12]} live={live_hash[:12]}; "
            f"re-validate or re-plan before execution"
        )

    return sealed  # resolve against the sealed entry, never the live one
