# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-credential-chains-from-silently-widening-at-re-delegation-in-aaif-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-narrowing-credential-chains-from-silently-widening-at-re-delegation-in-aaif-capability-tokens.warrant.json
# Markdown SHA-256:   fb43ee6e6b1b6827a752fb98080f4dab5612f93e72d9be3df02c51c03cc85bb7
# Code AST SHA-256:   955c8f98193ea95289ab98e6b1982871417286cc2594d7d9ad8c2bbbcc010b9f
# Verified Classes:   ScopeWideningError, Scope, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a delegated token's scope is not a subset of the
    running intersection of its ancestors' scopes."""
    pass


@dataclass(frozen=True)
class Scope:
    tools: frozenset[str]
    resources: frozenset[str]
    budget_tokens: int
    expires: Optional[str] = None  # ISO-8601; None means "inherit parent"


@dataclass(frozen=True)
class Token:
    token_id: str
    parent_id: Optional[str]
    scope: Scope
    signature_valid: bool = True


def _intersect(a: Scope, b: Scope) -> Scope:
    # Per-field attenuation. Missing expiry on either side inherits the
    # more restrictive (earlier) of the two; None on both stays None.
    if a.expires is None:
        exp = b.expires
    elif b.expires is None:
        exp = a.expires
    else:
        exp = min(a.expires, b.expires)
    return Scope(
        tools=a.tools & b.tools,
        resources=a.resources & b.resources,
        budget_tokens=min(a.budget_tokens, b.budget_tokens),
        expires=exp,
    )


def _is_subset(child: Scope, parent: Scope) -> bool:
    if not child.tools <= parent.tools:
        return False
    if not child.resources <= parent.resources:
        return False
    if child.budget_tokens > parent.budget_tokens:
        return False
    # Absent expiry on the child attenuates to the parent's expiry; it does
    # NOT default to a session bound. A child expiry later than the parent's
    # is a widening.
    if child.expires is not None:
        if parent.expires is not None and child.expires > parent.expires:
            return False
    return True


def verify_chain(chain: list[Token]) -> Scope:
    """Validate a delegation chain root->leaf and return the effective scope.

    Rejects any hop whose scope is not a subset of the running intersection
    of all ancestors. Per-hop signature validation is necessary but not
    sufficient; the fold is what catches sibling/superset widening at depth
    >= 2.
    """
    if not chain:
        raise ScopeWideningError("empty delegation chain")

    for hop in chain:
        if not hop.signature_valid:
            raise ScopeWideningError(f"invalid signature on {hop.token_id}")

    effective = chain[0].scope
    for hop in chain[1:]:
        if not _is_subset(hop.scope, effective):
            raise ScopeWideningError(
                f"scope widening at {hop.token_id}: child scope is not a "
                f"subset of running intersection of ancestors "
                f"(child resources={sorted(hop.scope.resources)}, "
                f"effective resources={sorted(effective.resources)}, "
                f"child budget={hop.scope.budget_tokens}, "
                f"effective budget={effective.budget_tokens})"
            )
        effective = _intersect(effective, hop.scope)
    return effective


# Reproduction of the observed trace: T0 -> T1 (narrow) -> T2 (widened resources).
T0 = Token("T0", None, Scope(
    tools=frozenset({"search", "fetch", "summarize"}),
    resources=frozenset({"kb://public/*"}),
    budget_tokens=50000,
    expires="2025-06-17T18:00:00Z",
))
T1 = Token("T1", "T0", Scope(
    tools=frozenset({"search", "fetch"}),
    resources=frozenset({"kb://public/docs/*"}),
    budget_tokens=30000,
    expires="2025-06-17T18:00:00Z",
))
T2 = Token("T2", "T1", Scope(
    tools=frozenset({"summarize"}),
    resources=frozenset({"kb://public/*"}),  # WIDENED vs T1
    budget_tokens=20000,
    expires=None,  # omitted; must inherit T1's expiry, not a session default
))

if __name__ == "__main__":
    verify_chain([T0, T1, T2])  # raises ScopeWideningError on T2
