# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-scoped-capability-token-when-the-delegation-depth-exceeds-the-warrant-s-attenuation-bud.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-scoped-capability-token-when-the-delegation-depth-exceeds-the-warrant-s-attenuation-bud.warrant.json
# Markdown SHA-256:   9092849fab6819e74ae1aab74d743927851f961071f976d6d0fe233ae76a8467
# Code AST SHA-256:   139a10a34c9f0c0cfe637d2981d654392ac9aa6404e55c8fa9f1e109df17cfd9
# Verified Classes:   DelegationDepthViolation, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthViolation(RuntimeError):
    """Raised when a re-delegation would exceed the warrant's signed attenuation budget."""


@dataclass(frozen=True)
class Warrant:
    scope: frozenset[str]
    depth_remaining: int
    parent_hash: str | None
    signature_valid: bool


def authorize_redelegation(
    parent: Warrant,
    requested_scope: frozenset[str],
    declared_depth: int,
    chain_length_from_root: int,
) -> int:
    if not parent.signature_valid:
        raise DelegationDepthViolation("parent warrant signature invalid; cannot delegate")

    if not requested_scope.issubset(parent.scope):
        raise DelegationDepthViolation(
            f"scope escalation: {requested_scope - parent.scope} not in parent scope"
        )

    # Derived depth: the chain length from root bounds the true remaining budget.
    effective_depth = min(declared_depth, chain_length_from_root - 1)

    if effective_depth != declared_depth:
        raise DelegationDepthViolation(
            f"declared depth {declared_depth} diverges from derived {effective_depth}; "
            "possible cache-aliasing or replay upstream"
        )

    if effective_depth <= 0:
        raise DelegationDepthViolation(
            "attenuation budget exhausted; re-delegation refused at depth 0"
        )

    return effective_depth - 1


def mint_child(parent: Warrant, scope: frozenset[str], declared_depth: int, chain_len: int) -> Warrant:
    child_depth = authorize_redelegation(parent, scope, declared_depth, chain_len)
    return Warrant(
        scope=scope,
        depth_remaining=child_depth,
        parent_hash=hash((parent.scope, parent.depth_remaining, parent.parent_hash)),
        signature_valid=True,
    )
