# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-validly-signed-skill-manifest-as-untrusted-provenance-attestation-scope-collapse-across-delegated-sub-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-validly-signed-skill-manifest-as-untrusted-provenance-attestation-scope-collapse-across-delegated-sub-a.warrant.json
# Markdown SHA-256:   071aec7146c69b8f393db2ea7954ad2a7958ef82ed52827fa672f327c966fe3c
# Code AST SHA-256:   3a9a9653d4842d99f9bb5daf22844e96637b19bd108e79213881d54c4c8ca489
# Verified Classes:   AttestationScopeCollapse, CapabilityFrame, DispatchGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttestationScopeCollapse(RuntimeError):
    """Raised when a skill's effective capability frame exceeds its attested set."""


@dataclass(frozen=True)
class CapabilityFrame:
    principal: str
    caps: FrozenSet[str]
    attested_caps: FrozenSet[str] = frozenset()
    max_delegation_depth: int = 0
    permitted_parent_caps: FrozenSet[str] = frozenset()


@dataclass
class DispatchGate:
    stack: list = field(default_factory=list)

    def push(self, frame: CapabilityFrame) -> None:
        self.stack.append(frame)

    def pop(self) -> CapabilityFrame:
        return self.stack.pop()

    def effective_caps(self) -> FrozenSet[str]:
        out: set = set()
        for frame in self.stack:
            out |= frame.caps
        return frozenset(out)

    def admit_and_dispatch(self, skill: CapabilityFrame) -> None:
        # Signature + attestation already verified upstream against the manifest
        # digest. This gate answers a different question: does the frame the skill
        # will actually execute in exceed what the attestation named?
        if skill.attested_caps - skill.caps:
            # A skill declaring more than it will run with is suspicious but not
            # an expansion; narrow the frame to the attested set.
            skill = CapabilityFrame(
                principal=skill.principal,
                caps=skill.caps & skill.attested_caps,
                attested_caps=skill.attested_caps,
                max_delegation_depth=skill.max_delegation_depth,
                permitted_parent_caps=skill.permitted_parent_caps,
            )

        parent_caps = self.effective_caps()
        depth = len(self.stack)

        if depth > skill.max_delegation_depth:
            raise AttestationScopeCollapse(
                f"skill {skill.principal!r} dispatched at depth {depth}, "
                f"attestation permits max_delegation_depth={skill.max_delegation_depth}"
            )

        if not parent_caps <= skill.permitted_parent_caps | skill.attested_caps:
            offending = parent_caps - (skill.permitted_parent_caps | skill.attested_caps)
            raise AttestationScopeCollapse(
                f"skill {skill.principal!r} composed under parent caps {sorted(offending)} "
                f"not named in attestation predicate"
            )

        self.push(skill)
        effective = self.effective_caps()
        if not effective <= skill.attested_caps:
            # The skill's own frame is clean, but the union it inherits is not.
            # This is the collapse: signature verified the artifact, not the context.
            leaked = effective - skill.attested_caps
            self.pop()
            raise AttestationScopeCollapse(
                f"skill {skill.principal!r} effective frame exceeds attestation; "
                f"inherited capabilities {sorted(leaked)} not attested for this skill"
            )
