# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-signing-key-is-still-inside-the-grace-window-of-a-federated-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-signing-key-is-still-inside-the-grace-window-of-a-federated-peer.warrant.json
# Markdown SHA-256:   a93ee1b218ce98258e9842d09cf59fd352171971d1ddfbe352b8f5af817896ec
# Code AST SHA-256:   5f1ebc5d34586c935322a17c561ad4fa965490c81a8d4b300a6553fabb75e14d
# Verified Classes:   RevocationFreshnessError, Verification
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationFreshnessError(RuntimeError):
    """Raised when a consequential action would proceed on a peer-backed
    verification whose issuer freshness exceeds the issuer's revocation SLA."""


@dataclass(frozen=True)
class Verification:
    key_id: str
    issuer: str
    issuer_last_seen: float   # epoch seconds of last authoritative issuer statement
    peer_asserted_valid: bool
    admitted_at: float


def commit_gate(
    v: Verification,
    issuer_revocation_sla: float,
    grace: float,
    now: float | None = None,
) -> None:
    """Gate for consequential actions (tool calls, state mutation, funds).

    Admission into reasoning context may tolerate a lease; committing may not.
    """
    now = time.time() if now is None else now

    if not v.peer_asserted_valid:
        raise RevocationFreshnessError(
            f"peer asserts key {v.key_id} invalid; refuse commit"
        )

    issuer_age = now - v.issuer_last_seen

    # Danger zone: peer says valid, but issuer hasn't spoken within its own SLA.
    if issuer_age > issuer_revocation_sla:
        if issuer_age <= issuer_revocation_sla + grace:
            raise RevocationFreshnessError(
                f"key {v.key_id} from issuer {v.issuer}: peer-backed positive "
                f"but issuer freshness {issuer_age:.1f}s exceeds SLA "
                f"{issuer_revocation_sla:.1f}s (inside grace). "
                f"Commit requires live issuer check."
            )
        raise RevocationFreshnessError(
            f"key {v.key_id}: issuer freshness {issuer_age:.1f}s exceeds "
            f"SLA+grace {issuer_revocation_sla + grace:.1f}s; fail closed."
        )


def replay_from_checkpoint(
    v: Verification,
    issuer_revocation_sla: float,
    grace: float,
    now: float | None = None,
) -> None:
    """A resumed agent must NOT trust a persisted 'verified' boolean.
    It re-enters the commit gate, which re-queries issuer freshness."""
    # Deliberately re-run the gate; a persisted positive is not evidence.
    commit_gate(v, issuer_revocation_sla, grace, now=now)
