# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-in-aaif-agent-identity-scope-width-escalation-at-chain-depth-3.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-delegation-chain-in-aaif-agent-identity-scope-width-escalation-at-chain-depth-3.warrant.json
# Markdown SHA-256:   00251bdacf1b861a15bbeb6384e40fd47c36f9ee854980746778465cf9750778
# Code AST SHA-256:   e324b6c503e4136f9f7fa37097e792fdd7779f99c1957cea7028be8e376e6ca7
# Verified Classes:   DelegationChainIntegrityError, DelegationLink
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationChainIntegrityError(RuntimeError):
    """Raised when an AAIF delegation chain violates a structural invariant."""


@dataclass(frozen=True)
class DelegationLink:
    issuer: str
    audience: str
    scope: FrozenSet[str]          # canonical resource:action tuples
    expires_at: int                # unix seconds
    signature_valid: bool


def verify_chain(links: list[DelegationLink]) -> None:
    if not links:
        raise DelegationChainIntegrityError("empty delegation chain")

    for i, link in enumerate(links):
        if not link.signature_valid:
            raise DelegationChainIntegrityError(f"link {i}: bad signature")
        if i == 0:
            continue

        parent = links[i - 1]
        if parent.audience != link.issuer:
            raise DelegationChainIntegrityError(
                f"link {i}: audience/issuer mismatch "
                f"({parent.audience!r} != {link.issuer!r})"
            )

        # Temporal monotonicity: a child must not outlive its parent.
        if link.expires_at > parent.expires_at:
            raise DelegationChainIntegrityError(
                f"link {i}: expiry {link.expires_at} exceeds parent "
                f"{parent.expires_at} (revocation cannot propagate)"
            )

        # Scope-width monotonicity. At depth >= 2 a widening link is
        # never legitimate: it is a confused-deputy or forged-intermediate
        # construction. Depth-1 widening is a valid root re-delegation.
        if i >= 2 and not link.scope.issubset(parent.scope):
            widened = link.scope - parent.scope
            raise DelegationChainIntegrityError(
                f"link {i}: scope widening at depth {i} "
                f"(added {sorted(widened)!r}); chain rejected"
            )

        # Wildcards cannot be width-compared; reject at depth >= 2.
        if i >= 2 and any(s.endswith(":*") for s in link.scope):
            raise DelegationChainIntegrityError(
                f"link {i}: wildcard scope at depth {i} cannot be "
                f"verified for monotonicity; expand or reject"
            )
