# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-revoked-agent-warrants-from-resurrecting-across-crdt-partitioned-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-revoked-agent-warrants-from-resurrecting-across-crdt-partitioned-swarms.warrant.json
# Markdown SHA-256:   4c47ee666a6441f8d7a559b8f6f0268fa3d3201c559238147d1624de26f6283b
# Code AST SHA-256:   d7c9c09762abde1bae2ff5bdae0bb0801896daefbbd111f33bc8274fc4a77841
# Verified Classes:   RevocationResurrectionError, Tombstone, MonotoneRevocationSet
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class RevocationResurrectionError(RuntimeError):
    """Raised when a merge would resurrect a revoked warrant or when a
    capability check cannot be proven safe under partition."""
    pass


@dataclass(frozen=True)
class Tombstone:
    warrant_id: str
    revocation_epoch: int
    revoking_authority: str
    hlc: tuple  # (physical, counter)


@dataclass
class MonotoneRevocationSet:
    """Grow-only tombstone set. Merge is union. No winner. No LWW."""
    _tombstones: FrozenSet[Tombstone] = field(default_factory=frozenset)

    def revoke(self, ts: Tombstone) -> "MonotoneRevocationSet":
        return MonotoneRevocationSet(self._tombstones | {ts})

    def merge(self, other: "MonotoneRevocationSet") -> "MonotoneRevocationSet":
        merged = self._tombstones | other._tombstones
        # Invariant guard: merge must be monotone. It is, by construction,
        # but we assert it explicitly so a future "optimization" that
        # drops tombstones fails loudly instead of silently resurrecting.
        if not self._tombstones.issubset(merged):
            raise RevocationResurrectionError(
                "merge decreased the revoked set; non-resurrection invariant violated"
            )
        return MonotoneRevocationSet(merged)

    def is_revoked(self, warrant_id: str, issue_epoch: int) -> bool:
        return any(
            t.warrant_id == warrant_id and t.revocation_epoch >= issue_epoch
            for t in self._tombstones
        )


def authorize_tool_call(
    warrant_id: str,
    issue_epoch: int,
    revoked: MonotoneRevocationSet,
    partitioned: bool,
    high_privilege: bool,
) -> None:
    if revoked.is_revoked(warrant_id, issue_epoch):
        raise RevocationResurrectionError(
            f"warrant {warrant_id}@epoch{issue_epoch} is in the monotone revoked set"
        )
    if partitioned and high_privilege:
        # Absence of a tombstone under partition is NOT evidence of non-revocation.
        raise RevocationResurrectionError(
            f"cannot prove non-revocation of high-privilege warrant {warrant_id} "
            f"under partition; failing closed"
        )
    return None


def apply_lww_merge_unsafe(
    local: str, local_hlc: tuple, remote: str, remote_hlc: tuple
) -> str:
    """Demonstrates the unsafe pattern: LWW resolves revoke-vs-renew by
    timestamp and can resurrect a REVOKED warrant. Do not use."""
    winner = local if local_hlc >= remote_hlc else remote
    if local == "REVOKED" and winner == "ACTIVE":
        raise RevocationResurrectionError(
            "LWW merge resurrected a revoked warrant: renewal_after_revoke "
            "won the timestamp tiebreak; use monotone tombstone set instead"
        )
    return winner
