# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-silently-orphaned-verified-tool-call-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-silently-orphaned-verified-tool-call-side-effects.warrant.json
# Markdown SHA-256:   a3ef953799e9fab269b88804922461826e951567fe0e43dc87cba78182a5b34e
# Code AST SHA-256:   f460f7eab1289c3099b5fa1ce359cb597f55ed33b881a9c281220133984752ec
# Verified Classes:   OrphanedEffectError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedEffectError(RuntimeError):
    """Raised when a committed tool effect has no live speculative-branch parent."""
    pass


def reconcile_at_promotion(
    committed_effects: list[dict],
    live_branches: dict[str, set[str]],
    promoted_branch_id: str,
) -> None:
    """
    Enforce the invariant: every committed effect is reachable from exactly one
    live branch's provenance closure, or explicitly tombstoned.

    committed_effects: each has {'effect_id', 'causal_key', 'tombstoned'}
    live_branches: branch_id -> set of causal_keys in its provenance closure
    """
    reachable: set[str] = set()
    for branch_id, closure in live_branches.items():
        reachable |= closure

    orphans = [
        e for e in committed_effects
        if not e.get("tombstoned") and e["causal_key"] not in reachable
    ]

    if orphans:
        # Promotion must abort: the promoted branch cannot be declared final
        # while effects exist that no live branch can account for.
        orphan_ids = [e["effect_id"] for e in orphans]
        ratio = len(committed_effects) / max(len(reachable), 1)
        raise OrphanedEffectError(
            f"Promotion of {promoted_branch_id} aborted: "
            f"{len(orphans)} orphaned effect(s) {orphan_ids} "
            f"have no live provenance parent "
            f"(effect-to-provenance ratio={ratio:.2f}). "
            f"Compensate orphans or tombstone before re-promoting."
        )

    # Invariant holds; promotion may proceed.
    return None
