# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-chain-is-transitively-valid-but-whose-attenuation-lattice.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-chain-is-transitively-valid-but-whose-attenuation-lattice.warrant.json
# Markdown SHA-256:   ff6f69e1820d63d3a5802838407de517f31ffb6ae777af1484919b37d4874ff1
# Code AST SHA-256:   b888bcec57b9ce767a2f64ec0c9e212bb71e1811393e049c3a0d1c03c2983ef6
# Verified Classes:   DelegationIntegrityError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationIntegrityError(RuntimeError):
    """Raised when a delegated AAIF token's scope chain is non-monotonic."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    issuer: str
    parent_id: str | None
    scope: FrozenSet[str]
    lattice_element: str  # normalized lattice position, e.g. "read:fs:/etc"


def normalize(scope: FrozenSet[str], lattice: dict[str, str]) -> FrozenSet[str]:
    """Map raw capability strings to normalized lattice elements."""
    out = set()
    for s in scope:
        if s not in lattice:
            raise DelegationIntegrityError(f"capability {s!r} not in lattice")
        out.add(lattice[s])
    return frozenset(out)


def verify_chain_intersection(
    token: CapabilityToken,
    ancestors: list[CapabilityToken],
    lattice: dict[str, str],
) -> None:
    """Enforce: effective_scope(token) subset of intersection of all ancestors.

    Signature verification is assumed already performed. This gate checks
    the monotonic attenuation invariant that signatures cannot express.
    """
    if not ancestors:
        return  # root token, no delegation boundary to cross

    child_scope = normalize(token.scope, lattice)

    # Condition 1: immediate-parent containment.
    immediate_parent = ancestors[0]
    parent_scope = normalize(immediate_parent.scope, lattice)
    if not child_scope <= parent_scope:
        raise DelegationIntegrityError(
            f"token {token.token_id} scope {sorted(child_scope)} not contained "
            f"in immediate parent {immediate_parent.token_id} scope "
            f"{sorted(parent_scope)}"
        )

    # Condition 2: chain-intersection containment over ALL ancestors.
    intersection = parent_scope
    for anc in ancestors[1:]:
        intersection = intersection & normalize(anc.scope, lattice)

    if not child_scope <= intersection:
        offending = sorted(child_scope - intersection)
        raise DelegationIntegrityError(
            f"lattice-jump escalation: token {token.token_id} grants "
            f"{offending} which is absent from the chain intersection "
            f"{sorted(intersection)}; signatures verified but attenuation "
            f"is non-monotonic"
        )


def execute_delegated(
    token: CapabilityToken,
    ancestors: list[CapabilityToken],
    lattice: dict[str, str],
    required: FrozenSet[str],
) -> None:
    verify_chain_intersection(token, ancestors, lattice)
    effective = normalize(token.scope, lattice)
    missing = normalize(required, lattice) - effective
    if missing:
        raise DelegationIntegrityError(
            f"token {token.token_id} lacks required capabilities {sorted(missing)}"
        )
    # ... execute with bounded capability ...
