# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-merge-a-reconciled-branch-when-speculative-rollback-has-already-mutated-shared-tool-side-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-merge-a-reconciled-branch-when-speculative-rollback-has-already-mutated-shared-tool-side-state.warrant.json
# Markdown SHA-256:   b543ee9946ff6757b4c22347adebf2f41bbb7470d4dcf632b4dff0a1c230a8c4
# Code AST SHA-256:   b96ea8dff4552add6e94ef2c6b61c5e9e7be5ac8b8ee728f27467cf1994c6602
# Verified Classes:   ReconciliationRefused, EffectClass, EffectRecord, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ReconciliationRefused(RuntimeError):
    """Raised when a speculative branch produced an unrecorded or non-compensable effect."""


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"          # safe to re-apply or overwrite
    COMPENSABLE = "compensable"        # has a durable inverse op
    IRREVERSIBLE = "irreversible"      # cannot be undone; must be journaled pre-issue


@dataclass(frozen=True)
class EffectRecord:
    effect_id: str
    branch_id: str
    kind: EffectClass
    inverse_op: str | None          # required for COMPENSABLE
    pre_state_hash: str | None      # required for COMPENSABLE
    journaled_pre_issue: bool       # written before the effect was issued


@dataclass
class Branch:
    branch_id: str
    effects: list[EffectRecord] = field(default_factory=list)
    elected: bool = False


def assert_mergeable(branches: Iterable[Branch]) -> None:
    """
    Enforce the grant-time invariant at merge time as a last line of defense.
    Sound only if every branch journaled pre-issue; this checks that it did.
    """
    for branch in branches:
        if branch.elected:
            continue  # winner's effects are the intended postcondition
        for effect in branch.effects:
            if effect.kind is EffectClass.IDEMPOTENT:
                continue  # superseded by winner's delta
            if effect.kind is EffectClass.COMPENSABLE:
                if not effect.journaled_pre_issue or effect.inverse_op is None:
                    raise ReconciliationRefused(
                        f"branch {branch.branch_id} effect {effect.effect_id} "
                        f"is compensable but lacks a pre-issue inverse journal entry; "
                        f"world state is unrecoverable — escalate, do not retry"
                    )
                continue
            if effect.kind is EffectClass.IRREVERSIBLE:
                raise ReconciliationRefused(
                    f"branch {branch.branch_id} produced irreversible effect "
                    f"{effect.effect_id} that survived rollback; trunk state is now "
                    f"conditioned on a non-elected branch — merge forbidden"
                )


def reconcile(trunk_checkpoint: str, branches: list[Branch]) -> str:
    assert_mergeable(branches)
    # Replay compensating inverses for losers in reverse order, then apply winner delta.
    for branch in branches:
        if branch.elected:
            continue
        for effect in reversed(branch.effects):
            if effect.kind is EffectClass.COMPENSABLE:
                _apply_inverse(effect)  # idempotent by contract
    winner = next(b for b in branches if b.elected)
    return f"{trunk_checkpoint}+{winner.branch_id}"


def _apply_inverse(effect: EffectRecord) -> None:
    # Implementation omitted; contract: idempotent, verifies pre_state_hash.
    ...
