# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-revocation-epoch-has-silently-regressed-under-clock-skew.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-revocation-epoch-has-silently-regressed-under-clock-skew.warrant.json
# Markdown SHA-256:   cf357290556ed94ea90dfeac06ad43f99f6be20e9acaa463f932aaa79f048b32
# Code AST SHA-256:   1d2bb83ac8bb59b144646641a83cbe3da625ccc867b14ff1d63c8b317f136711
# Verified Classes:   EpochRegressionError, VerifierState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochRegressionError(RuntimeError):
    """Raised when a verifier's stored revocation epoch has regressed below
    its own acknowledged high-water mark, indicating silent state corruption
    rather than mere staleness."""


@dataclass
class VerifierState:
    agent_id: str
    stored_epoch: int
    acked_high_water: int          # max epoch this node ever acked outbound
    fetch_monotonic_ts: float      # CLOCK_MONOTONIC at time of the fetch
    issuer_authoritative_epoch: int


def admit_agent(
    state: VerifierState,
    now_monotonic: float,
    max_staleness_s: float = 0.8,
) -> bool:
    # Predicate 1: causal freshness. The stored epoch must not be below
    # anything this node has already acknowledged to the mesh.
    if state.stored_epoch < state.acked_high_water:
        raise EpochRegressionError(
            f"agent {state.agent_id!r}: stored_epoch={state.stored_epoch} "
            f"< acked_high_water={state.acked_high_water}; "
            f"state regressed, quarantine and re-sync from issuer"
        )

    # Predicate 1b: stored epoch must match the issuer's authoritative view.
    if state.stored_epoch != state.issuer_authoritative_epoch:
        raise EpochRegressionError(
            f"agent {state.agent_id!r}: stored_epoch={state.stored_epoch} "
            f"!= issuer_authoritative={state.issuer_authoritative_epoch}; "
            f"refusing to admit on staleness bound alone"
        )

    # Predicate 2: staleness bound on the fetch that produced stored_epoch,
    # measured against a monotonic clock (survives NTP steps and migration).
    age = now_monotonic - state.fetch_monotonic_ts
    if age < 0:
        # Monotonic clock went backwards => process/migration anomaly.
        raise EpochRegressionError(
            f"agent {state.agent_id!r}: negative fetch age {age:.3f}s; "
            f"monotonic base invalid, fail closed"
        )
    return age < max_staleness_s


def reconcile(states: list[VerifierState], now_monotonic: float) -> list[str]:
    """Return agent_ids that must be quarantined. Never raises; caller decides."""
    bad = []
    for s in states:
        try:
            admit_agent(s, now_monotonic)
        except EpochRegressionError:
            bad.append(s.agent_id)
    return bad
