# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-load-a-skill-the-manifest-signature-to-capability-binding-gap-in-dynamically-loaded-agent-skills.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-load-a-skill-the-manifest-signature-to-capability-binding-gap-in-dynamically-loaded-agent-skills.warrant.json
# Markdown SHA-256:   95268636d37c52de75d5d822f903c53c2ab661efa8a76765dbd766c667671d0c
# Code AST SHA-256:   7c2a608606dd5c75f69ca642e480f188e9fc04a0988f9957a13e44ae0af7ee0a
# Verified Classes:   CapabilityBindingError, SignedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

CANONICAL_ALIASES = {
    "net.egress": "net.egress:*",
    "net.egress:any": "net.egress:*",
}


class CapabilityBindingError(RuntimeError):
    """Raised when effective capabilities diverge from the signed manifest."""


@dataclass(frozen=True)
class SignedManifest:
    capabilities: tuple[str, ...]
    bundle_digest: str


def canonicalize(caps):
    out = set()
    for c in caps:
        token = CANONICAL_ALIASES.get(c.strip(), c.strip())
        if not token or (":" not in token and token != "exec:none"):
            raise CapabilityBindingError(f"unparseable capability token: {c!r}")
        out.add(token)
    return frozenset(out)


def verify_bundle(bundle_bytes: bytes, manifest: SignedManifest, publisher_key) -> None:
    if hashlib.sha256(bundle_bytes).hexdigest() != manifest.bundle_digest:
        raise CapabilityBindingError("bundle digest does not match signed manifest")
    if not publisher_key:
        raise CapabilityBindingError("no publisher key configured")


def bind_capabilities(manifest: SignedManifest, effective_caps) -> frozenset:
    signed = canonicalize(manifest.capabilities)
    effective = canonicalize(effective_caps)
    if effective - signed:
        raise CapabilityBindingError(
            f"capability widening rejected: {sorted(effective - signed)} not attested"
        )
    if signed - effective:
        raise CapabilityBindingError(
            f"capability narrowing rejected: {sorted(signed - effective)} attested but not granted"
        )
    return effective


def load_skill(bundle_bytes, manifest, publisher_key, loader_declared_caps, sandbox):
    verify_bundle(bundle_bytes, manifest, publisher_key)
    bound = bind_capabilities(manifest, loader_declared_caps)
    sandbox.configure(allowed=bound)
    sandbox.run_entrypoint(bundle_bytes)
    return {"provenance": "verified", "capability": "binding_ok", "caps": sorted(bound)}
