# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-agent-branch-and-lose-the-side-effects-it-cannot-un-execute.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-agent-branch-and-lose-the-side-effects-it-cannot-un-execute.warrant.json
# Markdown SHA-256:   e1e7b51e6c69b8adf12a69b5e036446a72cf1e80fb374a0568d9f72e1a341249
# Code AST SHA-256:   a94f97caea8653a85615b4f2f29c7865faf107fad5f474c280be55ef4323097b
# Verified Classes:   EffectClass, SpeculativeRollbackViolation, ToolCall, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a branch is pruned while holding an unowned world mutation."""


@dataclass
class ToolCall:
    name: str
    effect_class: EffectClass
    compensator_handle: Optional[str] = None
    compensator_confirmed: bool = False


@dataclass
class Branch:
    branch_id: str
    calls: list[ToolCall] = field(default_factory=list)


def prune_branch(branch: Branch, committed_branch_id: str) -> None:
    orphaned = []
    for call in branch.calls:
        if call.effect_class is EffectClass.IRREVERSIBLE:
            orphaned.append(call.name)
        elif call.effect_class is EffectClass.REVERSIBLE and not call.compensator_confirmed:
            orphaned.append(call.name)

    if orphaned:
        raise SpeculativeRollbackViolation(
            f"branch {branch.branch_id} pruned while committed branch is "
            f"{committed_branch_id}; orphaned world mutations: {orphaned}. "
            f"Reasoning rollback cannot compensate these; reconstruct ownership "
            f"from the speculative call ledger before committing."
        )


def speculate(branch: Branch, call: ToolCall) -> None:
    if call.effect_class is EffectClass.IRREVERSIBLE:
        raise SpeculativeRollbackViolation(
            f"refusing to execute irreversible call {call.name} on speculative "
            f"branch {branch.branch_id}; must be deferred to commit"
        )
    if call.effect_class is EffectClass.REVERSIBLE and not call.compensator_confirmed:
        raise SpeculativeRollbackViolation(
            f"reversible call {call.name} has no confirmed compensator handle; "
            f"treating as irreversible and refusing speculative execution"
        )
    branch.calls.append(call)
