# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-agent-registration-the-revocation-propagation-staleness-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-agent-registration-the-revocation-propagation-staleness-window.warrant.json
# Markdown SHA-256:   5f9fd1a515c211047288f5e0d4fde5eb5ce89ef26d7928098aee545bf3d751c7
# Code AST SHA-256:   f2d850373fd6960d757689fdf40b4dc4f8a87fe8c45bb620319bd6212493e30d
# Verified Classes:   RevocationFreshnessError, StatusDocument
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
import time
from dataclasses import dataclass


class RevocationFreshnessError(RuntimeError):
    """Raised when a 'not revoked' assertion cannot be proven current."""
    pass


@dataclass(frozen=True)
class StatusDocument:
    subject: str
    revoked: bool
    version: int
    fetched_at: float      # monotonic seconds
    valid_until: float     # monotonic seconds
    issuer_propagation_deadline: float


def admit_agent(
    doc: StatusDocument,
    last_seen_version: int,
    now: float | None = None,
    safety_margin: float = 0.5,
) -> bool:
    now = time.monotonic() if now is None else now

    # Revoked always wins; freshness cannot rescue it.
    if doc.revoked:
        return False

    # Monotonic non-regression: never trust a rolled-back status version.
    if doc.version < last_seen_version:
        raise RevocationFreshnessError(
            f"status version regression for {doc.subject}: "
            f"got {doc.version}, previously {last_seen_version}"
        )

    # Freshness gate: a valid bit is only evidence if it is provably current.
    if now + safety_margin >= doc.valid_until:
        raise RevocationFreshnessError(
            f"stale status for {doc.subject}: valid_until={doc.valid_until:.3f} "
            f"<= now+margin ({now + safety_margin:.3f}); abstain"
        )

    age = now - doc.fetched_at
    if age > doc.issuer_propagation_deadline:
        raise RevocationFreshnessError(
            f"status age {age:.3f}s exceeds issuer propagation deadline "
            f"{doc.issuer_propagation_deadline:.3f}s for {doc.subject}"
        )

    return True
