# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegated-capability-token-whose-scope-narrows-a-parent-grant-it-no-longer-holds.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegated-capability-token-whose-scope-narrows-a-parent-grant-it-no-longer-holds.warrant.json
# Markdown SHA-256:   8fbdeff8bcb2500bc87c0ab99a1dbd87c61ae12ac908f282ac40c8e3e57f7939
# Code AST SHA-256:   2f448ebe979baec501539e3bdd35457bab4e002abb50a0956f302f362506355c
# Verified Classes:   DelegationScopeError, ScopeDelta, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet

class DelegationScopeError(RuntimeError):
    """Raised when a delegated token's scope is not sound against the parent's authoritative epoch."""
    pass

@dataclass(frozen=True)
class ScopeDelta:
    epoch: int
    removed: FrozenSet[str]
    added: FrozenSet[str]

@dataclass(frozen=True)
class DelegatedToken:
    scope: FrozenSet[str]
    parent_id: str
    parent_scope_epoch: int   # epoch of parent scope at mint time
    delegator_key: str
    depth: int
    expiry: float

def validate_at_use(
    child: DelegatedToken,
    parent_scope_at_mint: FrozenSet[str],
    parent_scope_at_use: FrozenSet[str],
    deltas_since_mint: list[ScopeDelta],
    max_depth: int,
    now: float,
) -> None:
    # 1. structural subset at mint
    if not child.scope <= parent_scope_at_mint:
        raise DelegationScopeError(
            f"child scope {child.scope} not subset of parent-at-mint {parent_scope_at_mint}"
        )
    # 2. depth and expiry
    if child.depth >= max_depth:
        raise DelegationScopeError(f"delegation depth {child.depth} >= max {max_depth}")
    if now >= child.expiry:
        raise DelegationScopeError("child token expired at use time")
    # 3. epoch-bound delta intersection: the invariant most validators omit
    for d in deltas_since_mint:
        if d.epoch <= child.parent_scope_epoch:
            continue
        if child.scope & d.removed:
            raise DelegationScopeError(
                f"parent scope narrowed at epoch {d.epoch}: child asserts removed "
                f"capability {child.scope & d.removed} — delegated token is stale"
            )
    # 4. liveness against authoritative use-time scope
    if not child.scope <= parent_scope_at_use:
        raise DelegationScopeError(
            f"child scope {child.scope} not subset of authoritative parent-at-use {parent_scope_at_use}"
        )
