# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-merges-when-deterministic-replay-diverges-at-non-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-merges-when-deterministic-replay-diverges-at-non-tool-call-boundaries.warrant.json
# Markdown SHA-256:   8b6adbb5ea47baac2be62c5b61dbbfae39981b1e1b60845b7422abae52b5e052
# Code AST SHA-256:   68d98e353b56db83b946d12b950300c0f325af2350d811bd06c963a6754027a9
# Verified Classes:   BoundaryDivergenceError, Boundary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BoundaryDivergenceError(RuntimeError):
    """Raised when a speculative branch replays deterministically but diverges
    from the merge target at a non-tool-call boundary that feeds the artifact."""


@dataclass
class Boundary:
    index: int
    prefix_tokens: str
    feeds_artifact: bool


def boundary_hash(prefix_tokens: str) -> str:
    return hashlib.sha256(prefix_tokens.encode("utf-8")).hexdigest()


def validate_merge(
    branch_boundaries: list[Boundary],
    replay_boundaries: list[Boundary],
    artifact_irrelevant: set[int],
) -> None:
    if len(branch_boundaries) != len(replay_boundaries):
        raise BoundaryDivergenceError(
            "boundary count mismatch: branch=%d replay=%d"
            % (len(branch_boundaries), len(replay_boundaries))
        )

    for b, r in zip(branch_boundaries, replay_boundaries):
        if b.index != r.index:
            raise BoundaryDivergenceError(
                "boundary index mismatch at %d vs %d" % (b.index, r.index)
            )
        if b.index in artifact_irrelevant:
            continue
        if not b.feeds_artifact:
            continue
        if boundary_hash(b.prefix_tokens) != boundary_hash(r.prefix_tokens):
            raise BoundaryDivergenceError(
                "non-tool-call divergence at boundary %d: branch and replay "
                "produced different prefixes that both feed the merged artifact"
                % b.index
            )


def merge_speculative_branch(
    branch_boundaries: list[Boundary],
    replay_boundaries: list[Boundary],
    artifact_irrelevant: set[int] | None = None,
) -> str:
    validate_merge(branch_boundaries, replay_boundaries, artifact_irrelevant or set())
    return "merged"
