# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-capability-tokens-from-silently-widening-scope-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-capability-tokens-from-silently-widening-scope-across-agent-handoffs.warrant.json
# Markdown SHA-256:   2c6bf67febeee82a638d179c15b16d60ce0b249115392523041a0c55751f3d75
# Code AST SHA-256:   f640d40b122f18bf531dd774ad097245ec64534b4673be8e845244fa6d8ab588
# Verified Classes:   ScopeWideningError, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated token's effective scope exceeds the transitive
    intersection of its ancestors' scopes, even though each pairwise link is a
    valid subset of its immediate parent."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    issuer: str
    subject: str
    scope: FrozenSet[str]
    delegatable: bool
    parent_id: str | None


def effective_scope_intersection(
    leaf: CapabilityToken,
    registry: dict[str, CapabilityToken],
) -> FrozenSet[str]:
    """Walk the full chain to root and intersect every scope set."""
    chain = [leaf]
    cursor = leaf
    seen: set[str] = set()
    while cursor.parent_id is not None:
        if cursor.parent_id in seen:
            raise ScopeWideningError(
                f"cycle detected at {cursor.parent_id} while resolving {leaf.token_id}"
            )
        seen.add(cursor.parent_id)
        parent = registry.get(cursor.parent_id)
        if parent is None:
            raise ScopeWideningError(
                f"broken chain: parent {cursor.parent_id} of {cursor.token_id} not found"
            )
        chain.append(parent)
        cursor = parent
    intersection = chain[0].scope
    for token in chain[1:]:
        intersection = intersection & token.scope
    return intersection


def verify_delegation(
    leaf: CapabilityToken,
    registry: dict[str, CapabilityToken],
) -> None:
    """Enforce transitive intersection, not just pairwise subset.

    A token may pass pairwise subset checks at every hop and still be illegal:
    this is the scope-widening failure. The invariant is that the leaf's scope
    must be a subset of the intersection of every ancestor's scope.
    """
    if leaf.parent_id is None:
        return  # root grant; nothing to attenuate against

    parent = registry.get(leaf.parent_id)
    if parent is None:
        raise ScopeWideningError(
            f"token {leaf.token_id} references missing parent {leaf.parent_id}"
        )

    # Pairwise check: necessary, insufficient.
    if not leaf.scope.issubset(parent.scope):
        raise ScopeWideningError(
            f"token {leaf.token_id} scope {sorted(leaf.scope)} is not a subset "
            f"of immediate parent {parent.token_id} scope {sorted(parent.scope)}"
        )

    # Delegation flag must be scope-bound, not root-bound.
    if not parent.delegatable:
        raise ScopeWideningError(
            f"parent {parent.token_id} is not delegatable but issued {leaf.token_id}"
        )

    # Transitive check: the actual invariant.
    transitive = effective_scope_intersection(leaf, registry)
    if not leaf.scope.issubset(transitive):
        widened = leaf.scope - transitive
        raise ScopeWideningError(
            f"token {leaf.token_id} widens scope beyond transitive intersection "
            f"of its chain; unauthorized capabilities: {sorted(widened)}"
        )
