# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-executing-on-a-revoked-aaif-warrant-the-stale-authorization-window-in-continuous-policy-evaluation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-executing-on-a-revoked-aaif-warrant-the-stale-authorization-window-in-continuous-policy-evaluation.warrant.json
# Markdown SHA-256:   658d6b71358f70b9ddac406186f7b3d363ae3b5d4760b6a49e7346c5cffa062d
# Code AST SHA-256:   a963a67f0abe60239be206a01ef3b65fa54fdbab5e3ebb805687167b4b05bd92
# Verified Classes:   StaleAuthorizationError, FencedAction
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleAuthorizationError(RuntimeError):
    """Raised when a side effect would commit under a superseded warrant epoch.

    This is non-retryable without re-authorization: the agent must re-acquire
    a warrant at the current epoch before the action may be attempted again.
    """


@dataclass(frozen=True)
class FencedAction:
    warrant_id: str
    check_epoch: int          # revocation_epoch observed at pre-flight check
    tool: str
    idempotent: bool          # if True, optimistic commit is permitted
    compensable: bool         # if True, post-hoc reconciliation is permitted


def commit_side_effect(action: FencedAction, current_epoch: int, committed_effects: list) -> None:
    """Enforce the fencing invariant before acknowledging a mutating action.

    Invariant: no non-idempotent, non-compensable effect may commit when the
    policy store's epoch has advanced past the epoch observed at check time.
    """
    if current_epoch > action.check_epoch:
        # Authority was withdrawn (or re-issued) between check and commit.
        if not action.idempotent and not action.compensable:
            # Fenced commit: fail closed, do not touch the world.
            raise StaleAuthorizationError(
                f"warrant {action.warrant_id} checked at epoch {action.check_epoch} "
                f"but store is at epoch {current_epoch}; tool={action.tool} is "
                f"non-idempotent and non-compensable — commit refused, "
                f"agent must re-authorize at epoch {current_epoch}"
            )
        # Idempotent/compensable path: commit allowed, but flag for reconciliation.
        committed_effects.append(
            {"warrant_id": action.warrant_id, "tool": action.tool,
             "check_epoch": action.check_epoch, "commit_epoch": current_epoch,
             "needs_reconciliation": True}
        )
        return

    committed_effects.append(
        {"warrant_id": action.warrant_id, "tool": action.tool,
         "check_epoch": action.check_epoch, "commit_epoch": current_epoch,
         "needs_reconciliation": False}
    )


def reconcile_after_revocation(committed_effects: list, revoked_epoch: int) -> list:
    """Agent obligation on learning of revocation: enumerate tainted effects."""
    tainted = [
        e for e in committed_effects
        if e["commit_epoch"] >= revoked_epoch or e["needs_reconciliation"]
    ]
    if not tainted:
        return []
    # Surface every side effect that landed at or after the revoking epoch so
    # the operator (or a compensating agent) can act on it. Do not silently drop.
    return tainted
