# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-signed-agent-card-that-is-internally-consistent-but-stale-relative-to-the-discovery-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-signed-agent-card-that-is-internally-consistent-but-stale-relative-to-the-discovery-epoch.warrant.json
# Markdown SHA-256:   06f5e8798fbe3956e3d9bc7bbea858797229d946e7fc2802979ed16f49c4ce7e
# Code AST SHA-256:   02aa402969933610216b5b4b1c89a1fa3a7604ae16e4be02e062e543e26625ca
# Verified Classes:   StaleAgentCardError, EpochForkError, AgentCard, EpochGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleAgentCardError(RuntimeError):
    """Raised when a signed agent card is valid but older than the observed epoch."""
    pass


class EpochForkError(RuntimeError):
    """Raised when two distinct manifests claim the same epoch."""
    pass


@dataclass(frozen=True)
class AgentCard:
    identity: str
    epoch: int
    manifest_digest: str


class EpochGuard:
    def __init__(self) -> None:
        # identity -> (high_water_epoch, digest_at_that_epoch)
        self._marks: dict[str, tuple[int, str]] = {}

    def admit(self, card: AgentCard, *, signature_ok: bool, digest_ok: bool) -> None:
        if not signature_ok:
            raise StaleAgentCardError(f"signature failed for {card.identity}")
        if not digest_ok:
            raise StaleAgentCardError(f"manifest digest mismatch for {card.identity}")

        mark = self._marks.get(card.identity)
        if mark is None:
            # First contact: accept provisionally.
            self._marks[card.identity] = (card.epoch, card.manifest_digest)
            return

        high_water, digest_at_high_water = mark

        if card.epoch < high_water:
            raise StaleAgentCardError(
                f"stale card for {card.identity}: "
                f"observed epoch {card.epoch} < high-water {high_water}"
            )

        if card.epoch == high_water and card.manifest_digest != digest_at_high_water:
            raise EpochForkError(
                f"fork at epoch {card.epoch} for {card.identity}: "
                f"digest {card.manifest_digest} != {digest_at_high_water}"
            )

        # epoch > high_water, or idempotent re-observation: advance/confirm.
        self._marks[card.identity] = (card.epoch, card.manifest_digest)
