# 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-the-runtime-behavior-of-the-skill-it-names.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-skill-manifest-and-the-runtime-behavior-of-the-skill-it-names.warrant.json
# Markdown SHA-256:   42e50deae10276efc4054c7adae0fdfc8ea7914a27df33cc9d043bff793c017b
# Code AST SHA-256:   cb8b22f4ab4a23fde60d37ce186775d6054f6d94e784aa6f79e139a9bec4e803
# Verified Classes:   CapabilityDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDivergenceError(RuntimeError):
    """Raised when a skill payload exercises capabilities outside its signed manifest."""
    pass


def enforce_manifest_envelope(manifest: dict, observed_events: list[dict]) -> None:
    """
    Invariant: observed capability set must be a subset of the signed declared set.
    A valid signature on an under-declared manifest does not exempt the payload.
    """
    declared = set(manifest.get("declared_capabilities", []))
    if not manifest.get("signature_verified", False):
        raise CapabilityDivergenceError(
            f"skill {manifest.get('name')!r}: manifest signature not verified at invoke time"
        )

    exercised = set()
    for ev in observed_events:
        cap = ev.get("capability")
        if cap is None:
            # An event with no attributable capability is itself a divergence:
            # the sandbox could not map it to any declared binding.
            raise CapabilityDivergenceError(
                f"skill {manifest.get('name')!r}: unattributable event {ev!r}"
            )
        exercised.add(cap)

    undeclared = exercised - declared
    if undeclared:
        raise CapabilityDivergenceError(
            f"skill {manifest.get('name')!r} v{manifest.get('version')}: "
            f"payload exercised undeclared capabilities {sorted(undeclared)}; "
            f"declared={sorted(declared)}; halting invocation and quarantining skill"
        )
