# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-branch-is-unsafe-to-commit-side-effect-leakage-across-rollback-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-branch-is-unsafe-to-commit-side-effect-leakage-across-rollback-boundaries.warrant.json
# Markdown SHA-256:   aa44bded55849f5c3cc5a35e817793e9731c2cd738819c6a0b26cd0877d805b6
# Code AST SHA-256:   4cab8466b628471612f657c50b308db73142dcf8a0e10c569cb3b1e5345d8166
# Verified Classes:   EffectClass, UnsafeCommitError, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    READ_ONLY = "read_only"
    UNDOABLE = "undoable"
    NON_UNDOABLE = "non_undoable"


class UnsafeCommitError(RuntimeError):
    """Raised when a winning branch would commit over unreconciled sibling effects."""


@dataclass
class Effect:
    tool: str
    klass: EffectClass
    undo_registered: bool = False
    compensated: bool = False


@dataclass
class Branch:
    name: str
    effects: list[Effect] = field(default_factory=list)
    quarantined: list[Effect] = field(default_factory=list)

    def record(self, effect: Effect) -> None:
        if effect.klass is EffectClass.NON_UNDOABLE:
            # Must be buffered until commit; never applied speculatively.
            self.quarantined.append(effect)
            return
        if effect.klass is EffectClass.UNDOABLE and not effect.undo_registered:
            raise UnsafeCommitError(
                f"branch {self.name}: undoable effect {effect.tool} "
                f"executed without pre-registered undo handler"
            )
        self.effects.append(effect)

    @property
    def has_unrecoverable_effect(self) -> bool:
        return any(
            e.klass is EffectClass.NON_UNDOABLE and not e.compensated
            for e in self.effects
        ) or bool(self.quarantined)


def commit_winner(winner: Branch, losers: list[Branch]) -> list[str]:
    """Commit winner only if every loser's effects are reconciled."""
    unreconciled = [
        b.name
        for b in losers
        if b.has_unrecoverable_effect
        and not all(e.compensated for e in b.effects)
    ]
    if unreconciled:
        raise UnsafeCommitError(
            f"refusing to commit {winner.name}: losing branches "
            f"{unreconciled} carry unrecoverable effects; "
            f"compensate or pin them before commit"
        )
    # Safe: drain quarantines of losers (dropped), apply winner's quarantine.
    for b in losers:
        b.quarantined.clear()
    applied = [e.tool for e in winner.quarantined]
    winner.quarantined.clear()
    return applied
