# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-federation-registry-entries-from-resurrecting-revoked-cross-org-agent-capabilities.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-federation-registry-entries-from-resurrecting-revoked-cross-org-agent-capabilities.warrant.json
# Markdown SHA-256:   3a87080493d01a25ccdec974eb60c4d0b38e9ac801f7ec3ca1469460b1a2acb0
# Code AST SHA-256:   263621b298ecbfd793be0873a5cfd903615ce8cd9901063fe1b69aa3cdc6d1bb
# Verified Classes:   WarrantResurrectionError, Warrant, ReplicaView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class WarrantResurrectionError(RuntimeError):
    """Raised when a re-advertised warrant bypasses revocation via ID reminting
    or when verification binds to a stale revocation epoch."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    capability: str
    delegation_depth: int
    not_after: float
    revocation_epoch: int
    # Immutable, content-addressed identity. NOT minted at re-advertisement.
    warrant_id: str


def derive_warrant_id(issuer: str, subject: str, capability: str, depth: int) -> str:
    # Content-addressed: same logical capability => same ID across re-advertisement.
    payload = f"{issuer}|{subject}|{capability}|{depth}".encode()
    return hashlib.sha256(payload).hexdigest()


@dataclass
class ReplicaView:
    known_epoch: int
    revoked_ids: frozenset
    max_staleness: int


def verify_warrant(w: Warrant, replica: ReplicaView, now: float) -> None:
    if now > w.not_after:
        raise WarrantResurrectionError(f"warrant {w.warrant_id} expired")

    # Invariant 1: identity must be content-addressed, not reminted.
    expected_id = derive_warrant_id(w.issuer, w.subject, w.capability, w.delegation_depth)
    if w.warrant_id != expected_id:
        raise WarrantResurrectionError(
            f"warrant ID {w.warrant_id} does not match content address {expected_id}; "
            "re-advertisement reminted identity, defeating revocation keying"
        )

    # Invariant 2: epoch-bound verification with enforced staleness ceiling.
    if replica.known_epoch - w.revocation_epoch > replica.max_staleness:
        raise WarrantResurrectionError(
            f"replica epoch {replica.known_epoch} lags warrant epoch "
            f"{w.revocation_epoch} beyond staleness ceiling {replica.max_staleness}; "
            "revocation state unbounded, must block or sync"
        )

    if w.warrant_id in replica.revoked_ids:
        raise WarrantResurrectionError(f"warrant {w.warrant_id} is revoked")


def dispatch_task(w: Warrant, replica: ReplicaView) -> str:
    verify_warrant(w, replica, time.time())
    return f"dispatched {w.capability} to {w.subject}"
