# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-in-multi-agent-verify-and-rollback-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-in-multi-agent-verify-and-rollback-execution.warrant.json
# Markdown SHA-256:   8332a2921a32ef44b8e97d316f8fa7de1ff3c166f6e0a2433e3410bb0d0d7cff
# Code AST SHA-256:   a7f04eb7219264c177ff98b07ae3caf7b264bff58af11259accac930065cc2ac
# Verified Classes:   SpeculativeDivergenceError, Effect, BranchReport, Reconciler
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeDivergenceError(RuntimeError):
    """Raised when a speculative branch's effect-log contradicts the commit predicate."""


@dataclass
class Effect:
    branch_id: str
    tool: str
    args_hash: str
    pre_state_hash: str
    post_state_hash: str
    invertible: bool
    undone: bool = False

    @property
    def mutated(self) -> bool:
        return self.pre_state_hash != self.post_state_hash


@dataclass
class BranchReport:
    branch_id: str
    self_reported_effect: str  # "none" | "applied" | "unreversible"


@dataclass
class Reconciler:
    baseline_hash: str
    effect_log: list[Effect] = field(default_factory=list)
    reports: dict[str, BranchReport] = field(default_factory=dict)

    def commit(self, winner_id: str) -> str:
        winner_effects = [e for e in self.effect_log if e.branch_id == winner_id and e.mutated]
        if not winner_effects:
            raise SpeculativeDivergenceError(
                f"winner {winner_id} has no logged mutation; report-only commit is inadmissible"
            )

        first = min(winner_effects, key=lambda e: e.pre_state_hash)
        if first.pre_state_hash != self.baseline_hash:
            raise SpeculativeDivergenceError(
                f"winner {winner_id} pre_state {first.pre_state_hash[:8]} != baseline "
                f"{self.baseline_hash[:8]}: a loser mutated the winner's input (race)"
            )

        losers = {e.branch_id for e in self.effect_log} - {winner_id}
        for loser in losers:
            for e in self.effect_log:
                if e.branch_id != loser or not e.mutated:
                    continue
                if not e.invertible and not e.undone:
                    raise SpeculativeDivergenceError(
                        f"loser {loser} left non-invertible residue via {e.tool} "
                        f"({e.pre_state_hash[:8]}->{e.post_state_hash[:8]}); abort or quarantine"
                    )
                if e.invertible and not e.undone:
                    raise SpeculativeDivergenceError(
                        f"loser {loser} residue not yet undone on {e.tool}; re-fork required"
                    )

        return hashlib.sha256(
            "".join(sorted(e.post_state_hash for e in winner_effects)).encode()
        ).hexdigest()


def reconcile_and_commit(rec: Reconciler, winner_id: str) -> str:
    try:
        return rec.commit(winner_id)
    except SpeculativeDivergenceError:
        # caller escalates to re-fork or abort; never proceeds to commit
        raise
