# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-reconciliation-has-silently-diverged-from-its-rollback-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-reconciliation-has-silently-diverged-from-its-rollback-anchor.warrant.json
# Markdown SHA-256:   fb8f336a167f1ddc535957a1ca092eccf7887e8cc57f1160f2f830824f27accc
# Code AST SHA-256:   0201fcc44b846fa9600182557acac0116e78b371b9edf3a654772b66ddbd48bc
# Verified Classes:   StaleAnchorCommitError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleAnchorCommitError(RuntimeError):
    """Raised when a speculative branch is about to be committed onto an
    anchor generation newer than the one it was forked from, without a
    recorded rebase-and-revalidate event."""
    pass


def reconcile_branch(branch, live_anchor, rebase_log):
    # branch.provenance.anchor_generation: generation at fork time
    # live_anchor.generation: current generation of the shared prefix
    fork_gen = branch.provenance.anchor_generation
    live_gen = live_anchor.generation

    if fork_gen == live_gen:
        return branch.commit_onto(live_anchor)

    # Generation skew: a post-fork mutation exists somewhere in the prefix.
    # Diff cleanliness is NOT sufficient evidence; the mutation may live in a
    # disjoint namespace (memory records, tool registry) invisible to the diff.
    rebased = rebase_log.find(branch.id, from_gen=fork_gen, to_gen=live_gen)
    if rebased is None or not rebased.revalidated:
        raise StaleAnchorCommitError(
            f"branch {branch.id} forked at gen={fork_gen} but live anchor is "
            f"gen={live_gen}; no rebase-and-revalidate event bridges the skew. "
            f"Branch-local validation is evidence about the fork, not the commit "
            f"target. Refusing to commit a silently stale branch."
        )

    return branch.commit_onto(live_anchor, rebase=rebased)
