# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-delegated-warrant-mid-chain-and-downstream-agents-keep-executing-on-cached-capability-grants.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-delegated-warrant-mid-chain-and-downstream-agents-keep-executing-on-cached-capability-grants.warrant.json
# Markdown SHA-256:   1796e20acd938d2ed1be8fe2ef6ae697548c9c1a8e24f991f68967a326f72709
# Code AST SHA-256:   16a36af91d24d1a3c6ed621d1f420fb7ca5f7f183d9db129ea597985c70fc24f
# Verified Classes:   StaleDerivedAuthorityError, Warrant, CachedCapability, RevocationOracle
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleDerivedAuthorityError(RuntimeError):
    """Raised when a derived capability is presented without a verifiable,
    unrevoked ancestry chain, or when its cached descriptor has outlived the
    last confirmed ancestry check."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    expires_at: float
    revoked: bool


@dataclass(frozen=True)
class CachedCapability:
    """What a leaf agent holds in hot state after negotiation."""
    warrant_id: str
    cached_expires_at: float
    last_ancestry_check: float
    max_staleness: float


class RevocationOracle:
    def __init__(self, warrants: dict[str, Warrant]):
        self._warrants = warrants

    def get(self, warrant_id: str) -> Warrant:
        return self._warrants[warrant_id]


def verify_derived_capability(
    cap: CachedCapability,
    chain: list[str],
    oracle: RevocationOracle,
    now: float,
) -> None:
    """Verify a derived capability at point of use.

    Invariant: a derived capability is valid only if (a) its own cached TTL has
    not lapsed, (b) the ancestry check is fresh within max_staleness, and
    (c) every warrant in the derivation chain exists and is unrevoked.
    """
    # (a) local TTL, clamped by staleness of the ancestry check.
    effective_expiry = min(
        cap.cached_expires_at,
        cap.last_ancestry_check + cap.max_staleness,
    )
    if now >= effective_expiry:
        raise StaleDerivedAuthorityError(
            f"capability {cap.warrant_id} effective expiry {effective_expiry} "
            f"<= now {now}; ancestry check stale or TTL lapsed"
        )

    # (b) chain must start at the presented warrant and terminate at a root.
    if not chain or chain[0] != cap.warrant_id:
        raise StaleDerivedAuthorityError(
            f"chain does not begin at presented warrant {cap.warrant_id}"
        )

    # (c) walk the full ancestry; any revoked or expired link is fatal.
    seen: set[str] = set()
    cursor = cap.warrant_id
    while cursor is not None:
        if cursor in seen:
            raise StaleDerivedAuthorityError(
                f"cycle detected in derivation chain at {cursor}"
            )
        seen.add(cursor)
        w = oracle.get(cursor)
        if w.revoked:
            raise StaleDerivedAuthorityError(
                f"ancestor warrant {cursor} revoked; derived authority dead"
            )
        if now >= w.expires_at:
            raise StaleDerivedAuthorityError(
                f"ancestor warrant {cursor} expired at {w.expires_at}"
            )
        cursor = w.parent_id

    # Chain length must match what was presented; a truncated chain is a
    # verification bypass attempt.
    if len(chain) != len(seen):
        raise StaleDerivedAuthorityError(
            f"presented chain length {len(chain)} != resolved ancestry {len(seen)}"
        )
