# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-credential-chain-has-silently-exceeded-its-scope-depth-invariant-under-aaif-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-credential-chain-has-silently-exceeded-its-scope-depth-invariant-under-aaif-capability-tokens.warrant.json
# Markdown SHA-256:   87676493b70982efa9638340ca3dd9d89634b5dbae83380a8d7a950bce5a93e5
# Code AST SHA-256:   9277d66bd7ecb9045ab77d1d06ee3b2a5e1458d683940e65db2db44c476c6a79
# Verified Classes:   DelegationBudgetExceeded, RootIssuanceRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationBudgetExceeded(RuntimeError):
    """Raised when a mint would push total descendants past the root's budget."""
    pass


class RootIssuanceRecord:
    def __init__(self, root_id: str, delegation_budget: int):
        self.root_id = root_id
        self.delegation_budget = delegation_budget
        self.descendants_issued = 0
        self._lock = __import__("threading").Lock()

    def reserve_descendant(self) -> int:
        # Atomic, fail-closed increment: the ONLY place budget is enforced.
        with self._lock:
            if self.descendants_issued + 1 > self.delegation_budget:
                raise DelegationBudgetExceeded(
                    f"root {self.root_id}: budget {self.delegation_budget} "
                    f"already consumed {self.descendants_issued}; refusing mint"
                )
            self.descendants_issued += 1
            return self.descendants_issued


def mint_child_token(parent_scope: set, child_scope: set,
                     parent_depth: int, root_record: RootIssuanceRecord,
                     max_path_length: int) -> dict:
    if not child_scope.issubset(parent_scope):
        raise DelegationBudgetExceeded(
            f"scope escalation: {child_scope} not subset of {parent_scope}"
        )
    if parent_depth + 1 > max_path_length:
        raise DelegationBudgetExceeded(
            f"path length {parent_depth + 1} exceeds {max_path_length}"
        )
    # Global count check anchored at root, serialized across all hops.
    root_record.reserve_descendant()
    return {
        "root_id": root_record.root_id,
        "depth": parent_depth + 1,
        "scope": child_scope,
        "remaining_hops": max_path_length - (parent_depth + 1),
    }
