# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-silently-merging-divergent-tool-side-effects-across-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-silently-merging-divergent-tool-side-effects-across-agents.warrant.json
# Markdown SHA-256:   e2c10fdf82aab8dbdad5d0d250572d21cdc180439e115a0e0971a3c1ea4bfa1f
# Code AST SHA-256:   3ec4f89dfc3251f4950a96e051917bb1ec767b14ce9fc1215de80bc0cfaf4ba4
# Verified Classes:   GhostEffectContamination, EffectRecord, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class GhostEffectContamination(RuntimeError):
    """Raised when a speculative branch winner read a resource that a
    rolled-back sibling mutated after the winner's read baseline."""
    pass


@dataclass
class EffectRecord:
    branch_id: str
    resource_id: str
    seq: int          # global monotonic sequence at time of effect
    is_write: bool


@dataclass
class Branch:
    branch_id: str
    effects: List[EffectRecord] = field(default_factory=list)
    read_resources: Set[str] = field(default_factory=set)
    rolled_back: bool = False


def reconcile_winner(winner: Branch, all_branches: Dict[str, Branch]) -> None:
    """
    Commit `winner` only if no rolled-back sibling wrote to any resource
    the winner read at a sequence at-or-after the winner's first read of it.
    """
    # Baseline: earliest seq at which the winner observed each resource.
    winner_baseline: Dict[str, int] = {}
    for eff in winner.effects:
        if not eff.is_write:
            winner_baseline.setdefault(eff.resource_id, eff.seq)

    tainted: List[str] = []
    for other in all_branches.values():
        if other.branch_id == winner.branch_id:
            continue
        if not other.rolled_back:
            continue
        for eff in other.effects:
            if not eff.is_write:
                continue
            base = winner_baseline.get(eff.resource_id)
            if base is not None and eff.seq >= base:
                tainted.append(
                    f"sibling {other.branch_id} wrote {eff.resource_id} "
                    f"at seq {eff.seq} >= winner baseline {base}"
                )

    if tainted:
        raise GhostEffectContamination(
            "winner reads are contaminated by rolled-back sibling effects; "
            "re-derive winner in isolation: " + "; ".join(tainted)
        )

    # Safe: no ghost effects on the winner's read set. Commit.
    winner.rolled_back = False


# --- Illustrative trace of the observed incident ---
planner_a = Branch("A")
planner_a.effects.append(EffectRecord("A", "mcp.cursor", seq=10, is_write=True))
planner_a.rolled_back = True

planner_b = Branch("B")
planner_b.effects.append(EffectRecord("B", "mcp.cursor", seq=20, is_write=False))
planner_b.read_resources.add("mcp.cursor")

planner_c = Branch("C")
planner_c.rolled_back = True

swarm = {b.branch_id: b for b in (planner_a, planner_b, planner_c)}

try:
    reconcile_winner(planner_b, swarm)
except GhostEffectContamination as exc:
    # Correct behavior: refuse to commit B, surface the contamination.
    print(f"RECONCILIATION BLOCKED: {exc}")
