# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-capability-token-at-each-hop-and-why-does-scope-attenuation-silently-invert-at-the-second-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-capability-token-at-each-hop-and-why-does-scope-attenuation-silently-invert-at-the-second-delegation.warrant.json
# Markdown SHA-256:   0a18f138eb2d2ac462b48335f34c1eefd41da3685a9de8e323bf07bc916a79c1
# Code AST SHA-256:   1a31450037fb02e2cebfc8f518d20eafcb0552af03eecc679db779d5a08389e8
# Verified Classes:   ScopeAttenuationInversion, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeAttenuationInversion(RuntimeError):
    """Raised when a delegated child token's scope is not a subset of its parent's."""
    pass

@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    issuer: str
    scope: FrozenSet[str]
    parent_scope: FrozenSet[str] = field(default_factory=frozenset)

def mint_child_token(
    delegator: CapabilityToken,
    requested_scope: FrozenSet[str],
    local_allowlist: FrozenSet[str],
) -> CapabilityToken:
    # Correct attenuation: intersect with the INBOUND token's scope, not just the allowlist.
    effective = requested_scope & delegator.scope & local_allowlist

    # Invariant: the child must never exceed the delegator's own grant.
    if not effective.issubset(delegator.scope):
        raise ScopeAttenuationInversion(
            f"child scope {sorted(effective)} exceeds parent scope "
            f"{sorted(delegator.scope)}; delegator {delegator.subject} "
            f"attempted to widen authority it never held"
        )

    return CapabilityToken(
        subject="child",
        issuer=delegator.subject,
        scope=effective,
        parent_scope=delegator.scope,
    )

def verify_chain(tokens: list[CapabilityToken]) -> None:
    for parent, child in zip(tokens, tokens[1:]):
        if not child.scope.issubset(parent.scope):
            raise ScopeAttenuationInversion(
                f"chain non-monotonic at {child.issuer}: "
                f"{sorted(child.scope)} ⊄ {sorted(parent.scope)}"
            )
