# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-merge-has-silently-invalidated-a-branch-s-cost-basis-the-divergence-witness-gap-in-parallel-agent-orche.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-merge-has-silently-invalidated-a-branch-s-cost-basis-the-divergence-witness-gap-in-parallel-agent-orche.warrant.json
# Markdown SHA-256:   f7f224ac772074e06b7cddecff8e249d8e43804e0c11ab9b25ad75cba21a8cd3
# Code AST SHA-256:   38f09a1286d9a9d09aa3f822ea789619d58acc68d5c1f14f92ff0f2d30373edd
# Verified Classes:   DivergenceWitnessGap, BranchRecord, MergeArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DivergenceWitnessGap(RuntimeError):
    """Raised when a merge would proceed over an unreconciled world-state divergence."""
    pass


@dataclass
class BranchRecord:
    branch_id: str
    pruned: bool
    read_hashes: dict = field(default_factory=dict)   # resource -> hash at last read
    stale_read_flags: dict = field(default_factory=dict)  # resource -> bool


@dataclass
class MergeArtifact:
    touched_resources: set
    reconciliation: dict = field(default_factory=dict)  # resource -> reconciliation step id


def _hash(content: bytes) -> str:
    return hashlib.sha256(content).hexdigest()


def verify_merge_soundness(
    branches: list[BranchRecord],
    artifact: MergeArtifact,
    reconciliation_floor_tokens: int,
    remaining_budget_tokens: int,
) -> None:
    # Invariant 1: budget must reserve a reconciliation floor.
    if remaining_budget_tokens < reconciliation_floor_tokens:
        raise DivergenceWitnessGap(
            f"Speculation budget {remaining_budget_tokens} below reconciliation floor "
            f"{reconciliation_floor_tokens}; merge cannot guarantee a reconciling re-read."
        )

    # Collect observations across surviving AND pruned branches.
    for resource in artifact.touched_resources:
        observed = {}
        witnesses = []
        for b in branches:
            if resource in b.read_hashes:
                observed.setdefault(b.read_hashes[resource], []).append(b.branch_id)
            if b.pruned and b.stale_read_flags.get(resource):
                witnesses.append(b.branch_id)

        # Invariant 2: uniform observation OR explicit reconciliation.
        if len(observed) > 1:
            if resource not in artifact.reconciliation:
                raise DivergenceWitnessGap(
                    f"Resource {resource!r} observed with {len(observed)} distinct hashes "
                    f"across branches {list(observed.values())} and no reconciliation artifact."
                )

        # Invariant 3: a pruned branch that witnessed a mismatch on a shared
        # resource is a mandatory merge input, not a discardable log line.
        if witnesses and resource not in artifact.reconciliation:
            raise DivergenceWitnessGap(
                f"Pruned branch(es) {witnesses} observed a stale read on shared "
                f"resource {resource!r}; merge verifier must consume this witness."
            )
