# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-silently-discarding-a-losing-agent-s-verified-side-effects-during-conflict-aware-plan-reconcil.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-silently-discarding-a-losing-agent-s-verified-side-effects-during-conflict-aware-plan-reconcil.warrant.json
# Markdown SHA-256:   3be3f1855724a243969f0086615402c88726d1cd9e5d29ae0b4a4f614bd76761
# Code AST SHA-256:   dbc8a5f1c68e39c67ea445c3a80c855e9d538c94ac34783195f632773fb4052b
# Verified Classes:   OrphanedEffectError, Effect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class OrphanedEffectError(RuntimeError):
    """Raised when a committed branch fails to account for a sibling's verified effect."""


@dataclass(frozen=True)
class Effect:
    tool: str
    canonical_args: str
    receipt_id: str

    @property
    def idempotency_token(self) -> str:
        # Content-derived, NOT branch-scoped. This is the load-bearing detail.
        return f"{self.tool}::{self.canonical_args}"


@dataclass
class Branch:
    name: str
    plan_text: str
    effects: list[Effect] = field(default_factory=list)
    compensated: set[str] = field(default_factory=set)  # idempotency tokens


def reconcile(
    branches: Iterable[Branch],
    committed: Branch,
) -> list[Effect]:
    """
    Enforce: committed plan must account for every non-compensated effect
    produced by any sibling branch. Returns the set of effects that the
    committed branch must adopt (or that must be escalated).
    """
    committed_tokens = {e.idempotency_token for e in committed.effects}
    orphaned: list[Effect] = []

    for b in branches:
        if b.name == committed.name:
            continue
        for eff in b.effects:
            tok = eff.idempotency_token
            if tok in committed_tokens:
                continue  # deduped: sibling and committed agree on this effect
            if tok in b.compensated:
                continue  # explicitly rolled back by the branch itself
            orphaned.append(eff)

    if orphaned:
        raise OrphanedEffectError(
            f"committed branch {committed.name!r} does not account for "
            f"{len(orphaned)} sibling effect(s): "
            f"{[e.receipt_id for e in orphaned]}. "
            f"Compensate or escalate before commit."
        )

    return orphaned


def commit_plan(branches: list[Branch], winner: Branch) -> Branch:
    # The gate: reconcile must pass before the plan is persisted.
    reconcile(branches, winner)
    return winner
