# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-revoked-mid-chain-while-a-grandchild-agent-still-holds-a-valid-looking-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-revoked-mid-chain-while-a-grandchild-agent-still-holds-a-valid-looking-warrant.warrant.json
# Markdown SHA-256:   f13daf3783305301247017479a79b908a832a639bc69a05d37e5505fcb3f18f3
# Code AST SHA-256:   70fe393c6bc4a58e6a8a8f0d9f1c466c3dbc9d27242fa8059f583e6e1f62e861
# Verified Classes:   ChainRevocationError, CapabilityToken, RevocationList
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ChainRevocationError(RuntimeError):
    """Raised when a token's ancestor was revoked but the leaf still looks valid."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    issuer_id: str
    scope: frozenset
    expires_at: float
    chain: list = field(default_factory=list)  # ancestor token_ids, root-first


class RevocationList:
    def __init__(self):
        self._revoked = {}  # token_id -> revoked_at

    def revoke(self, token_id):
        self._revoked[token_id] = time.time()

    def is_revoked(self, token_id):
        return token_id in self._revoked


def validate_at_use(token, revocation_list, now=None, max_depth=8):
    """
    Validate a delegated token. For depth >= 2, walking only the leaf is
    unsound: revocation of any ancestor must invalidate the leaf.
    """
    now = now if now is not None else time.time()

    if token.expires_at <= now:
        raise ChainRevocationError(f"token {token.token_id} expired")

    if len(token.chain) > max_depth:
        raise ChainRevocationError(
            f"delegation depth {len(token.chain)} exceeds max {max_depth}"
        )

    # Leaf-only check (the common, insufficient path).
    if revocation_list.is_revoked(token.token_id):
        raise ChainRevocationError(f"leaf token {token.token_id} revoked")

    # Chain-walk: the load-bearing invariant for depth >= 2.
    if len(token.chain) >= 2:
        for ancestor_id in token.chain:
            if revocation_list.is_revoked(ancestor_id):
                raise ChainRevocationError(
                    f"ancestor {ancestor_id} revoked; leaf {token.token_id} "
                    f"is a dead warrant (depth {len(token.chain)})"
                )
    return True


# Reproduction of the observed failure.
rl = RevocationList()
root = CapabilityToken("O0", "orchestrator", frozenset({"read:corpus", "spawn"}), time.time() + 3600, [])
planner = CapabilityToken("P1", "orchestrator", frozenset({"read:corpus", "spawn:analyst"}), time.time() + 3600, ["O0"])
analyst = CapabilityToken("A2", "P1", frozenset({"read:corpus"}), time.time() + 3600, ["O0", "P1"])

rl.revoke("P1")  # planner's authority cut mid-chain; A2 untouched.

# Leaf-only validation (buggy path) would pass A2:
assert not rl.is_revoked("A2")

# Correct validation must reject, because A2's warrant derives from revoked P1.
try:
    validate_at_use(analyst, rl)
    raise AssertionError("chain-walk failed to catch ancestor revocation")
except ChainRevocationError as e:
    print(f"detected: {e}")
