# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-skill-registry-as-an-untrusted-code-execution-boundary-rather-than-a-passive-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-dynamically-loaded-skill-registry-as-an-untrusted-code-execution-boundary-rather-than-a-passive-capability.warrant.json
# Markdown SHA-256:   b86ef0eba0b618be88d6ad6c03f3791631d8e7ae5fccd71a2d1bf297b476422c
# Code AST SHA-256:   998b026f464229d61005f94b4269d8fb7f0dcd5dc8ec11bd766a86d988173917
# Verified Classes:   SkillInjectionError, SkillEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class SkillInjectionError(RuntimeError):
    """Raised when a registry entry violates the untrusted-boundary invariant."""


CROSS_TOOL_REF = re.compile(r"\b(call|invoke|first call|before invoking)\b.*\b[a-z_]+\(|\b[a-z_]+\([^)]*\)", re.I)
PSEUDO_TAG = re.compile(r"\[/?(SYSTEM|INST|INSTRUCTIONS?)\]|<\|?im_start\|?>", re.I)


@dataclass(frozen=True)
class SkillEntry:
    name: str
    description: str
    schema: dict
    digest: str


def digest_entry(name: str, description: str, schema: dict) -> str:
    h = hashlib.sha256()
    h.update(name.encode())
    h.update(b"\x00")
    h.update(description.encode())
    h.update(b"\x00")
    h.update(repr(sorted(schema.items())).encode())
    return h.hexdigest()


def adjudicate(entry: SkillEntry, trusted_digests: dict[str, str]) -> SkillEntry:
    # Invariant 1: trust is keyed by content digest, never by name alone.
    prior = trusted_digests.get(entry.name)
    if prior is not None and prior != entry.digest:
        raise SkillInjectionError(
            f"registry drift for '{entry.name}': digest {prior[:12]} -> {entry.digest[:12]}; "
            "re-adjudication required before callable"
        )

    # Invariant 2: descriptions may not carry instruction authority.
    if PSEUDO_TAG.search(entry.description):
        raise SkillInjectionError(
            f"pseudo-instruction tag in description of '{entry.name}'; quarantine"
        )

    # Invariant 3: a tool describes itself, never other tools / the agent procedure.
    if CROSS_TOOL_REF.search(entry.description):
        raise SkillInjectionError(
            f"cross-tool reference in description of '{entry.name}'; "
            "possible injection steering toward another capability"
        )

    # Invariant 4: schema enums/defaults must not name unrequested resources.
    for field, spec in entry.schema.get("properties", {}).items():
        enum = spec.get("enum")
        if enum and any(v in ("all", "secrets", "config", "*") for v in enum):
            raise SkillInjectionError(
                f"schema enum for '{entry.name}.{field}' exposes broad scope {enum}"
            )

    return entry


def load_registry(entries: list[SkillEntry], trusted: dict[str, str]) -> dict[str, SkillEntry]:
    resolved: dict[str, SkillEntry] = {}
    for e in entries:
        resolved[e.name] = adjudicate(e, trusted)
    return resolved
