# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-stale-revocation-epoch-during-cross-domain-agent-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-stale-revocation-epoch-during-cross-domain-agent-delegation.warrant.json
# Markdown SHA-256:   f2028a210369ff71807d75eb8b5617e8bcf10b825bf5b60e57ca63c90b4d43f8
# Code AST SHA-256:   da23288a475da5f0764be195e3713d3cdb5d8b9533569632baa525c75c61eeae
# Verified Classes:   StaleRevocationEpochError, EpochObservation, Warrant, Delegate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationEpochError(RuntimeError):
    """Raised when a delegate cannot prove its revocation epoch is fresh enough to act."""


@dataclass(frozen=True)
class EpochObservation:
    epoch: int
    observed_at: float          # issuer-signed monotonic timestamp, not delegate clock
    issuer_signature: bytes


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    epoch: int
    not_after: float
    max_staleness: float        # negotiated at delegation, must be < remaining lifetime


class Delegate:
    def __init__(self, warrant: Warrant, clock=time.monotonic):
        self.warrant = warrant
        self._clock = clock
        self._last: EpochObservation | None = None
        self._last_refresh_failed = False

    def record_refresh(self, obs: EpochObservation) -> None:
        # A successful refresh replaces the observation; a failure must NOT.
        if obs.epoch < self.warrant.epoch:
            raise StaleRevocationEpochError(
                f"epoch regression for {self.warrant.warrant_id}: "
                f"observed {obs.epoch} < warrant {self.warrant.epoch}"
            )
        self._last = obs
        self._last_refresh_failed = False

    def record_refresh_failure(self) -> None:
        # Critically: do not touch self._last.observed_at. The age keeps growing.
        self._last_refresh_failed = True

    def authorize_action(self) -> None:
        w = self.warrant
        if self._last is None:
            raise StaleRevocationEpochError(
                f"no epoch observation for {w.warrant_id}; cannot prove liveness"
            )
        age = self._clock() - self._last.observed_at
        if age > w.max_staleness:
            raise StaleRevocationEpochError(
                f"epoch observation for {w.warrant_id} is stale: "
                f"age={age:.1f}s > max_staleness={w.max_staleness:.1f}s "
                f"(last_refresh_failed={self._last_refresh_failed})"
            )
        if self._last.epoch < w.epoch:
            raise StaleRevocationEpochError(
                f"warrant {w.warrant_id} revoked: observed {self._last.epoch} "
                f"< required {w.epoch}"
            )
        if self._clock() > w.not_after:
            raise StaleRevocationEpochError(
                f"warrant {w.warrant_id} expired at {w.not_after}"
            )
        # Only here is authority proven fresh and monotonic.
