# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-the-speculative-sibling-divergence-boundary-when-reconciling-parallel-agent-branches-whose-rollback-points-overlap-on-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-the-speculative-sibling-divergence-boundary-when-reconciling-parallel-agent-branches-whose-rollback-points-overlap-on-a.warrant.json
# Markdown SHA-256:   ca2f7c6a0b40b6186560e56e3d9651ef121fa7eeb30cd01e837f4585eda722ab
# Code AST SHA-256:   10e6a14230a2eced3fbb7dabf1a51e19f0f3947fd52432a901804a74c8107a08
# Verified Classes:   SpeculativeSiblingDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeSiblingDivergence(RuntimeError):
    """Raised when a losing branch advanced a shared causal structure past
    its rollback barrier, invalidating content-based reconciliation."""
    pass


def reconcile_branches(branches, barrier_seq, shared_seq, replay_fn):
    # branches: list of dicts with 'id', 'effects', 'is_winner'
    # shared_seq: current shared log offset after all branches ran
    # replay_fn: callable(branch) -> terminal_state

    if shared_seq > barrier_seq:
        # A sibling advanced the shared counter past the barrier.
        # Content reconciliation is now unsound; require replay equivalence.
        winner = next(b for b in branches if b["is_winner"])
        try:
            replayed = replay_fn(winner)
        except Exception as exc:
            raise SpeculativeSiblingDivergence(
                f"Replay of winner {winner['id']} failed after shared_seq "
                f"{shared_seq} exceeded barrier {barrier_seq}: {exc}"
            ) from exc

        if replayed != winner.get("terminal_state"):
            raise SpeculativeSiblingDivergence(
                f"Replay divergence for winner {winner['id']}: surviving "
                f"effects unreachable from barrier {barrier_seq} "
                f"(shared_seq={shared_seq}). Reconciliation verdict untrusted."
            )
        return replayed

    # Barrier was a true causal fence; content reconciliation is sound.
    return next(b for b in branches if b["is_winner"])["terminal_state"]
