# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-multi-agent-branch-commit-a-partial-side-effect-when-the-reconciler-aborts-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-multi-agent-branch-commit-a-partial-side-effect-when-the-reconciler-aborts-it.warrant.json
# Markdown SHA-256:   5950b059f5f63d69ab897f2148369e2dc4ada38912d78854eed27c447f245656
# Code AST SHA-256:   dfe50fbdde04d3f184896f2163769b39c9a5efa51f71a1d1af756e64ef8d365d
# Verified Classes:   IrreversibleAbortError, EffectIntent, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class IrreversibleAbortError(RuntimeError):
    """Raised when an abort would silently leak an irreversible side effect."""


@dataclass
class EffectIntent:
    branch_id: str
    effect_id: str
    target: str
    idempotency_key: str
    reversible: bool


@dataclass
class EffectLedger:
    _entries: dict[str, list[EffectIntent]] = field(default_factory=dict)

    def record(self, intent: EffectIntent) -> None:
        # Write-ahead: called BEFORE the branch emits the external effect.
        self._entries.setdefault(intent.branch_id, []).append(intent)

    def for_branch(self, branch_id: str) -> list[EffectIntent]:
        return list(self._entries.get(branch_id, []))


def abort_branch(branch_id: str, ledger: EffectLedger) -> list[str]:
    """Reconcile the effect ledger, then tear down. May refuse to abort."""
    intents = ledger.for_branch(branch_id)
    irreversible = [i for i in intents if not i.reversible]
    if irreversible:
        # Aborting here would leave an un-undoable trace. Refuse loudly.
        raise IrreversibleAbortError(
            f"branch {branch_id} emitted irreversible effects "
            f"{[i.effect_id for i in irreversible]}; abort would leak them"
        )
    # Compensate reversible effects keyed on the ledger, not branch-local state.
    compensations = [f"compensate:{i.effect_id}@{i.idempotency_key}" for i in intents]
    # Only after the ledger is fully reconciled is state teardown safe.
    return compensations
