# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-chains-from-silently-widening-scope-at-re-delegation-depth-3.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-chains-from-silently-widening-scope-at-re-delegation-depth-3.warrant.json
# Markdown SHA-256:   dfb8b047400202ccdc704f6b520ee44ec2b1e99869a6ef2b7bdb372cb0f0a563
# Code AST SHA-256:   37b65200c7ad2746c88e719bb1f3726fb1acd8f698b85d917a424ac1f341d106
# Verified Classes:   DelegationScopeWidening, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeWidening(RuntimeError):
    """Raised when a child warrant exceeds its root-anchored ancestry closure."""
    pass


@dataclass(frozen=True)
class Warrant:
    resource: str
    ops: FrozenSet[str]
    audience: str
    depth_remaining: int
    origin: str
    parent: "Warrant | None" = None
    _closure_cache: dict = field(default_factory=dict, compare=False, repr=False)


def closure(w: Warrant) -> Warrant:
    """Root-anchored intersection across the entire ancestry chain."""
    if w.parent is None:
        return w
    p = closure(w.parent)
    # Per-dimension subset; absent dimension == empty set, never default-open.
    if w.resource != p.resource:
        raise DelegationScopeWidening(
            f"resource mismatch at depth: child={w.resource!r} parent={p.resource!r}"
        )
    if not w.ops.issubset(p.ops):
        raise DelegationScopeWidening(
            f"ops widening: child={set(w.ops)} not subset of ancestry={set(p.ops)}"
        )
    if w.audience != p.audience and w.audience not in p.audience:
        raise DelegationScopeWidening(
            f"audience widening: child={w.audience!r} not within ancestry={p.audience!r}"
        )
    if w.depth_remaining >= p.depth_remaining:
        raise DelegationScopeWidening(
            f"depth not strictly decreasing: child={w.depth_remaining} parent={p.depth_remaining}"
        )
    return Warrant(
        resource=p.resource,
        ops=w.ops,          # already verified subset of p.ops
        audience=w.audience,
        depth_remaining=w.depth_remaining,
        origin=p.origin,
        parent=w.parent,
    )


def reissue(parent: Warrant, requested_ops: FrozenSet[str], audience: str) -> Warrant:
    """Pure intersection; never merge. Rejects any attempt to widen."""
    narrowed = requested_ops & parent.ops
    if narrowed != requested_ops:
        raise DelegationScopeWidening(
            f"re-issuance attempted to add ops {set(requested_ops - parent.ops)} "
            f"absent from ancestry {set(parent.ops)}"
        )
    child = Warrant(
        resource=parent.resource,
        ops=narrowed,
        audience=audience,
        depth_remaining=parent.depth_remaining - 1,
        origin=parent.origin,
        parent=parent,
    )
    closure(child)  # fail-closed at issuance, not at verification
    return child
