# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-signed-skill-manifest-from-a-signed-skill-bundle-the-manifest-bundle-signing-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-signed-skill-manifest-from-a-signed-skill-bundle-the-manifest-bundle-signing-boundary.warrant.json
# Markdown SHA-256:   fdbe35f97998084f842c1d9d9ab692a016e48d17ab7344e5c62a45844961ab00
# Code AST SHA-256:   7c8d430cea448a834c6d6b690ff585535bc8504ce5768d87a011055a90c01f91
# Verified Classes:   ManifestBundleMismatch, CapabilityNotDeclared
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib


class ManifestBundleMismatch(RuntimeError):
    """Raised when a signed manifest does not bind the bytes about to be executed."""
    pass


class CapabilityNotDeclared(RuntimeError):
    """Raised when a bundle attempts to exercise a capability absent from its manifest."""
    pass


def load_skill(manifest: dict, bundle_bytes: bytes, requested_caps: set[str]) -> "Sandbox":
    # 1. Signature must already have been verified by the caller against a trusted key.
    if not manifest.get("signature_verified"):
        raise ManifestBundleMismatch("manifest signature not verified before load")

    # 2. Hash binding MUST precede any capability grant.
    actual = hashlib.sha256(bundle_bytes).hexdigest()
    if actual != manifest["bundle_hash"]:
        # Hard failure: never fall through to capability grant on mismatch.
        raise ManifestBundleMismatch(
            f"bundle hash {actual} does not match signed manifest "
            f"{manifest['bundle_hash']}; refusing to load"
        )

    # 3. Allowlist is the sole source of grants; deny-by-default.
    declared = set(manifest["capabilities"])
    undeclared = requested_caps - declared
    if undeclared:
        raise CapabilityNotDeclared(
            f"bundle requested undeclared capabilities: {sorted(undeclared)}"
        )

    return Sandbox(grants=declared & requested_caps)
