# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-attenuated-authority-when-a-delegated-capability-token-crosses-a-sub-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-attenuated-authority-when-a-delegated-capability-token-crosses-a-sub-agent-handoff.warrant.json
# Markdown SHA-256:   7a1e0dfc2025f7f2dffbde2c302be7ab0354445d9ee8d23f130a3424854a2093
# Code AST SHA-256:   c6ac59ef604ebe74c24d536aa7825725035b012c39a27ad34599e96c10199a30
# Verified Classes:   AttenuationViolation, SignedToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttenuationViolation(RuntimeError):
    """Raised when a child capability is not a valid monotonic attenuation of its parent."""


@dataclass(frozen=True)
class SignedToken:
    scope: frozenset[str]
    depth: int
    expires_at: float
    parent: "SignedToken | None" = None
    signature: bytes = b""


def mint_child(parent: SignedToken, requested: frozenset[str], now: float) -> SignedToken:
    # Guardrail 2: the mint function accepts only a SignedToken, never prose.
    # A compacted agent holding only a summary cannot call this and must fail closed.
    if parent is None:
        raise AttenuationViolation("no signed parent token; refusing to synthesize authority from memory")

    # Guardrail 3: depth is a signed integer, consumed on mint.
    if parent.depth <= 0:
        raise AttenuationViolation(f"delegation depth exhausted at parent (depth={parent.depth})")

    # Temporal validity against the *current* parent, not a stale snapshot.
    if now >= parent.expires_at:
        raise AttenuationViolation("parent token expired; re-fetch from issuer before delegating")

    # Guardrail 1: monotonic meet, computed — never asserted.
    child_scope = parent.scope & requested
    if not child_scope:
        raise AttenuationViolation(
            f"requested scope {sorted(requested)} disjoint from parent {sorted(parent.scope)}"
        )

    return SignedToken(
        scope=child_scope,
        depth=parent.depth - 1,
        expires_at=min(parent.expires_at, now + 300.0),
        parent=parent,
        signature=b"<signed-by-parent-key>",
    )


def verify_chain(token: SignedToken, now: float) -> None:
    # Resource-server side: attenuation is verified by walking parents,
    # not by trusting the minter's declared scope.
    node = token
    while node.parent is not None:
        if not node.scope <= node.parent.scope:
            raise AttenuationViolation(
                f"escalation: {sorted(node.scope - node.parent.scope)} not held by parent"
            )
        if node.depth >= node.parent.depth:
            raise AttenuationViolation("depth not strictly decreasing across handoff")
        if now >= node.parent.expires_at:
            raise AttenuationViolation("chain contains revoked/expired ancestor")
        node = node.parent
