# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-forked-the-shared-world-state-during-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-forked-the-shared-world-state-during-rollback-reconciliation.warrant.json
# Markdown SHA-256:   6efc308d1090e9caf467ba6fd3bd082b5663a91c8a7027687b5dc5723b309667
# Code AST SHA-256:   21ce1bd78f886d7e529cea8311b29e40d1b4d4b23e8a79fc2fc15e737ac432e3
# Verified Classes:   BranchDivergenceError, Branch, WorldState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class BranchDivergenceError(RuntimeError):
    """Raised when a retained branch commits against a world-state that a
    discarded branch's incomplete compensation has contaminated."""


@dataclass
class Branch:
    name: str
    spawned_env_hash: str
    effects: list = field(default_factory=list)
    compensation_confirmed: bool = False
    observations: list = field(default_factory=list)  # facts read from peers


@dataclass
class WorldState:
    env_hash: str
    pending_compensations: list = field(default_factory=list)


def reconcile(world: WorldState, retained: Branch, discarded: list[Branch]) -> str:
    # 1. Effect closure: every discarded branch's compensation must be terminal.
    for b in discarded:
        if not b.compensation_confirmed:
            raise BranchDivergenceError(
                f"discarded branch {b.name!r} has unconfirmed compensation; "
                f"retained branch {retained.name!r} must not commit yet"
            )

    # 2. Observation closure: no retained branch may hold a fact derived from
    #    a discarded branch that was not re-derived post-rollback.
    discarded_names = {b.name for b in discarded}
    tainted = [o for o in retained.observations if o.get("source") in discarded_names]
    if tainted:
        raise BranchDivergenceError(
            f"retained branch {retained.name!r} holds {len(tainted)} observation(s) "
            f"from discarded branches {sorted(discarded_names)}; re-derive before commit"
        )

    # 3. Identity stability: the commit key must fold in the effect log, not
    #    just the final artifact, so a half-compensated twin cannot collide.
    effect_log = "|".join(f"{b.name}:{b.effects}" for b in discarded + [retained])
    commit_key = hashlib.sha256(effect_log.encode()).hexdigest()

    if world.env_hash != retained.spawned_env_hash:
        raise BranchDivergenceError(
            f"env drift on {retained.name!r}: spawned={retained.spawned_env_hash} "
            f"now={world.env_hash}; unexplained delta implies leaked compensation"
        )

    return commit_key
