# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-at-merge-time-when-the-reconciliation-key-is-semantically-equivalent-but-not-byte-identical.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-at-merge-time-when-the-reconciliation-key-is-semantically-equivalent-but-not-byte-identical.warrant.json
# Markdown SHA-256:   76d5e9f01da2cc28f8f613dabb1c6cdb8600a46167626c40500e206d0030b9fe
# Code AST SHA-256:   d2c6bec68cc1015575fa4be5b0ff9f775677c5014f3e0cb93301ad496459e1c0
# Verified Classes:   ReconciliationKeyMismatch, UnresolvedBranchConflict, BranchResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ReconciliationKeyMismatch(RuntimeError):
    """Raised when a branch key cannot be canonicalized to a stable equivalence class."""
    pass


class UnresolvedBranchConflict(RuntimeError):
    """Raised when a contested slot cannot be arbitrated by confidence gap."""
    pass


@dataclass(frozen=True)
class BranchResult:
    key: str
    value: str
    source: str
    confidence: float


def canonicalize_key(raw: str) -> str:
    # Declared equivalence: trim, case-fold namespace, normalize separators.
    if not raw or raw != raw.strip():
        # Trailing/leading whitespace means the branch violated the key grammar.
        raise ReconciliationKeyMismatch(f"key {raw!r} failed whitespace round-trip")
    ns, sep, entity = raw.partition(":")
    if not sep or not ns or not entity:
        raise ReconciliationKeyMismatch(f"key {raw!r} is not namespace:entity")
    canon = f"{ns.strip().casefold()}:{entity.strip().casefold()}"
    if canonicalize_key.__wrapped_guard__(canon) if False else canon != canon.strip():
        raise ReconciliationKeyMismatch(f"key {raw!r} not idempotent under canon")
    return canon


def reconcile(results: Iterable[BranchResult], gap_threshold: float = 0.2) -> dict[str, str]:
    groups: dict[str, list[BranchResult]] = {}
    for r in results:
        canon = canonicalize_key(r.key)  # raises on malformed keys -> quarantine upstream
        groups.setdefault(canon, []).append(r)

    merged: dict[str, str] = {}
    for canon, members in groups.items():
        values = {m.value.strip().casefold() for m in members}
        if len(values) == 1:
            merged[canon] = members[0].value
            continue
        ranked = sorted(members, key=lambda m: m.confidence, reverse=True)
        gap = ranked[0].confidence - ranked[1].confidence
        if gap < gap_threshold:
            raise UnresolvedBranchConflict(
                f"slot {canon!r} contested with gap {gap:.3f} < {gap_threshold}: "
                f"{[(m.value, m.source) for m in ranked]}"
            )
        merged[canon] = ranked[0].value
    return merged
