# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-a-revoked-capability-delegation-chain-that-has-already-fanned-out-across-a-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-a-revoked-capability-delegation-chain-that-has-already-fanned-out-across-a-swarm.warrant.json
# Markdown SHA-256:   61c7000338b7d660b131a7db142a5dc455fc97e2d443c14446c0073fcb9f1b89
# Code AST SHA-256:   b915e0b149df1b4697d20b81a13c8a07755cc59e262a7de8bd673a9f83333bcf
# Verified Classes:   RevokedCapabilityError, UnverifiableRootError, CapabilityToken, RevocationAuthority
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RevokedCapabilityError(RuntimeError):
    """Raised when an action is attempted under a capability whose root is revoked or whose chain is broken."""
    pass


class UnverifiableRootError(RuntimeError):
    """Raised when the root's current epoch cannot be established within the staleness bound."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    parent_id: Optional[str]
    root_id: str
    mint_epoch: int
    scope: dict
    signature_valid: bool = True


@dataclass
class RevocationAuthority:
    # root_id -> current epoch
    epochs: dict = field(default_factory=dict)
    # bounded staleness for cached epoch reads, in seconds
    max_staleness_s: float = 0.5
    _cache: dict = field(default_factory=dict)

    def current_epoch(self, root_id: str) -> int:
        now = time.monotonic()
        cached = self._cache.get(root_id)
        if cached and (now - cached[1]) <= self.max_staleness_s:
            return cached[0]
        if root_id not in self.epochs:
            raise UnverifiableRootError(f"no epoch record for root {root_id}")
        epoch = self.epochs[root_id]
        self._cache[root_id] = (epoch, now)
        return epoch

    def revoke(self, root_id: str) -> None:
        self.epochs[root_id] = self.epochs.get(root_id, 0) + 1
        self._cache.pop(root_id, None)


def authorize_action(
    token: CapabilityToken,
    chain: list[CapabilityToken],
    authority: RevocationAuthority,
    action_irreversible: bool,
) -> None:
    """
    Enforce the causal-cut invariant: token valid iff root unrevoked *now*, chain intact,
    and scope covers the action. Fails closed on unverifiable root for irreversible actions.
    """
    # 1. Chain integrity: each link's parent must be present and root must match.
    by_id = {t.token_id: t for t in chain}
    cursor = token
    while cursor.parent_id is not None:
        parent = by_id.get(cursor.parent_id)
        if parent is None or not parent.signature_valid:
            raise RevokedCapabilityError(
                f"broken chain at {cursor.token_id}: parent {cursor.parent_id} missing or invalid"
            )
        if parent.root_id != token.root_id:
            raise RevokedCapabilityError(
                f"root mismatch: {cursor.token_id} roots to {cursor.root_id}, parent to {parent.root_id}"
            )
        cursor = parent
    if cursor.token_id != token.root_id:
        raise RevokedCapabilityError(
            f"chain does not terminate at declared root {token.root_id}"
        )

    # 2. Live epoch check against the root, bounded by staleness.
    try:
        live_epoch = authority.current_epoch(token.root_id)
    except UnverifiableRootError:
        if action_irreversible:
            raise UnverifiableRootError(
                f"cannot verify root {token.root_id} for irreversible action; failing closed"
            )
        return  # reversible action may proceed under recorded unverified-root flag

    if token.mint_epoch < live_epoch:
        raise RevokedCapabilityError(
            f"token {token.token_id} minted at epoch {token.mint_epoch}, "
            f"root {token.root_id} now at {live_epoch}: revoked"
        )

    # 3. Scope must cover the action (attenuation must not have widened).
    if not token.scope.get("covers_action", False):
        raise RevokedCapabilityError(
            f"token {token.token_id} scope does not cover requested action"
        )
