# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-attestation-that-survived-registry-federation-gossip.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-attestation-that-survived-registry-federation-gossip.warrant.json
# Markdown SHA-256:   802c730694cd5f815ba1559d73987aa804a031fc28e15032e8ad70d47c96c0da
# Code AST SHA-256:   52cf8804b82ccc9d7321efa19fde09c292db335277b39789089db1635e303d56
# Verified Classes:   StaleAttestationError, Attestation, AttestationGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a discovered peer's capability attestation cannot be trusted at dispatch time."""


@dataclass(frozen=True)
class Attestation:
    peer_id: str
    attester_key_id: str
    attester_sequence: int
    not_after: float  # local monotonic deadline, already converted from wall clock at issuance
    tool_surface: frozenset


class AttestationGate:
    def __init__(self, current_key_ids: set[str]):
        self._current_key_ids = frozenset(current_key_ids)
        self._last_seq: dict[str, int] = {}

    def admit(self, att: Attestation, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now

        if att.attester_key_id not in self._current_key_ids:
            raise StaleAttestationError(
                f"peer {att.peer_id}: attester key {att.attester_key_id} rotated out of current key set"
            )

        if now >= att.not_after:
            raise StaleAttestationError(
                f"peer {att.peer_id}: attestation expired at {att.not_after:.3f}, now {now:.3f}"
            )

        prior = self._last_seq.get(att.peer_id)
        if prior is not None and att.attester_sequence <= prior:
            raise StaleAttestationError(
                f"peer {att.peer_id}: attester sequence {att.attester_sequence} "
                f"not strictly greater than last accepted {prior} (gossip resurrection)"
            )

        self._last_seq[att.peer_id] = att.attester_sequence


def dispatch_batch(gate: AttestationGate, att: Attestation, tasks: list[str]) -> list[str]:
    gate.admit(att)  # raises StaleAttestationError before any task leaves the instance
    if "write_file" in att.tool_surface:
        return [f"{t}:rw" for t in tasks]
    return [f"{t}:ro" for t in tasks]
