# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-agent-s-rollback-has-already-been-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-agent-s-rollback-has-already-been-observed.warrant.json
# Markdown SHA-256:   d424015f4d1b1dda1bfcd85c31256dc0f11af179735bd97b10c81f365eb25e0f
# Code AST SHA-256:   398e2cf8e061f946e2ea75f137e0d5c8e0e5f772185fdddca4f561c7dd220719
# Verified Classes:   ReconciliationRefused, EffectClass, JournalEntry, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReconciliationRefused(RuntimeError):
    """Raised when a speculative branch cannot be safely reconciled after rollback."""


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    PRIVATE_NS = "private_ns"
    SHARED_MUTABLE = "shared_mutable"


@dataclass
class JournalEntry:
    tool: str
    effect_class: EffectClass
    content_hash: str
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    generation: int
    journal: list[JournalEntry] = field(default_factory=list)
    lease_state: str = "UNHELD"          # as read from the LEASE SERVICE, not the branch context
    quiescent: bool = False              # confirmed by tool gateway, not assumed


def is_reconcilable(branch: Branch) -> tuple[bool, Optional[str]]:
    """Evaluate the reconciliation predicate. Returns (ok, reason_if_not)."""
    if not branch.quiescent:
        return False, f"branch {branch.branch_id} gen {branch.generation} not quiescent"
    for e in branch.journal:
        if e.effect_class is EffectClass.SHARED_MUTABLE and not e.compensated:
            return False, (
                f"branch {branch.branch_id} has uncompensated shared effect "
                f"{e.tool}#{e.content_hash[:8]}"
            )
    if branch.lease_state not in ("UNHELD", "RELEASED_BY_COMPENSATOR"):
        return False, f"branch {branch.branch_id} lease_state={branch.lease_state}"
    return True, None


def reconcile_losing_branch(branch: Branch, live_world_hashes: set[str]) -> list[str]:
    """Merge a losing branch's contribution against the LIVE world, not its transcript."""
    ok, reason = is_reconcilable(branch)
    if not ok:
        # Refuse: transcript-merge here would manufacture a phantom state.
        raise ReconciliationRefused(
            f"refusing to reconcile {branch.branch_id}: {reason}. "
            f"Re-run merge against live world with dedupe, or compensate first."
        )
    # Safe path: only effects not already present in the world are appended.
    to_append = [e.content_hash for e in branch.journal
                 if e.content_hash not in live_world_hashes]
    return to_append


def fence_stale_generation(branch: Branch, gateway_generation: int) -> None:
    """Tool gateway must reject calls from rolled-back generations."""
    if branch.generation < gateway_generation:
        raise ReconciliationRefused(
            f"stale generation: branch {branch.branch_id} gen {branch.generation} "
            f"< gateway gen {gateway_generation}; late tool call rejected"
        )
