# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-delegated-capability-token-chain-collapse-when-an-aaif-hop-attenuates-scope-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-delegated-capability-token-chain-collapse-when-an-aaif-hop-attenuates-scope-mid-execution.warrant.json
# Markdown SHA-256:   324f3a17997336cf79ce2b470b98620367e05a2b12af9373bef41bddd3911e9d
# Code AST SHA-256:   df386eff529b0be48564c574084e092e849bc411ba095807d9e8edf2d409397d
# Verified Classes:   AttenuationCollapseError, EmptyConjunctionError, Capability, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class AttenuationCollapseError(RuntimeError):
    """Raised when a DCT chain's resolved lineage conjunction does not
    contain the capability an instance is about to exercise."""
    pass


class EmptyConjunctionError(AttenuationCollapseError):
    """Raised when the full-lineage intersection of scope sets is empty."""
    pass


@dataclass(frozen=True)
class Capability:
    name: str
    constraint: Optional[str] = None  # e.g. "api.internal" for net.egress

    def __le__(self, other: "Capability") -> bool:
        # Subset relation with argument constraints: a constrained capability
        # is only covered by an identical or unconstrained (None) parent.
        if self.name != other.name:
            return False
        if other.constraint is None:
            return True
        return self.constraint == other.constraint


@dataclass(frozen=True)
class Hop:
    subject: str
    scope: FrozenSet[Capability]
    parent_index: int  # -1 for root


def resolve_lineage_conjunction(chain: list[Hop]) -> FrozenSet[Capability]:
    """Walk every attenuation proof to the root and compute the true
    effective scope E = intersection of all hop scopes. Never trust a
    cached parent scope."""
    if not chain:
        raise EmptyConjunctionError("empty token chain")
    # Verify each hop's scope is a subset of its resolved parent.
    for i, hop in enumerate(chain):
        if hop.parent_index < 0:
            continue
        parent = chain[hop.parent_index]
        for cap in hop.scope:
            if not any(cap <= p for p in parent.scope):
                raise AttenuationCollapseError(
                    f"hop {i} ({hop.subject}) claims {cap} not covered by "
                    f"resolved parent {hop.parent_index} ({parent.subject})"
                )
    effective = chain[0].scope
    for hop in chain[1:]:
        effective = frozenset(c for c in effective if any(c <= h for h in hop.scope))
    return effective


def authorize_execution(chain: list[Hop], requested: Capability) -> None:
    """Authorize a tool call only if the requested capability is in the
    recomputed lineage conjunction. Fail closed otherwise."""
    effective = resolve_lineage_conjunction(chain)
    if not effective:
        raise EmptyConjunctionError(
            "lineage conjunction is empty; no capability may be exercised"
        )
    if not any(requested <= cap for cap in effective):
        raise AttenuationCollapseError(
            f"requested {requested} not in resolved effective scope {effective}"
        )
    # Only past this point may a side-effecting tool call be dispatched.
    return None


# Trace from the incident: O -> W -> H, W's verifier used a stale cached
# parent scope that still contained net.egress. Full-lineage resolution
# catches the collapse.
chain = [
    Hop("O", frozenset({Capability("fs.read"), Capability("fs.write"),
                        Capability("net.egress", "api.internal")}), -1),
    Hop("W", frozenset({Capability("fs.read"), Capability("fs.write")}), 0),
    Hop("H", frozenset({Capability("fs.read"),
                        Capability("net.egress", "api.internal")}), 1),
]

# H attempts an egress call it believes it holds via the stale parent view.
authorize_execution(chain, Capability("net.egress", "api.internal"))
