# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-divergence-between-sibling-speculative-branches-before-rollback-commits-in-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-divergence-between-sibling-speculative-branches-before-rollback-commits-in-multi-agent-execution.warrant.json
# Markdown SHA-256:   6cdf115878dfad4687e43d93589bd124f34b62835673ff535d98eb00210c623e
# Code AST SHA-256:   594233f41a440d6721f41eb3cde77d09d58d03f08d658aa4ff5119029a067b56
# Verified Classes:   UnsafeRollbackError, Effect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class UnsafeRollbackError(RuntimeError):
    """Raised when rollback would discard a branch whose external effects are still live."""
    pass


@dataclass
class Effect:
    branch_id: str
    tool: str
    postcondition: str  # e.g. "ticket.status=resolved"
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    world_model: Dict[str, str] = field(default_factory=dict)  # branch's belief
    effects: List[Effect] = field(default_factory=list)


def reconcile(selected: Branch, losers: List[Branch]) -> None:
    """
    Commit `selected`, roll back `losers`.
    Refuses rollback if any loser's effect ledger is uncompensated and
    contradicts the selected branch's world model.
    """
    live_uncompensated: List[Effect] = [
        e for b in losers for e in b.effects if not e.compensated
    ]

    # Structural signal: effect-divergence between sibling ledgers and
    # the selected branch's world model.
    contradictions = []
    for e in live_uncompensated:
        key, _, val = e.postcondition.partition("=")
        believed = selected.world_model.get(key)
        if believed is not None and believed != val:
            contradictions.append((e, believed))

    if contradictions:
        detail = "; ".join(
            f"branch {e.branch_id} emitted {e.tool} -> {e.postcondition} "
            f"but selected branch believes {k}={v}"
            for e, (k, v) in [(e, (e.postcondition.partition('=')[0],
                                   e.postcondition.partition('=')[2]))
                               for e, _ in [(c[0], c[1]) for c in contradictions]]
        )
        # Simpler, explicit construction of the message:
        raise UnsafeRollbackError(
            "rollback refused: live uncompensated sibling effects contradict "
            f"selected branch world model ({len(contradictions)} contradiction(s)); "
            "execute compensating inverses or serialize effects before rollback"
        )

    # Safe: discard loser contexts.
    for b in losers:
        b.world_model.clear()
        b.effects.clear()
    selected.world_model["_committed"] = "true"
