# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-pruned-speculative-branch-as-non-restorable-during-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-pruned-speculative-branch-as-non-restorable-during-multi-agent-rollback.warrant.json
# Markdown SHA-256:   aee72cc02491da59cf8ee45d1a48c39fbe7a22ff82d50ac23632cc27a9e2ae17
# Code AST SHA-256:   406434def80acea7e1fa0bd7fc681dd1917a3244ac25a935b3cd1a3b5e6d5d40
# Verified Classes:   EffectClass, NonRestorableBranchError, ToolEffect, SpeculativeBranch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    OVERLAY_CONTAINED = "overlay_contained"
    IDEMPOTENT_EXTERNAL = "idempotent_external"
    NON_RESTORABLE = "non_restorable"


class NonRestorableBranchError(RuntimeError):
    """Raised when a pruned speculative branch left non-rollbackable world effects."""


@dataclass
class ToolEffect:
    tool: str
    target: str
    idempotency_key: str | None
    in_overlay: bool


@dataclass
class SpeculativeBranch:
    branch_id: str
    effects: list[ToolEffect] = field(default_factory=list)
    pruned: bool = False


def classify_branch(branch: SpeculativeBranch) -> EffectClass:
    if all(e.in_overlay for e in branch.effects):
        return EffectClass.OVERLAY_CONTAINED
    external = [e for e in branch.effects if not e.in_overlay]
    if all(e.idempotency_key for e in external):
        return EffectClass.IDEMPOTENT_EXTERNAL
    return EffectClass.NON_RESTORABLE


def safe_to_resume_siblings(pruned: SpeculativeBranch) -> bool:
    cls = classify_branch(pruned)
    if cls is EffectClass.OVERLAY_CONTAINED:
        return True
    if cls is EffectClass.IDEMPOTENT_EXTERNAL:
        # Caller must still issue and confirm compensating deletes before resume;
        # returning True here only signals the branch is *compensable*, not compensated.
        return True
    raise NonRestorableBranchError(
        f"branch {pruned.branch_id} pruned with non-rollbackable external effects: "
        f"{[e.tool + ':' + e.target for e in pruned.effects if not e.in_overlay]}; "
        "sibling resume against live world is unsound — reconcile and re-checkpoint"
    )


def orchestrate_rollback(pruned: SpeculativeBranch) -> str:
    try:
        if safe_to_resume_siblings(pruned):
            return "resume_siblings"
    except NonRestorableBranchError:
        return "halt_and_reconcile"
    return "halt_and_reconcile"
