# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-delegation-warrant-that-arrives-mid-execution-when-the-peer-agent-s-tool-calls-are-already-in-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-delegation-warrant-that-arrives-mid-execution-when-the-peer-agent-s-tool-calls-are-already-in-flight.warrant.json
# Markdown SHA-256:   09a9f640467e61eee443bafe4a3dbe2794719ec618f58894184c1e855a8b98eb
# Code AST SHA-256:   93a47fe5810e1c36edda2b5d618016e4ff66df3dd051671108372f448042d6e5
# Verified Classes:   RevokedWarrantEffectError, EffectState, InFlightEffect, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RevokedWarrantEffectError(RuntimeError):
    """Raised when an effect commits or is found committed under a revoked warrant
    and cannot be silently reconciled."""
    pass


class EffectState(Enum):
    QUEUED = "queued"
    COMMITTED = "committed"
    COMPENSATED = "compensated"
    DROPPED = "dropped"


@dataclass
class InFlightEffect:
    effect_id: str
    tool: str
    compensable: bool
    state: EffectState = EffectState.QUEUED


@dataclass
class EffectLedger:
    effects: dict[str, InFlightEffect] = field(default_factory=dict)

    def record(self, effect: InFlightEffect) -> None:
        self.effects[effect.effect_id] = effect


def reconcile_on_revocation(
    ledger: EffectLedger,
    warrant_id: str,
    status_list_revoked: bool,
) -> list[str]:
    """Walk the in-flight effect ledger at revocation observation.

    Returns the list of effect_ids that were committed under revoked authority
    and are NOT compensable -- these must be escalated, never reported as a
    plain task failure.
    """
    if not status_list_revoked:
        return []

    unaccounted: list[str] = []
    for eff in ledger.effects.values():
        if eff.state is EffectState.QUEUED:
            # Not yet committed: safe to drop at dequeue re-check.
            eff.state = EffectState.DROPPED
        elif eff.state is EffectState.COMMITTED:
            if eff.compensable:
                eff.state = EffectState.COMPENSATED
            else:
                # Irreversible effect already committed under a warrant that
                # is now revoked. A bare "task failed" would hide this.
                unaccounted.append(eff.effect_id)

    if unaccounted:
        raise RevokedWarrantEffectError(
            f"warrant {warrant_id} revoked; irreversible effects already "
            f"committed and not reconcilable: {unaccounted}. "
            f"Escalate with explicit effect inventory; do not report plain failure."
        )
    return unaccounted
