# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-capability-is-still-live-in-a-delegated-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-capability-is-still-live-in-a-delegated-agent-chain.warrant.json
# Markdown SHA-256:   2ef1d13bebdc74e42b07d783c7e37bf4b4c0f8bf9354d3fc024e0290722be4c3
# Code AST SHA-256:   4eb47d2c276a515f17978bf07a4e40dfb42b2d995b8c362f18accbd1fdcb9b42
# Verified Classes:   CapabilityResurrectionError, Capability, Checkpoint, AuthorityRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityResurrectionError(RuntimeError):
    """Raised when a resumed execution continues under a capability whose
    ancestor chain has been revoked since the checkpoint was written."""


@dataclass
class Capability:
    cap_id: str
    scope: str
    parent_id: Optional[str]
    minted_at: float
    ttl_seconds: float
    revoked_at: Optional[float] = None

    def is_live(self, now: float) -> bool:
        if self.revoked_at is not None and now >= self.revoked_at:
            return False
        return now < self.minted_at + self.ttl_seconds


@dataclass
class Checkpoint:
    # NOTE: stores a reference, never a boolean. This is the invariant.
    capability_id: str
    delegation_chain_hash: str
    step: int


class AuthorityRegistry:
    def __init__(self) -> None:
        self._caps: dict[str, Capability] = {}

    def register(self, cap: Capability) -> None:
        self._caps[cap.cap_id] = cap

    def revoke(self, cap_id: str, at: float) -> None:
        cap = self._caps[cap_id]
        cap.revoked_at = at
        # Cascade revocation down the delegation tree.
        for child in self._caps.values():
            if child.parent_id == cap_id:
                self.revoke(child.cap_id, at)

    def chain_is_live(self, cap_id: str, now: float) -> bool:
        seen: set[str] = set()
        cur: Optional[str] = cap_id
        while cur is not None:
            if cur in seen:
                raise CapabilityResurrectionError(
                    f"cycle detected in delegation chain at {cur}"
                )
            seen.add(cur)
            cap = self._caps.get(cur)
            if cap is None:
                return False
            if not cap.is_live(now):
                return False
            cur = cap.parent_id
        return True


def resume_execution(
    registry: AuthorityRegistry,
    checkpoint: Checkpoint,
    now: Optional[float] = None,
) -> int:
    """Resume a checkpointed execution, re-deriving authority from live state.

    The checkpoint carries a capability_id, not an `authorized` flag, so the
    authority is re-derived against the current revocation state. If any
    ancestor in the delegation chain has been revoked, this raises rather
    than continuing under a resurrected capability.
    """
    now = time.time() if now is None else now

    if not registry.chain_is_live(checkpoint.capability_id, now):
        raise CapabilityResurrectionError(
            f"refusing to resume step {checkpoint.step}: capability "
            f"{checkpoint.capability_id} (chain hash "
            f"{checkpoint.delegation_chain_hash[:12]}) is no longer live; "
            f"an ancestor was revoked after the checkpoint was written"
        )

    # Authority re-derived; safe to continue.
    return checkpoint.step
