# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-loaded-skill-s-declared-capability-manifest-and-its-actual-runtime-effect-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-loaded-skill-s-declared-capability-manifest-and-its-actual-runtime-effect-surface.warrant.json
# Markdown SHA-256:   fbe5a79aaeafbb64163c5c8d0a94a2a6bdfc34d736eb5918d35145f193889c7c
# Code AST SHA-256:   9f35bf91b06e68d3a2640593503231b7ba38c55833d7be79beec646b3c7c1b95
# Verified Classes:   SkillCapabilityViolation, SkillManifest, SkillInstance, SkillRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SkillCapabilityViolation(RuntimeError):
    """Raised when a skill's actual effect surface exceeds its declared manifest."""


@dataclass(frozen=True)
class SkillManifest:
    name: str
    version_hash: str  # content hash, not a mutable tag
    declared_capabilities: frozenset[str]


@dataclass
class SkillInstance:
    manifest: SkillManifest
    body: Callable
    principal: str  # skill runs under its own identity, not the parent agent's


class SkillRegistry:
    """Registry that pins by content hash and refuses unvalidated versions."""

    def __init__(self, expected_hashes: dict[str, str]):
        self._expected = expected_hashes
        self._validated: dict[str, SkillManifest] = {}

    def load(self, name: str, raw_body: bytes, manifest: SkillManifest) -> SkillInstance:
        actual = hashlib.sha256(raw_body).hexdigest()
        if manifest.version_hash != actual:
            raise SkillCapabilityViolation(
                f"manifest hash {manifest.version_hash[:12]} != body hash {actual[:12]} "
                f"for skill {name!r}; manifest does not describe the code that will run"
            )
        if self._expected.get(name) != actual:
            raise SkillCapabilityViolation(
                f"skill {name!r} body hash {actual[:12]} not in pinned allowlist; "
                f"registry drift or tag mutation"
            )
        self._validated[name] = manifest
        return SkillInstance(manifest=manifest, body=_wrap(raw_body), principal=f"skill:{name}")


def derive_handle(skill: SkillInstance, requested: str) -> Callable:
    """Mint only handles the manifest declares; refuse everything else."""
    if requested not in skill.manifest.declared_capabilities:
        raise SkillCapabilityViolation(
            f"skill {skill.manifest.name!r} requested capability {requested!r} "
            f"not in declared set {sorted(skill.manifest.declared_capabilities)}"
        )
    return _HANDLES[requested]


def invoke(skill: SkillInstance, args: dict, requested_caps: list[str]) -> object:
    handles = {cap: derive_handle(skill, cap) for cap in requested_caps}
    # The skill executes with ONLY `handles` in scope — no ambient tool bus,
    # no parent credentials. Effect surface == declared set, by construction.
    return skill.body(args, handles)


_HANDLES: dict[str, Callable] = {
    "read:filesystem:/data/inputs": lambda p: open(p, "rb").read(),
    # http.post is intentionally absent from the handle table for read-only skills;
    # a skill that reaches for it fails at derive_handle, not in the audit log.
}


def _wrap(raw: bytes) -> Callable:
    # placeholder: real loader would exec a sandboxed entrypoint
    def _entry(args, handles):
        return handles
    return _entry
