# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-skill-manifest-and-its-executable-body-in-a-dynamically-loaded-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-skill-manifest-and-its-executable-body-in-a-dynamically-loaded-tool-registry.warrant.json
# Markdown SHA-256:   aa372ffd33bb5b6ec3b5d9c0689cd097bcb27f80f0623479c9d6513d19998428
# Code AST SHA-256:   0de5640cd0fc879f3eb3c9d84a510da74224221f13a5ab873d6e44061d589c02
# Verified Classes:   CapabilityBoundaryError, SkillContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac


class CapabilityBoundaryError(RuntimeError):
    """Raised when a loaded skill attempts an operation outside its verified manifest."""


class SkillContext:
    """Deny-by-default capability handle injected into a skill body.

    The handle is the enforcement chokepoint: it must consult the *verified*
    manifest capability set, never descriptor defaults, before performing any
    side-effecting operation.
    """

    def __init__(self, verified_caps: frozenset[str], descriptor_defaults: dict):
        self._caps = verified_caps
        # Descriptor defaults are untrusted until filtered against verified caps.
        self._defaults = self._filter_defaults(descriptor_defaults)
        self._invoked: set[str] = set()

    def _filter_defaults(self, defaults: dict) -> dict:
        # Only defaults that name a declared capability survive the merge.
        allowed = {k for k in defaults if k in self._caps}
        return {k: defaults[k] for k in allowed}

    def _require(self, cap: str) -> None:
        if cap not in self._caps:
            raise CapabilityBoundaryError(
                f"skill invoked undeclared capability {cap!r}; "
                f"verified caps={sorted(self._caps)}"
            )
        self._invoked.add(cap)

    def read_file(self, path: str) -> bytes:
        self._require("fs.read")
        with open(path, "rb") as fh:
            return fh.read()

    def http_post(self, url: str, data: bytes) -> None:
        self._require("http.post")
        # ... transport elided ...

    def resolve_secret(self, name: str) -> str:
        self._require("secrets.resolve")
        # ... resolver elided ...


def load_and_invoke(manifest: dict, body: bytes, descriptor: dict,
                    signature: bytes, pubkey: bytes) -> None:
    # 1. Verify signature over manifest.
    expected = hmac.new(pubkey, repr(sorted(manifest.items())).encode(),
                        hashlib.sha256).digest()
    if not hmac.compare_digest(expected, signature):
        raise CapabilityBoundaryError("manifest signature invalid")

    # 2. Verify body hash.
    if hashlib.sha256(body).hexdigest() != manifest["body_hash"]:
        raise CapabilityBoundaryError("body hash mismatch")

    # 3. Build deny-by-default handle from VERIFIED caps only.
    ctx = SkillContext(frozenset(manifest["capabilities"]),
                       descriptor.get("defaults", {}))

    # 4. Invoke. Any undeclared capability raises at the handle.
    exec(compile(body, "<skill>", "exec"), {"ctx": ctx})


if __name__ == "__main__":
    manifest = {"capabilities": ["fs.read"], "body_hash": "deadbeef"}
    descriptor = {"defaults": {"include_env": True, "post_url": "https://evil"}}
    # A body that honors descriptor defaults to exfiltrate will fault here:
    ctx = SkillContext(frozenset(manifest["capabilities"]),
                       descriptor["defaults"])
    if ctx._defaults.get("include_env"):
        # This path is unreachable because include_env was filtered out,
        # but if a body reached secrets directly it would raise:
        raise CapabilityBoundaryError(
            "descriptor default 'include_env' survived filtering; "
            "execution context is not closed under the signature"
        )
