# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-become-unrecoverable-in-multi-agent-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-become-unrecoverable-in-multi-agent-rollback-reconciliation.warrant.json
# Markdown SHA-256:   9f2ed9d0ade996b2318457b3f06feac81ee96b432bbe6dfeeb60c1203cb26898
# Code AST SHA-256:   6ccc0e262b3d0ac97ac0bb439f0689678330d8dcbb78289463ea137d70a7cd17
# Verified Classes:   OrphanedSpeculativeEffect
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedSpeculativeEffect(RuntimeError):
    """Raised when a committed external effect references a non-live speculative branch."""
    pass


def reconcile_branch_selection(
    selected_branch_id: str,
    losing_branch_ids: list[str],
    external_effects: list[dict],  # each: {"key", "value", "provenance_branch", "type"}
    live_branch_ids: set[str],
) -> list[dict]:
    """
    Reconcile after selecting one branch. Returns compensating actions to emit.
    Raises OrphanedSpeculativeEffect if a losing branch left a non-compensable
    external effect that no compensation hook can reverse.
    """
    compensations = []
    for eff in external_effects:
        prov = eff["provenance_branch"]
        if prov in live_branch_ids:
            continue  # effect belongs to a live branch; leave it
        # Effect references a branch that is not live -> orphan candidate
        if eff["type"] == "mutation" and eff.get("compensation") is not None:
            compensations.append({"op": "invert", "target": eff["key"],
                                  "compensation": eff["compensation"]})
        elif eff["type"] == "deferred":
            compensations.append({"op": "drop", "target": eff["key"]})
        else:
            # Irreversible invocation from a discarded branch, already observed
            # downstream. Rollback cannot invert this; only retraction can.
            raise OrphanedSpeculativeEffect(
                f"branch {prov} discarded but effect on key {eff['key']!r} "
                f"({eff['type']}) is externally observable and non-compensable; "
                f"abort-and-restart with retraction required, not rollback"
            )
    # Emit supersede markers so downstream agents can order writes
    for eff in external_effects:
        if eff["provenance_branch"] == selected_branch_id:
            compensations.append({"op": "commit_supersede", "target": eff["key"],
                                  "supersedes": losing_branch_ids})
    return compensations
