# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-detection-from-collapsing-into-manifest-self-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-detection-from-collapsing-into-manifest-self-attestation.warrant.json
# Markdown SHA-256:   31be24ec8b5d6f2ce40355eddde1c383517e6383549a5ae19ec94af550f29d6a
# Code AST SHA-256:   e580c512cc4eea8971dd8603f7c06b1e567e9093e9fe93a64b0c5d55ad1e46e1
# Verified Classes:   CapabilityInvariantError, Manifest, Invocation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityInvariantError(RuntimeError):
    """Raised when observed effects escape the declared capability surface."""


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    declared: FrozenSet[str]
    signature_valid: bool
    content_hash: str


@dataclass
class Invocation:
    skill_id: str
    # Derived by the verifier from parsed args, NOT asserted by the caller.
    requested: FrozenSet[str]
    # Measured by an out-of-band sensor (seccomp / egress proxy), NOT self-reported.
    observed: FrozenSet[str] = field(default_factory=frozenset)


def verify_invocation(manifest: Manifest, inv: Invocation) -> None:
    if not manifest.signature_valid:
        raise CapabilityInvariantError(
            f"manifest for {manifest.skill_id} failed signature check"
        )
    if inv.skill_id != manifest.skill_id:
        raise CapabilityInvariantError(
            f"invocation identity {inv.skill_id} != manifest {manifest.skill_id}"
        )
    # The load-bearing check: behavior vs declaration, not manifest vs manifest.
    escape = inv.observed - manifest.declared
    if escape:
        raise CapabilityInvariantError(
            f"undeclared effects {sorted(escape)} observed for "
            f"{manifest.skill_id}; declared={sorted(manifest.declared)}"
        )
    if not inv.requested <= manifest.declared:
        raise CapabilityInvariantError(
            f"requested {sorted(inv.requested)} exceeds declared surface"
        )


def verify_composition(manifests: list[Manifest], observed: FrozenSet[str]) -> None:
    # Per-skill subset checks are not closed under composition.
    union_declared = frozenset().union(*(m.declared for m in manifests))
    escape = observed - union_declared
    if escape:
        raise CapabilityInvariantError(
            f"composition produced undeclared effects {sorted(escape)}"
        )
