# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-skill-injection-at-registry-load-time-versus-invocation-time-in-dynamically-loaded-agent-tool-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-skill-injection-at-registry-load-time-versus-invocation-time-in-dynamically-loaded-agent-tool-registries.warrant.json
# Markdown SHA-256:   158dd3f81d7ee7c9b0d6bc38dcd2908820f917794213b11d06409d3072d12a62
# Code AST SHA-256:   9335049203a9e64971076c81881df0ba2316af65a825e049e459d50a55eb487d
# Verified Classes:   SkillInjectionBoundaryError, ResolvedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a resolved tool's description is not bound to the same
    integrity hash as its code, or when a cache hit serves a description
    that diverged from the frozen tool graph for the current turn."""
    pass


@dataclass(frozen=True)
class ResolvedTool:
    name: str
    code_sha256: str
    description: str
    description_sha256: str | None
    manifest_hash: str


def verify_at_resolution(tool: ResolvedTool, frozen_graph_hash: str) -> None:
    # The seam: description must be covered by the same hash as code.
    if tool.description_sha256 is None:
        # Unhashed description == unauthenticated instruction channel.
        # Degrade: caller must suppress prose and present capability-only.
        raise SkillInjectionBoundaryError(
            f"tool {tool.name!r}: description not covered by integrity hash; "
            "suppress description until graph frozen and re-verified"
        )

    expected = hashlib.sha256(
        f"{tool.code_sha256}:{tool.description_sha256}".encode()
    ).hexdigest()
    if expected != tool.manifest_hash:
        raise SkillInjectionBoundaryError(
            f"tool {tool.name!r}: manifest hash mismatch "
            f"(expected {expected}, got {tool.manifest_hash}); "
            "description/code binding broken — force full re-resolve"
        )

    if tool.manifest_hash != frozen_graph_hash:
        # Cache hit served an entry that predates or postdates the frozen graph.
        raise SkillInjectionBoundaryError(
            f"tool {tool.name!r}: resolved against stale graph; "
            "refuse invocation until graph re-frozen"
        )


def resolve_from_cache_or_registry(entry: dict, frozen_graph_hash: str) -> ResolvedTool:
    tool = ResolvedTool(
        name=entry["name"],
        code_sha256=entry["code_sha256"],
        description=entry.get("description", ""),
        description_sha256=entry.get("description_sha256"),
        manifest_hash=entry["manifest_hash"],
    )
    verify_at_resolution(tool, frozen_graph_hash)
    return tool
