# 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-session-when-the-revocation-signal-races-the-token-s-own-expiry-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-capability-token-was-revoked-mid-session-when-the-revocation-signal-races-the-token-s-own-expiry-window.warrant.json
# Markdown SHA-256:   bdf84b9880e63ddffeb8604e0770416bb01865249c6b715fcedd928fe24d01dd
# Code AST SHA-256:   de6638dee4b5d5a46faaba87615efa6286246f022a53e9ae99faab6be7e35c41
# Verified Classes:   RevocationIndeterminate, Token, RevocationView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Mapping, Sequence


class RevocationIndeterminate(RuntimeError):
    """Raised when a token's authorization state cannot be soundly determined."""


@dataclass(frozen=True)
class Token:
    jti: str
    parent_jti: str | None
    exp: float           # absolute epoch seconds
    scopes: frozenset[str]


@dataclass(frozen=True)
class RevocationView:
    version: int
    observed_at: float   # epoch seconds when this view was fetched
    revoked: frozenset[str]


def assert_chain_authorized(
    presented: Token,
    chain: Sequence[Token],
    view: RevocationView,
    max_staleness: float,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Freshness bound: an old view is not evidence of non-revocation.
    if now - view.observed_at > max_staleness:
        raise RevocationIndeterminate(
            f"revocation view v{view.version} is stale by "
            f"{now - view.observed_at:.1f}s > max_staleness {max_staleness:.1f}s"
        )

    # The view must be no older than the shortest remaining lifetime,
    # otherwise the token can expire before the next required poll.
    shortest_remaining = min(t.exp for t in chain) - now
    if shortest_remaining <= 0:
        raise RevocationIndeterminate(
            f"token chain contains an expired link; remaining={shortest_remaining:.1f}s"
        )
    if max_staleness >= shortest_remaining:
        raise RevocationIndeterminate(
            f"max_staleness {max_staleness:.1f}s >= shortest remaining "
            f"{shortest_remaining:.1f}s; freshness cannot be guaranteed"
        )

    # Chain-aware check: any ancestor revoked severs the whole chain.
    for link in chain:
        if link.jti in view.revoked:
            raise RevocationIndeterminate(
                f"ancestor {link.jti} revoked (presented={presented.jti}); "
                f"descendant authority is severed"
            )

    # Scope narrowing invariant: a child may never exceed its parent's scopes.
    for parent, child in zip(chain, chain[1:]):
        if not child.scopes <= parent.scopes:
            raise RevocationIndeterminate(
                f"scope escalation: {child.jti} grants "
                f"{child.scopes - parent.scopes} not held by {parent.jti}"
            )


def guarded_write(
    presented: Token,
    chain: Sequence[Token],
    view: RevocationView,
    max_staleness: float,
    path: str,
) -> None:
    assert_chain_authorized(presented, chain, view, max_staleness)
    if not any(s.startswith("tool:filesystem:write:") for s in presented.scopes):
        raise RevocationIndeterminate(
            f"presented token {presented.jti} lacks write scope for {path}"
        )
    # ... perform the write only after the gate has passed ...
