# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-signed-skill-manifest-but-the-capability-sandbox-and-the-provenance-chain-disagree-on-the-effective-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-signed-skill-manifest-but-the-capability-sandbox-and-the-provenance-chain-disagree-on-the-effective-capability.warrant.json
# Markdown SHA-256:   a061b8741340953f673dba5b5366e99ce146ed477099400acc296d6670c2bce3
# Code AST SHA-256:   abcd838ce3607962e898f8f1c4aa2ad817917603762f91442762e5d866056ca8
# Verified Classes:   CapabilityDivergenceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CapabilityDivergenceError(RuntimeError):
    """Raised when the compiled sandbox policy does not equal the signed capability set."""
    pass


def gate_skill_load(signed_caps: frozenset, compiled_caps: frozenset, skill_id: str) -> None:
    """
    Enforce C_enforced == C_declared before loading a dynamically signed skill.
    signed_caps   = capabilities attested by the verified provenance manifest
    compiled_caps = capabilities the runtime sandbox will actually enforce
    """
    if compiled_caps == signed_caps:
        return  # only safe state

    widened = compiled_caps - signed_caps
    narrowed = signed_caps - compiled_caps

    if widened:
        # Enforced superset (or incomparable): privilege no one signed for.
        raise CapabilityDivergenceError(
            f"skill={skill_id} sandbox widens signed capabilities: "
            f"unattested={sorted(widened)} narrowed={sorted(narrowed)}"
        )

    # Pure narrowing: safe to load, but skill will misbehave at runtime.
    import warnings
    warnings.warn(
        f"skill={skill_id} sandbox narrows signed capabilities: missing={sorted(narrowed)}",
        RuntimeWarning,
    )


def load_skill(skill_id: str, manifest: dict, compiler) -> None:
    signed_caps = frozenset(manifest["capabilities"])
    compiled_caps = frozenset(compiler.compile(manifest))  # must fail closed internally
    gate_skill_load(signed_caps, compiled_caps, skill_id)
    # ... proceed to instantiate skill under compiled policy ...
