# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-scope-credential-has-silently-widened-through-transitive-aaif-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-scope-credential-has-silently-widened-through-transitive-aaif-re-delegation.warrant.json
# Markdown SHA-256:   9a5882d27e8829cf76118b92a1b760c0ad86decab10d0d8ced444e98e6ada2f1
# Code AST SHA-256:   5164f7669658d91d47e3e91cc0b85cc262dfed99a5f262edccf970cd154e6132
# Verified Classes:   ScopeWideningError, Scope, Node
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a delegation tree's realized authority exceeds its root grant."""
    pass


@dataclass
class Scope:
    capability: str
    budget_tokens: int
    expires_at: float
    may_redelegate: bool
    delegation_slots: int = 0


@dataclass
class Node:
    grant_id: str
    scope: Scope
    parent: Optional["Node"] = None
    children: list = field(default_factory=list)
    spent: int = 0


def _rival_closure_ok(parent: Node, child: Scope, existing_siblings: list) -> tuple[bool, str]:
    # Rival qualifiers must be SPLIT, not copied. Sum across siblings must not
    # exceed the parent's remaining rival capacity.
    sibling_budget = sum(s.scope.budget_tokens for s in existing_siblings)
    if sibling_budget + child.budget_tokens > parent.scope.budget_tokens:
        return False, "budget_overcommit"
    if child.expires_at > parent.scope.expires_at:
        return False, "expiry_widened"
    if child.may_redelegate and parent.scope.delegation_slots <= 0:
        return False, "delegation_slots_exhausted"
    if child.may_redelegate and child.delegation_slots > parent.scope.delegation_slots - 1:
        return False, "delegation_amplification"
    return True, "ok"


def delegate(parent: Node, child_scope: Scope) -> Node:
    ok, reason = _rival_closure_ok(parent, child_scope, parent.children)
    if not ok:
        raise ScopeWideningError(
            f"AAIF re-delegation from {parent.grant_id} rejected: {reason}. "
            f"Per-edge subset may still pass; root-closure does not. "
            f"This is the silent-widening signature (edge_valid=true, closure_valid=false)."
        )
    child = Node(grant_id=f"{parent.grant_id}.{len(parent.children)}", scope=child_scope, parent=parent)
    parent.children.append(child)
    return child


def audit_edge_only(node: Node) -> bool:
    # What the reference AAIF checker does: is child a subset of parent?
    if node.parent is None:
        return True
    p, c = node.parent.scope, node.scope
    return (c.capability.startswith(p.capability)
            and c.budget_tokens <= p.budget_tokens
            and c.expires_at <= p.expires_at)


def audit_root_closure(node: Node, root: Node) -> bool:
    # The check that actually bounds widening: realized subtree authority vs root.
    leaves = [n for n in _walk(node) if not n.children]
    total_budget = sum(l.scope.budget_tokens for l in leaves)
    if total_budget > root.scope.budget_tokens:
        raise ScopeWideningError(
            f"Root {root.grant_id} authorized {root.scope.budget_tokens} tokens; "
            f"subtree under {node.grant_id} realizes {total_budget} across {len(leaves)} leaves."
        )
    return True


def _walk(n: Node):
    yield n
    for c in n.children:
        yield from _walk(c)
