# 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-across-non-monotonic-tool-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-credential-chains-from-silently-widening-scope-across-non-monotonic-tool-re-entry.warrant.json
# Markdown SHA-256:   06a1f134dd198e6875c247de54110df447600565552e8657a61f86f5f75b8719
# Code AST SHA-256:   bbff507aa5bff8ee21d23858ccc31bacd1ee66bf39aba0a130c7935e8bb9cf28
# Verified Classes:   DelegationWideningError, Warrant, ConsumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, FrozenSet


class DelegationWideningError(RuntimeError):
    """Raised when a child warrant's remaining authority exceeds its parent's."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    tool: str
    declared_scope: FrozenSet[str]
    quota: int
    cursor: int
    non_monotone: bool
    parent_consumption_digest: str | None = None


@dataclass
class ConsumptionLedger:
    # (warrant_id, tool) -> (consumed_quota, advanced_cursor, touched_resources)
    state: Dict[tuple, tuple] = field(default_factory=dict)

    def remaining(self, w: Warrant) -> tuple[int, int, FrozenSet[str]]:
        used_q, cur, touched = self.state.get((w.warrant_id, w.tool), (0, 0, frozenset()))
        return (w.quota - used_q, max(w.cursor, cur), w.declared_scope - touched)

    def record(self, w: Warrant, resource: str, cost: int = 1) -> None:
        used_q, cur, touched = self.state.get((w.warrant_id, w.tool), (0, 0, frozenset()))
        self.state[(w.warrant_id, w.tool)] = (used_q + cost, cur, touched | {resource})


def delegate(parent: Warrant, child_id: str, ledger: ConsumptionLedger) -> Warrant:
    if not parent.non_monotone:
        # Static subset is sound only for monotone tools.
        return Warrant(
            warrant_id=child_id,
            tool=parent.tool,
            declared_scope=parent.declared_scope,
            quota=parent.quota,
            cursor=parent.cursor,
            non_monotone=False,
            parent_consumption_digest=None,
        )

    rem_q, rem_cur, rem_scope = ledger.remaining(parent)
    # Child must be minted from LIVE remainder, never declared scope.
    child = Warrant(
        warrant_id=child_id,
        tool=parent.tool,
        declared_scope=rem_scope,
        quota=rem_q,
        cursor=rem_cur,
        non_monotone=True,
        parent_consumption_digest=f"{parent.warrant_id}:{rem_q}:{rem_cur}:{len(rem_scope)}",
    )

    # Post-mint invariant: remaining(child) must be subset of remaining(parent).
    c_q, c_cur, c_scope = ledger.remaining(child)
    if c_q > rem_q or c_cur < rem_cur or not c_scope.issubset(rem_scope):
        raise DelegationWideningError(
            f"child {child_id} widens parent {parent.warrant_id}: "
            f"quota {c_q}>{rem_q} or cursor {c_cur}<{rem_cur} or "
            f"scope {set(c_scope) - set(rem_scope)}"
        )
    return child


def verify_reentry(w: Warrant, resource: str, ledger: ConsumptionLedger) -> None:
    rem_q, rem_cur, rem_scope = ledger.remaining(w)
    if w.non_monotone and resource in w.declared_scope and resource not in rem_scope:
        raise DelegationWideningError(
            f"re-entry into already-consumed resource {resource} under {w.warrant_id}"
        )
    if rem_q <= 0:
        raise DelegationWideningError(f"warrant {w.warrant_id} exhausted quota")
