# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-sibling-agents-and-reconciles-branches-on-a-lossy-merge-token.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-sibling-agents-and-reconciles-branches-on-a-lossy-merge-token.warrant.json
# Markdown SHA-256:   e313f6c2bfd3187c3b1fee4bab3945ba7cf692c19b0a2163ddcb35262e3f86ac
# Code AST SHA-256:   1230ffe0f368c48ce5b8e81c0d24a547eae06e480976edcb8f137fea83b5ca98
# Verified Classes:   UnsoundMergeError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnsoundMergeError(RuntimeError):
    """Raised when a speculative merge token drops information needed to decide non-commutativity."""
    pass


def reconcile_speculative_branches(branches, shared_surface):
    """
    branches: list of dicts with keys
        - branch_id: str
        - touched_surface: set[str]        # declared shared-surface symbols touched
        - assumptions: list[dict] with keys 'text' and 'constrained_surface': set[str]
        - summary: str                     # lossy projection
        - raw_delta: dict                  # structured, per-surface
    shared_surface: set[str] of symbols considered shared
    """
    # Step 1: compute contested surfaces from RAW deltas, never from summaries.
    contested = set()
    for b in branches:
        contested |= (b["touched_surface"] & shared_surface)

    # Step 2: for every assumption whose constrained surface is contested,
    # the branch holding the assumption needs the *raw* delta of any branch
    # that touched that surface. Summaries are not decidable.
    merge_plan = {}
    for holder in branches:
        for assumption in holder["assumptions"]:
            constrained = assumption["constrained_surface"] & contested
            if not constrained:
                continue
            for other in branches:
                if other["branch_id"] == holder["branch_id"]:
                    continue
                if other["touched_surface"] & constrained:
                    # We need to verify: does other's raw delta preserve holder's assumption?
                    if constrained - other["raw_delta"].keys():
                        raise UnsoundMergeError(
                            f"Branch {holder['branch_id']} assumption "
                            f"{assumption['text']!r} constrains {constrained}, "
                            f"but branch {other['branch_id']} touched it without "
                            f"a structured delta. Merge token would be lossy; "
                            f"refusing to summarize. Fall back to serial or "
                            f"require raw_delta for {constrained}."
                        )
                    merge_plan.setdefault(holder["branch_id"], []).append(
                        (assumption["text"], other["branch_id"], other["raw_delta"])
                    )

    # Step 3: only now may summaries be used, and only for disjoint surfaces.
    disjoint = [b for b in branches if not (b["touched_surface"] & contested)]
    for b in disjoint:
        merge_plan.setdefault(b["branch_id"], []).append(("summary_only", b["summary"]))

    return merge_plan
