# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-revoked-agent-from-re-entering-a-federated-mesh-through-a-warm-capability-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-revoked-agent-from-re-entering-a-federated-mesh-through-a-warm-capability-cache.warrant.json
# Markdown SHA-256:   2479afe10bddd7cbe8179a3e0700bf46039113b41b2c9ac05be88f524fffc8c3
# Code AST SHA-256:   7e6685dfac961516c2a33c4c4702205be2376dbbdacde759b9e3e1d99de49e1a
# Verified Classes:   StaleWarrantError, EpochRegressionError, Warrant, Verifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a presented warrant's epoch predates the verifier's high-water-mark."""


class EpochRegressionError(RuntimeError):
    """Raised when the IdP attempts to advance a subject's epoch non-monotonically."""


@dataclass
class Warrant:
    subject: str
    capability: str
    epoch: int
    expires_at: float


@dataclass
class Verifier:
    # Durable high-water-mark: subject -> highest epoch observed.
    high_water_mark: dict = field(default_factory=dict)
    # Warm authorization cache keyed on (subject, capability, epoch).
    cache: dict = field(default_factory=dict)

    def observe_revocation(self, subject: str, new_epoch: int) -> None:
        current = self.high_water_mark.get(subject, 0)
        if new_epoch <= current:
            raise EpochRegressionError(
                f"epoch regression for {subject}: {current} -> {new_epoch}"
            )
        self.high_water_mark[subject] = new_epoch

    def authorize(self, warrant: Warrant, now: float | None = None) -> bool:
        now = time.time() if now is None else now
        if warrant.expires_at <= now:
            raise StaleWarrantError(f"warrant expired for {warrant.subject}")

        # Monotonic guard: refuse anything older than what we know.
        hwm = self.high_water_mark.get(warrant.subject, 0)
        if warrant.epoch < hwm:
            raise StaleWarrantError(
                f"presented epoch {warrant.epoch} < high-water-mark {hwm} "
                f"for {warrant.subject}; cache not consulted"
            )

        key = (warrant.subject, warrant.capability, warrant.epoch)
        if key in self.cache:
            return self.cache[key]

        # Cold path: negotiate, then cache under the versioned key.
        granted = self._negotiate(warrant)
        self.cache[key] = granted
        return granted

    def _negotiate(self, warrant: Warrant) -> bool:
        # Placeholder for real capability negotiation (schema + scope check).
        return True
