# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-forks-from-reconciling-against-a-mutated-lineage-root-after-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-forks-from-reconciling-against-a-mutated-lineage-root-after-rollback.warrant.json
# Markdown SHA-256:   3c74b383b60a9fe06a650b0f04ce845c431c3bc279ca945a6124db86d835480d
# Code AST SHA-256:   5479ea6d67fc8d11f77dd02f6c7da4c25662f45a1d14c63aaabff5c612a8533e
# Verified Classes:   PhantomDivergenceError, Checkpoint, Branch, LineageStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PhantomDivergenceError(RuntimeError):
    """Raised when a branch patch's base is not an ancestor of the merge target."""
    pass


@dataclass
class Checkpoint:
    cid: str
    parent: Optional[str]
    state_hash: str


@dataclass
class Branch:
    branch_id: str
    base_cid: str
    base_hash: str
    patch: dict = field(default_factory=dict)


class LineageStore:
    def __init__(self):
        self.nodes: dict[str, Checkpoint] = {}

    def add(self, cp: Checkpoint):
        self.nodes[cp.cid] = cp

    def is_ancestor(self, candidate: str, target: str) -> bool:
        cur = target
        while cur is not None:
            if cur == candidate:
                return True
            cur = self.nodes[cur].parent
        return False


def reconcile(store: LineageStore, merge_target: str, branches: list[Branch]) -> dict:
    merged: dict = {}
    for b in branches:
        node = store.nodes.get(b.base_cid)
        if node is None or node.state_hash != b.base_hash:
            raise PhantomDivergenceError(
                f"branch {b.branch_id} base {b.base_cid} hash mismatch: "
                f"expected {b.base_hash}, found {node.state_hash if node else 'missing'}"
            )
        if not store.is_ancestor(b.base_cid, merge_target):
            raise PhantomDivergenceError(
                f"branch {b.branch_id} forked from {b.base_cid} which is not an "
                f"ancestor of merge target {merge_target}; base was mutated by rollback"
            )
        for k, v in b.patch.items():
            if k in merged and merged[k] != v:
                raise PhantomDivergenceError(
                    f"true conflict on key {k} between branches at merge target {merge_target}"
                )
            merged[k] = v
    return merged


def rollback_lineage(store: LineageStore, branches: list[Branch], failed_base: str) -> list[Branch]:
    survivors = []
    for b in branches:
        if store.is_ancestor(failed_base, b.base_cid) or b.base_cid == failed_base:
            continue
        survivors.append(b)
    return survivors
