# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-revocation-across-a-federated-agent-handshake-when-the-revoking-authority-is-itself-mid-checkpoi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-revocation-across-a-federated-agent-handshake-when-the-revoking-authority-is-itself-mid-checkpoi.warrant.json
# Markdown SHA-256:   0923070394c077fa6f8661c53b6420774d8ad6bf6508fa8e6e316acf724b74c7
# Code AST SHA-256:   17be8785cd9c355613eff19af51707334d1d822c5b216072feba938115bbda5f
# Verified Classes:   StaleEpochAuthorizationError, FederatedDelegate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleEpochAuthorizationError(RuntimeError):
    """Raised when a verification verdict is valid but computed against an epoch
    older than the delegate's monotonic floor for that warrant."""
    pass


class FederatedDelegate:
    def __init__(self, warrant_id: str, issued_epoch: int):
        self.warrant_id = warrant_id
        # Floor is set from the handshake's issued epoch, NOT the first verdict,
        # so a delegate that starts mid-checkpoint cannot act on stale-valid.
        self.epoch_floor = issued_epoch

    def authorize_action(self, verdict: dict) -> None:
        # verdict: {"valid": bool, "epoch": int, "sig_ok": bool}
        if not verdict.get("sig_ok"):
            raise StaleEpochAuthorizationError(
                f"warrant {self.warrant_id}: unverifiable signature, refusing"
            )
        epoch = verdict["epoch"]
        if not verdict["valid"]:
            raise StaleEpochAuthorizationError(
                f"warrant {self.warrant_id}: explicit denial at epoch {epoch}"
            )
        if epoch < self.epoch_floor:
            # valid:true but older epoch -> revocation likely in flight behind
            # a checkpoint. Treat as denial, do NOT advance floor.
            raise StaleEpochAuthorizationError(
                f"warrant {self.warrant_id}: stale-valid verdict at epoch {epoch} "
                f"below floor {self.epoch_floor}; possible revocation behind checkpoint"
            )
        # Safe to act; advance the floor monotonically.
        self.epoch_floor = epoch


def handle_revalidation(delegate: FederatedDelegate, verdict: dict) -> str:
    try:
        delegate.authorize_action(verdict)
        return "acted"
    except StaleEpochAuthorizationError as e:
        # Halt and escalate; carry the epoch mismatch as evidence.
        return f"halted_and_escalated: {e}"
