# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-after-rollback-and-why-silent-reconciliation-corrupts-the-task-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-after-rollback-and-why-silent-reconciliation-corrupts-the-task-tree.warrant.json
# Markdown SHA-256:   348d91552d3464485417f5f688a4a92eb6a31b67898f88d9455b33d914e3f5eb
# Code AST SHA-256:   9cf30122ca422f17729149df356e04dab9a302a919838472696e744b898753d5
# Verified Classes:   StaleBranchMergeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleBranchMergeError(RuntimeError):
    """Raised when a speculative branch delta is about to be merged onto a
    task-tree epoch other than the one it was computed against."""
    pass


def merge_speculative_branch(tree, branch_delta, verifier):
    """
    Merge a winning speculative branch into the task tree, enforcing the
    base-epoch equality invariant. Refuses to reconcile across epochs.
    """
    # Corollary 1: rollback bumps epoch even when content is reverted.
    current_epoch = tree.current_epoch
    delta_base_epoch = branch_delta.base_epoch

    if delta_base_epoch != current_epoch:
        # Do NOT attempt reconciliation. Discard and signal re-execution.
        raise StaleBranchMergeError(
            f"branch {branch_delta.branch_id} computed against epoch "
            f"{delta_base_epoch}, tree is at epoch {current_epoch}; "
            f"rollback invalidated base. Discard and re-execute."
        )

    # Corollary 2: every tool call in the branch must have stayed within
    # the branch's copy-on-write view.
    if not branch_delta.all_mutations_isolated:
        raise StaleBranchMergeError(
            f"branch {branch_delta.branch_id} leaked a shared-state mutation "
            f"outside its COW view; base_epoch stamp is untrustworthy."
        )

    # Corollary 3: verify against the merge target, not the branch snapshot.
    apply_preview = tree.preview_apply(branch_delta)
    verdict = verifier.replay_against(apply_preview, target_epoch=current_epoch)
    if not verdict.passed:
        raise StaleBranchMergeError(
            f"branch {branch_delta.branch_id} fails replay against merge "
            f"target epoch {current_epoch}: {verdict.reason}"
        )

    tree.apply(branch_delta)
    tree.advance_epoch()  # merge is itself a state mutation
    return tree
