# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-capability-advertisement-that-was-valid-at-negotiation-time-but-stale-at-invocation-time-monotonic-capability-ep.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-capability-advertisement-that-was-valid-at-negotiation-time-but-stale-at-invocation-time-monotonic-capability-ep.warrant.json
# Markdown SHA-256:   f59afdadad2c7b9a8d864749858cffbabb104f4fbf29c36af040b74e6a7b19ae
# Code AST SHA-256:   de1fecd58d40d37342d8d8644e192827b1d45dff700796f7cb9c406cadc6b3d1
# Verified Classes:   StaleCapabilityEpochError, HeartbeatStalenessError, Warrant, EpochObservation, FederationInvoker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Callable, Literal


class StaleCapabilityEpochError(RuntimeError):
    """Raised when a negotiated warrant's capability epoch is behind the peer's live epoch."""


class HeartbeatStalenessError(RuntimeError):
    """Raised when the epoch heartbeat is older than the configured staleness bound."""


CurrencyClass = Literal["tolerant", "critical"]


@dataclass(frozen=True)
class Warrant:
    peer_id: str
    capability: str
    bound_epoch: int
    policy_digest: str
    expiry_ts: float
    currency: CurrencyClass


@dataclass(frozen=True)
class EpochObservation:
    peer_id: str
    live_epoch: int
    observed_ts: float


class FederationInvoker:
    def __init__(
        self,
        get_epoch: Callable[[str], EpochObservation],
        renegotiate: Callable[[str, str], Warrant],
        heartbeat_ttl_s: float = 30.0,
        clock: Callable[[], float] = time.time,
    ) -> None:
        self._get_epoch = get_epoch
        self._renegotiate = renegotiate
        self._ttl = heartbeat_ttl_s
        self._clock = clock

    def _observe_epoch(self, peer_id: str) -> EpochObservation:
        obs = self._get_epoch(peer_id)
        age = self._clock() - obs.observed_ts
        if age > self._ttl:
            raise HeartbeatStalenessError(
                f"epoch heartbeat for {peer_id} is {age:.1f}s old, ttl={self._ttl}s"
            )
        return obs

    def invoke(self, warrant: Warrant, payload: dict) -> dict:
        # Expiry is necessary but not sufficient.
        if self._clock() > warrant.expiry_ts:
            raise StaleCapabilityEpochError(
                f"warrant for {warrant.capability} on {warrant.peer_id} expired"
            )

        if warrant.currency == "tolerant":
            # Best-effort currency check; a mismatch is handled by one renegotiation.
            obs = self._observe_epoch(warrant.peer_id)
            if obs.live_epoch != warrant.bound_epoch:
                warrant = self._renegotiate(warrant.peer_id, warrant.capability)
            return self._send(warrant, payload)

        # currency == "critical": must re-check immediately before side effect.
        obs = self._observe_epoch(warrant.peer_id)
        if obs.live_epoch != warrant.bound_epoch:
            raise StaleCapabilityEpochError(
                f"peer {warrant.peer_id} advanced epoch "
                f"{warrant.bound_epoch} -> {obs.live_epoch}; "
                f"warrant for {warrant.capability} is stale and MUST NOT be invoked"
            )
        return self._send(warrant, payload)

    def _send(self, warrant: Warrant, payload: dict) -> dict:
        # Transport is elided; the point is that only currency-verified warrants reach here.
        return {"peer": warrant.peer_id, "capability": warrant.capability, "ok": True}


def resume_after_checkpoint(
    invoker: FederationInvoker,
    restored_warrants: list[Warrant],
    restored_last_epoch_check: dict[str, float],
) -> list[Warrant]:
    """On resume, force a currency re-check for every critical warrant.

    A resumed agent that cannot prove it has seen the peer's current epoch
    is epistemically cold-started and must not assume continuity.
    """
    now = invoker._clock()
    for w in restored_warrants:
        if w.currency != "critical":
            continue
        last = restored_last_epoch_check.get(w.peer_id, 0.0)
        if now - last > invoker._ttl:
            obs = invoker._observe_epoch(w.peer_id)
            if obs.live_epoch != w.bound_epoch:
                raise StaleCapabilityEpochError(
                    f"resume: peer {w.peer_id} epoch moved {w.bound_epoch} -> "
                    f"{obs.live_epoch}; renegotiate before invoking {w.capability}"
                )
    return restored_warrants
