# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-outlived-its-rollback-safety-window-during-multi-agent-plan-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-outlived-its-rollback-safety-window-during-multi-agent-plan-merge.warrant.json
# Markdown SHA-256:   f38260e0d2b3f95ffdc2d68fe8bb905dd5cfccbc836a4ffb636fe53161e2dc62
# Code AST SHA-256:   690b08456de0c2490e2f5b4098eb9ddfa64102671cc03d50979d6a42f0dea6fb
# Verified Classes:   RollbackWindowClosedError, BranchState, EffectClass, ToolContract, Residue, SpeculativeBranch, Orchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import enum
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class RollbackWindowClosedError(RuntimeError):
    """Raised when a speculative branch attempts a commitment-class effect
    while still discardable, or when a merge is attempted with live residue."""
    pass


class BranchState(enum.Enum):
    SPECULATIVE = "speculative"
    COMMITTED = "committed"
    ABANDONED = "abandoned"
    DISCARDED = "discarded"


class EffectClass(enum.Enum):
    READ = "read"
    REVERSIBLE_WRITE = "reversible_write"
    COMMITMENT = "commitment"  # create-only, TTL-bounded, or externally held


@dataclass
class ToolContract:
    name: str
    effect_class: EffectClass
    compensating_op: Optional[str] = None
    compensator_principal: Optional[str] = None
    # Reversibility must be asserted by endpoint, not inferred from idempotency.
    reversibility_asserted_by_endpoint: bool = False


@dataclass
class Residue:
    branch_id: str
    tool: str
    external_ref: str
    compensable: bool
    created_at: float = field(default_factory=time.time)


@dataclass
class SpeculativeBranch:
    branch_id: str
    speculation_id: str
    state: BranchState = BranchState.SPECULATIVE
    residue: List[Residue] = field(default_factory=list)

    def dispatch(self, contract: ToolContract, external_ref: str) -> None:
        if contract.effect_class is EffectClass.COMMITMENT:
            if self.state is BranchState.SPECULATIVE:
                raise RollbackWindowClosedError(
                    f"branch {self.branch_id} is SPECULATIVE but tool "
                    f"{contract.name} is COMMITMENT-class; promote before dispatch "
                    f"or route through reversible tools"
                )
            if not contract.reversibility_asserted_by_endpoint:
                raise RollbackWindowClosedError(
                    f"tool {contract.name} does not assert reversibility from the "
                    f"endpoint; residue would be orphaned on discard"
                )
            self.residue.append(
                Residue(
                    branch_id=self.branch_id,
                    tool=contract.name,
                    external_ref=external_ref,
                    compensable=contract.compensating_op is not None,
                )
            )


@dataclass
class Orchestrator:
    branches: Dict[str, SpeculativeBranch] = field(default_factory=dict)
    # Reaper holds standing authority to compensate residue (C3).
    reaper_principal: str = "orchestrator-reaper"

    def merge(self, winner_id: str, losers: List[str]) -> None:
        winner = self.branches[winner_id]
        # C4: reconciliation runs unconditionally, not gated on confidence.
        for lid in losers:
            loser = self.branches[lid]
            live = [r for r in loser.residue if r.compensable]
            if live:
                raise RollbackWindowClosedError(
                    f"merge blocked: losing branch {lid} holds {len(live)} "
                    f"un-compensated commitment residue; winner {winner_id} "
                    f"plan may be invalidated by sibling residue"
                )
            # Compensate first, discard second (correct order).
            loser.state = BranchState.DISCARDED
        winner.state = BranchState.COMMITTED

    def abandon(self, branch_id: str) -> None:
        branch = self.branches[branch_id]
        for r in branch.residue:
            if not r.compensable:
                raise RollbackWindowClosedError(
                    f"branch {branch_id} residue {r.external_ref} on {r.tool} "
                    f"is not compensable and cannot be reaped"
                )
            # reaper_principal invokes r.tool's compensating_op here.
        branch.residue.clear()
        branch.state = BranchState.ABANDONED
