Skip to content
zit Artifact [0d52c7b605]
Login

Artifact [0d52c7b605]

Artifact 0d52c7b605710b148de3ef6425e348caaff2f4f7a0e64e9818d6a113a37b98e2:


//! `zit merge`: three-way merge of another check-in into the working tree,
//! and the store-only mergeability probe.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const merge3 = @import("zit").merge3;
const cmd_sync = @import("sync.zig");
const cmd_precedent = @import("precedent.zig");
const logstore = @import("zit").logstore;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const Repository = @import("zit").Repository;
const repostate = zit.repostate;
const artifact = zit.artifact;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const checkin_display = @import("checkin_display.zig");
const stateOom = diagnostics.stateOom;
const checkoutFail = diagnostics.checkoutFail;
const repoOpenFail = diagnostics.repoOpenFail;
const openRepo = diagnostics.openRepo;
const lessByHash = checkin_display.lessByHash;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const merge_help = help_pages.merge_help;

const cmd_commit = @import("commit.zig");
const commitMapCapture = cmd_commit.commitMapCapture;

// ==========================================================================
// `zit merge NAME` — compute a line-based three-way merge of NAME (the "other"
// side) into the working tree and record it as a pending merge parent. Thin
// orchestration: resolve + refusal gate + pure `merge3` classification, then
// `update.applyMerge` materializes and records the parent. It does NOT mint a
// check-in — `zit commit` does that from the recorded state (contracts/merge.md
// B-merge-1..29). Conflicts are written in-tree with markers, listed on stderr,
// exit 1 — but the merge parent is still recorded (`zit undo` is the escape).
// ==========================================================================

pub fn runMerge(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    return runMergeIn(gpa, io, arena, verb_args, streams, amb, null);
}

/// `merge`, against a checkout this caller NAMES rather than the one the
/// process happens to be standing in.
///
/// `checkout_root` null is the verb: discover from the cwd. Non-null is the
/// in-process caller (`landing accept`) driving an ephemeral checkout it
/// created itself -- the merge engine below already takes its worktree as a
/// parameter, so the only thing that was ever implicit here is WHICH tree, and
/// this makes that explicit instead of mutating the process's cwd to say it.
///
/// The dir is BORROWED: the caller opened it and closes it.
pub const NamedCheckout = struct { dir: std.Io.Dir, abs: []const u8 };

/// Set once a merge has deepened and re-entered itself, so a base the origin
/// also cannot find does not loop.
var merge_deepen_spent: bool = false;

/// Under a structural horizon a name that does not resolve is usually a
/// branch the held set does not reach, not a typo; say so and name the way
/// out, since "not found" alone sends the user looking for a spelling error.
/// A full hash below the horizon does not resolve either, so the remedy is
/// a clone that holds the branch.
fn mergeHorizonHint(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir, streams: cli.Streams) void {
    var cone = zit.repocache.readStoreCone(gpa, io, root_dir) orelse return;
    defer cone.deinit(gpa);
    const h = cone.horizon orelse return;
    if (h.depth != .structural) return;
    streams.err.print(
        "zit merge: this store holds history from its horizon {s} forward (rule '{s}'); a branch below it has no name or hash here\n" ++
            "zit merge: re-clone with --horizon-rule=leaves to hold every open leaf, or with an earlier --horizon\n",
        .{ cli.shortHash(h.hash), @tagName(h.rule) },
    ) catch {};
}

/// Horizon draft section 5.5 -- the merge-base remedy under a structural
/// horizon: ask the saved remote for the pivot of `other` against
/// `secondaries` (the check-out, then each pending plain merge: the set
/// `pendingMergeRids` gives Fossil's pivot), move C to it (depth and rule
/// unchanged), drop the stale seed and pull. A dense or content-horizon store
/// is never deepened here: its "no common ancestor" is the truth.
const MergeDeepen = enum {
    /// The store deepened: the merge should run again.
    deepened,
    /// Nothing changed; the store's own answer stands (any reason printed).
    held,
    /// The merge cannot be asked of the origin; the refusal is printed.
    refused,
};

fn mergeDeepenToBase(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, root_dir: std.Io.Dir, streams: cli.Streams, amb: cli.Ambient, other: []const u8, secondaries: []const []const u8) MergeDeepen {
    var stored = zit.repocache.readStoreCone(gpa, io, root_dir) orelse return .held;
    defer stored.deinit(gpa);
    const h = stored.horizon orelse return .held;
    if (h.depth != .structural) return .held;
    // Horizon draft section 6.2.4 -- a query card carries the check-out and
    // one pending merge. Asking without the others would name a base Fossil's
    // merge would not choose, and the store's own may lie below C.
    if (secondaries.len > zit.sync.max_mergebase_secondaries) {
        streams.err.print(
            "zit merge: the merge base may lie below the store's horizon, and a merge-base query carries the check-out and at most {d} pending merge, not the {d} pending here; commit or undo the pending merges first\n",
            .{ zit.sync.max_mergebase_secondaries - 1, secondaries.len - 1 },
        ) catch {};
        return .refused;
    }
    var base_buf: [64]u8 = undefined;
    const base = cmd_sync.queryMergeBase(gpa, io, root_dir, streams, amb, other, secondaries, &base_buf) orelse {
        streams.err.writeAll("zit merge: the merge base may lie below the store's horizon, and the saved remote did not answer a merge-base query; re-clone with an earlier --horizon\n") catch {};
        return .held;
    };
    if (base.len == 0) return .held; // the origin agrees: no common ancestor
    // The base of the two sides need not be C's ancestor; the deepen must
    // reach both it and C.
    var point_buf: [64]u8 = undefined;
    const point = cmd_sync.deepenPoint(gpa, io, root_dir, streams, amb, "merge", h.hash, base, &point_buf) orelse return .held;
    var deepened = zit.cone.Cone.initFrom(gpa, &stored, .{ .hash = point, .rule = h.rule, .depth = h.depth }) catch return .held;
    defer deepened.deinit(gpa);
    streams.err.print("zit merge: the merge base {s} lies below the store's horizon; deepening to {s} from the saved remote\n", .{ cli.shortHash(base), cli.shortHash(point) }) catch {};
    return if (cmd_sync.deepenHorizon(gpa, io, arena, root_dir, streams, "merge", &deepened) == .ok) .deepened else .held;
}

/// Horizon draft section 4.4 -- a merge reads every side's content, and under
/// a horizon a side below C has its manifest but not its blobs. When some
/// side's content is not held, deepen to the sides' common ancestor, whose K
/// holds all of them, and run the merge again over real artifacts; the merge
/// never runs against content it does not hold.
const MergeContent = union(enum) {
    /// Every side's content is here (or the store has no horizon): merge.
    held,
    /// The store deepened: the view is stale, so the merge runs again.
    deepened,
    /// The content cannot be had; the diagnostic is printed.
    refused: cli.Exit,
};

fn mergeDeepenForContent(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    repo: *Repository,
    sides: []const ?repostate.Rid,
) MergeContent {
    if (merge_deepen_spent) return .held;
    var stored = zit.repocache.readStoreCone(gpa, io, root_dir) orelse return .held;
    defer stored.deinit(gpa);
    const h = stored.horizon orelse return .held;
    const missing = blk: for (sides) |side| {
        const rid = side orelse continue;
        var files = (repo.files(gpa, rid) catch return .held) orelse return .held;
        defer files.deinit(gpa);
        var it = files.iterator();
        while (it.next()) |f| {
            const name = f.hash orelse continue;
            if (!(repo.blobPresent(gpa, name) catch return .held)) break :blk true;
        }
    } else false;
    if (!missing) return .held;
    var root: ?repostate.Rid = null;
    for (sides) |side| {
        const rid = side orelse continue;
        root = if (root) |r| (repo.mergeBaseOf(gpa, r, rid) catch return .{ .refused = mergeOom(streams) }) else rid;
        if (root == null) break;
    }
    // A deepen moves C to an ancestor of C; a common ancestor that is not one
    // would trade held history for the merge's.
    const c_rid = repo.lookup(h.hash);
    const target = root orelse return .{ .refused = mergeBelowHorizon(streams, h.hash) };
    if (c_rid == null or !(repo.isAncestorOf(gpa, target, c_rid.?) catch return .{ .refused = mergeOom(streams) })) return .{ .refused = mergeBelowHorizon(streams, h.hash) };
    var deepened = zit.cone.Cone.initFrom(gpa, &stored, .{ .hash = repo.hashOf(target), .rule = h.rule, .depth = h.depth }) catch return .{ .refused = mergeOom(streams) };
    defer deepened.deinit(gpa);
    streams.err.print("zit merge: the merge reads content below the store's horizon; deepening to {s} from the saved remote\n", .{cli.shortHash(repo.hashOf(target))}) catch {};
    const deepen_exit = cmd_sync.deepenHorizon(gpa, io, arena, root_dir, streams, "merge", &deepened);
    if (deepen_exit != .ok) return .{ .refused = deepen_exit };
    merge_deepen_spent = true;
    return .deepened;
}

fn mergeBelowHorizon(streams: cli.Streams, horizon: []const u8) cli.Exit {
    streams.err.print("zit merge: the merge reads content below the store's horizon {s}, and no deepen reaches it; re-clone with an earlier --horizon\n", .{cli.shortHash(horizon)}) catch {};
    return .failure;
}

pub fn runMergeIn(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
) cli.Exit {
    // The three sides' trees are read before anything is written, so a run
    // that met withheld tree nodes left the checkout as it was.
    var tree: cmd_sync.ElidedTree = .{};
    const rc = mergeOnce(gpa, io, arena, verb_args, streams, amb, checkout_root, &tree);
    if (!tree.fetch(gpa, io, arena, streams, amb, "merge")) return rc;
    return mergeOnce(gpa, io, arena, verb_args, streams, amb, checkout_root, &tree);
}

fn mergeOnce(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
    tree: *cmd_sync.ElidedTree,
) cli.Exit {
    // 1. Parse the one-positional NAME plus `-h`/`--help` and the two mutually-
    //    exclusive baseline flags `--cherrypick`/`--backout` (B-merge-25/26/40).
    //    Help wins; an unknown option, a second positional, or both flags is a
    //    usage error (exit 2). A missing NAME is a usage error — NAME is
    //    mandatory (unlike `update`, which defaults to tip). The flagless grammar
    //    stays byte-identical to the shipped surface (B-merge-31).
    const parsed = switch (cli.parseMergeArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "merge", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "merge", .extra_argument, tok),
        .bad_strategy => |tok| {
            if (tok.len == 0) {
                streams.err.writeAll("zit merge: -X needs a strategy: ours or theirs\n") catch {};
            } else {
                streams.err.print(
                    "zit merge: '{s}' is not a merge strategy; use ours or theirs\n",
                    .{tok},
                ) catch {};
            }
            streams.err.writeAll("try 'zit merge --help'\n") catch {};
            return .usage;
        },
        .conflicting_flags => {
            streams.err.writeAll(
                "zit merge: --cherrypick and --backout cannot be combined\n",
            ) catch {};
            streams.err.writeAll("try 'zit merge --help'\n") catch {};
            return .usage;
        },
    };
    if (parsed.help) {
        streams.out.writeAll(merge_help) catch {};
        return .ok;
    }
    // With no NAME, a real merge takes the one other open leaf
    // (resolved once the repository is open); a probe still needs a name.
    var name: []const u8 = parsed.checkin orelse "";
    if (name.len == 0 and (parsed.probe or parsed.special != null)) return cli.usageError(streams, "merge", .no_name, "");
    // `-X ours|theirs`. Absent means the shipped behaviour: a
    // content conflict is written as markers and left for a human. The parser
    // has already refused anything that is neither, so this mapping is total.
    const strategy: merge3.Strategy = if (parsed.strategy) |sname|
        (if (std.mem.eql(u8, sname, "ours")) .ours else .theirs)
    else
        .conflict;
    // `--probe` answers "would this merge cleanly?" and writes NOTHING.
    // It is a READ, so it takes `-R`, needs no checkout, and never autosyncs:
    // a caller asking a question must not have its store mutated by the asking.
    // Everything below this line is the writing verb.
    if (parsed.probe)
        return runMergeProbe(gpa, io, arena, parsed, streams, amb, checkout_root);

    // `-R` is granted to this verb for `--probe` only. A real merge
    // writes a working tree, so it is refused BY NAME here rather than left to
    // fail as a discovery miss -- which would tell the operator to pass `-R`
    // when they just did.
    if (checkout_root == null and amb.repo_override != null) {
        streams.err.writeAll(
            "zit merge: -R names a repository with no working tree to merge into; " ++
                "run it in a checkout, or ask with --probe\n",
        ) catch {};
        return .failure;
    }

    // Autosync pull, before resolution — same reasoning as `update`'s.
    // A rerun after the tree fetch has just spoken to the remote.
    if (!parsed.no_sync and !tree.fetched) cmd_sync.autosyncPull(gpa, io, arena, streams, "merge");

    // 2. Open the repository through the read-only facade (B-merge-27): a missing
    //    repo / read fault is exit 1, distinct from the exit-2 usage class, and
    //    the repository check precedes any resolution or working-tree read.
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    var owns_root = false;
    if (checkout_root) |given| {
        // A named checkout: open the repository THROUGH it, exactly as
        // discovery does, so a store-relocated worktree resolves its store the
        // same way (`checkout.storeDirOf`). No second resolution rule.
        repo.open(gpa, io, given.dir, .{ .bypass_cache = false, .mode = .full }) catch |e| {
            if (repo.view.fault) |f| return diagnostics.repoDeriveFault(streams, "merge", f);
            return repoOpenFail(streams, "merge", e);
        };
        root_dir = given.dir;
    } else {
        const rc = openRepo(gpa, io, arena, streams, "merge", null, false, false, &repo, &root_dir);
        if (rc != .ok) return rc;
        owns_root = true;
    }
    defer if (owns_root) root_dir.close(io);
    defer repo.deinit(gpa);

    // 3. Resolve NAME (repo-state §8.3) → the "other" side. Unresolvable or
    //    ambiguous is a runtime failure (exit 1, B-merge-18), nothing mutated.
    if (name.len == 0) {
        name = soleOtherOpenLeaf(gpa, arena, &repo, streams) orelse return .failure;
    }
    const other = repo.resolve(name, .checkin) catch |e| {
        switch (e) {
            error.NotFound => {
                streams.err.print("zit merge: check-in '{s}' not found\n", .{name}) catch {};
                mergeHorizonHint(gpa, io, root_dir, streams);
            },
            error.Ambiguous => streams.err.print("zit merge: name '{s}' is ambiguous\n", .{name}) catch {},
            error.OutOfMemory => return stateOom(streams, "merge"),
        }
        return .failure;
    };

    // 4. The current checkout is the merge's "current" side. An unborn checkout
    //    has nothing to merge into.
    const current = repo.currentCheckoutRid() orelse {
        streams.err.writeAll("zit merge: no current check-in to merge into\n") catch {};
        return .failure;
    };

    // 5. The checkout record. A merge already pending does not refuse this
    //    one: Fossil stacks merges, each recorded behind the last, and the
    //    commit names every one (B-merge-15). An unresolved earlier merge's
    //    conflict markers are just working-tree content to merge into.
    var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
    const ck = (checkout.read(io, root_dir, &ck_buf) catch |e|
        return checkoutFail(streams, "merge", e)) orelse {
        streams.err.writeAll("zit merge: no current check-in to merge into\n") catch {};
        return .failure;
    };

    // 6. The working tree's own side. B-merge-14 used to refuse a
    //    dirty tree here, because the merge computed over the checkout's
    //    EFFECTIVE content — what the check-in says is on disk — and a dirty
    //    tree contradicts that. The fix is not to relax the check but to stop
    //    needing it: the current side becomes the working tree, so there is
    //    nothing left to disagree with. A clean tree scans to no divergences and
    //    every side is read exactly as before.
    //
    //    Scanned before the ancestry gates, in the position the refusal held, so
    //    an unreadable tree still reports before an up-to-date/unrelated verdict
    //    can mask it (plan §3 order).
    const log = repo.logStore(gpa) catch |e| return repoOpenFail(streams, "merge", e);
    const local = switch (localSide(gpa, io, arena, root_dir, log, streams)) {
        .ok => |l| l,
        .fail => |exit| return exit,
    };

    // 6b. Special merges (merge-flags.md) choose an ALTERNATE baseline inside
    //     this same machinery — cherrypick applies REV's own change, backout
    //     reverses it — so they skip the plain-merge ancestry gates (up-to-date /
    //     unrelated-histories / merge-base) entirely and route straight through
    //     `classifyFile`/`applyMerge` with base/other picked per the flag. A root
    //     REV (no primary parent) uses the EMPTY file set for its parent side, so
    //     no refusal is needed (error defined out of existence).
    if (parsed.special) |sp| {
        const rev = other;
        const pp = repo.state().primaryParentOf(rev);
        const sel = specialBaseline(sp, rev, pp);
        const rev_hash = repo.hashOf(rev);
        // Fossil ignores pending merges here: the baseline is REV's own parent.
        switch (mergeDeepenForContent(gpa, io, arena, root_dir, streams, &repo, &.{ sel.base, current, sel.other })) {
            .held => {},
            .deepened => return runMergeIn(gpa, io, arena, verb_args, streams, amb, checkout_root),
            .refused => |exit| return exit,
        }
        return computeAndApplyMerge(gpa, io, arena, &repo, root_dir, sel.base, current, sel.other, ck, .{
            .pending = .{ .kind = if (sp == .cherrypick) .cherrypick else .backout, .hash = rev_hash },
            .report_verb = if (sp == .cherrypick) "cherry-picked" else "backed out",
            .report_hash = rev_hash,
            .refuse_empty = true,
            .use_precedent = !parsed.no_precedent,
        }, strategy, local, streams, tree);
    }

    // 7. Up to date (B-merge-16): NAME is an ancestor of the checkout, itself
    //    included → the checkout already contains it, refuse. This is the pure
    //    §3.3 full-ancestry membership test (`isAncestorOf`), mtime-INDEPENDENT —
    //    NOT `base == other`, which the merge-base mtime tiebreak defeats when
    //    `other` ties another ancestor on mtime and loses the least-hash
    //    selection: the base is then a different node, the equality misses, and
    //    an ancestor would wrongly be merged as a parent. Self-membership
    //    subsumes the self-merge case (other == current).
    if (repo.isAncestorOf(gpa, other, current) catch return mergeOom(streams)) {
        streams.err.writeAll("zit merge: already up to date; nothing to merge\n") catch {};
        return .failure;
    }

    // 8. Merge base over FULL ancestry (repo-state `mergeBaseOf`; ambiguities.md
    //    merge-base). No common ancestor → unrelated histories, refuse
    //    (B-merge-17). The up-to-date case (NAME an ancestor of the checkout) was
    //    already refused in step 7 by the mtime-independent ancestry test, so
    //    `base` here is strictly the three-way merge base.
    const base = blk: {
        // --baseline: the operator names the common ancestor.
        if (parsed.baseline) |bn| break :blk repo.resolve(bn, .checkin) catch |e| {
            switch (e) {
                error.NotFound => streams.err.print("zit merge: baseline '{s}' not found\n", .{bn}) catch {},
                error.Ambiguous => streams.err.print("zit merge: baseline '{s}' is ambiguous\n", .{bn}) catch {},
                error.OutOfMemory => return mergeOom(streams),
            }
            return .failure;
        };
        // Horizon draft section 5.5 -- under a structural horizon a base found
        // over what is held may be outranked by one below the boundary: ask
        // the origin and deepen, exactly as when none is found.
        const secondaries = pendingMergeRids(arena, &repo, current, ck) catch return mergeOom(streams);
        const secondary_hashes = arena.alloc([]const u8, secondaries.len) catch return mergeOom(streams);
        for (secondaries, secondary_hashes) |rid, *hash| hash.* = repo.hashOf(rid);
        if (!merge_deepen_spent and (repo.mergeBaseMayLieBelow(gpa, other, secondaries) catch return mergeOom(streams))) {
            switch (mergeDeepenToBase(gpa, io, arena, root_dir, streams, amb, repo.hashOf(other), secondary_hashes)) {
                .deepened => {
                    merge_deepen_spent = true;
                    return runMergeIn(gpa, io, arena, verb_args, streams, amb, checkout_root);
                },
                .refused => return .failure,
                .held => {},
            }
        }
        const found = if (secondaries.len == 1)
            repo.mergeBaseOf(gpa, current, other) catch return mergeOom(streams)
        else
            // Merges are pending: the base is Fossil's pivot against the
            // checkout AND each of them, which no two-way base can give.
            repo.pivotOf(gpa, other, secondaries) catch return mergeOom(streams);
        const b = found orelse {
            // Horizon draft section 5.5 -- under a structural horizon "no common
            // ancestor" usually means the base lies below C. Ask the origin,
            // deepen to the base, and run the merge again over real artifacts.
            if (!merge_deepen_spent) {
                switch (mergeDeepenToBase(gpa, io, arena, root_dir, streams, amb, repo.hashOf(other), secondary_hashes)) {
                    .deepened => {
                        merge_deepen_spent = true;
                        // The re-entered run opens its own view; this one's is
                        // released by the defers above when the result comes back.
                        return runMergeIn(gpa, io, arena, verb_args, streams, amb, checkout_root);
                    },
                    .refused => return .failure,
                    .held => {},
                }
            }
            streams.err.print(
                "zit merge: '{s}' shares no history with the current check-in\n",
                .{name},
            ) catch {};
            return .failure;
        };
        // NAME is an ancestor of a pending merge: already in the tree.
        if (b == other) {
            streams.err.writeAll("zit merge: already up to date; nothing to merge\n") catch {};
            return .failure;
        }
        break :blk b;
    };

    // 9. Compute the outcome set purely and materialize it, recording other's
    //    hash as the pending merge parent. Reports last.
    switch (mergeDeepenForContent(gpa, io, arena, root_dir, streams, &repo, &.{ base, current, other })) {
        .held => {},
        .deepened => return runMergeIn(gpa, io, arena, verb_args, streams, amb, checkout_root),
        .refused => |exit| return exit,
    }
    return computeAndApplyMerge(gpa, io, arena, &repo, root_dir, base, current, other, ck, .{
        .pending = .{ .kind = if (parsed.integrate) .integrate else .merge, .hash = repo.hashOf(other) },
        .report_verb = "merged",
        .report_hash = repo.hashOf(other),
        .refuse_empty = false,
        .use_precedent = !parsed.no_precedent,
    }, strategy, local, streams, tree);
}

/// Fossil's pivot secondaries for a plain merge: the current check-in, then
/// each pending plain merge (`vmerge.id = 0` only -- not an integrate, a
/// cherrypick or a backout). Arena-owned.
fn pendingMergeRids(arena: std.mem.Allocator, repo: *Repository, current: repostate.Rid, ck: checkout.CheckoutState) error{OutOfMemory}![]const repostate.Rid {
    var out: std.ArrayList(repostate.Rid) = .empty;
    try out.append(arena, current);
    var it = checkout.pending(ck);
    while (it.next()) |p| {
        if (p.kind != .merge) continue;
        // A pending merge names a check-in this store holds; one it can no
        // longer resolve contributes nothing, as an unknown rid does in Fossil.
        if (repo.lookup(p.hash)) |rid| try out.append(arena, rid);
    }
    return out.items;
}

/// The hash of the one open leaf that is not the current check-in,
/// or null (with a diagnostic) when there are none or several.
fn soleOtherOpenLeaf(gpa: std.mem.Allocator, arena: std.mem.Allocator, repo: *Repository, streams: cli.Streams) ?[]const u8 {
    const current = repo.currentCheckoutRid() orelse {
        streams.err.writeAll("zit merge: no NAME given and no current check-in to measure against\n") catch {};
        return null;
    };
    var found: std.ArrayList(Repository.Rid) = .empty;
    defer found.deinit(gpa);
    var it = repo.view.state.leaves();
    while (it.next()) |rid| {
        if (rid == current) continue;
        if (!repo.view.state.isOpenLeaf(rid)) continue;
        found.append(gpa, rid) catch {
            streams.err.writeAll("zit merge: out of memory\n") catch {};
            return null;
        };
    }
    if (found.items.len == 1) return arena.dupe(u8, repo.hashOf(found.items[0])) catch null;
    if (found.items.len == 0) {
        streams.err.writeAll("zit merge: no NAME given and no other open leaf to merge\n") catch {};
        return null;
    }
    streams.err.print("zit merge: no NAME given and {d} other open leaves; name one:\n", .{found.items.len}) catch {};
    for (found.items) |rid| streams.err.print("  {s} ({s})\n", .{ repo.hashOf(rid)[0..12], repo.branchOf(rid) }) catch {};
    return null;
}

/// What the WORKING TREE holds for each path that diverges from the check-in
/// the checkout is on. Empty on a clean tree, which is why every
/// clean merge reads exactly the sides it always did.
///
/// `merge`'s "current" side is the checkout. Before this, that meant the
/// check-in's stored content, and a dirty tree was refused because the two
/// disagreed. Now a divergent path answers from disk instead, which is what the
/// operator actually has and what a three-way merge is supposed to compare.
const LocalSide = struct {
    /// Divergent path -> the bytes on disk, or `.absent` where the file is gone.
    /// A path absent from this map is clean: its content IS the check-in's.
    by_path: std.StringHashMap(update.WorktreeContent),

    fn currentOf(self: *const LocalSide, path: []const u8) ?update.WorktreeContent {
        return self.by_path.get(path);
    }
};

/// Scan the working tree and read back every divergent path. Refuses, naming
/// the paths, when one holds something a three-way merge has no bytes for.
fn localSide(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    log: *logstore.LogStore,
    streams: cli.Streams,
) union(enum) { ok: LocalSide, fail: cli.Exit } {
    var out = LocalSide{ .by_path = std.StringHashMap(update.WorktreeContent).init(arena) };
    const divergences = update.scanWorktree(gpa, arena, io, root_dir, log) catch |e|
        return .{ .fail = mergeApplyFail(streams, e) };
    if (divergences.len == 0) return .{ .ok = out };

    var unsupported: std.ArrayList([]const u8) = .empty;
    for (divergences) |d| {
        const content: update.WorktreeContent = switch (d.kind) {
            // Absent on our side by definition; not re-read.
            .missing, .removed => .absent,
            .modified, .added => update.readWorktreeContent(arena, io, root_dir, d.path) catch |e|
                return .{ .fail = mergeApplyFail(streams, e) },
        };
        if (content == .unsupported) {
            unsupported.append(arena, d.path) catch return .{ .fail = mergeOom(streams) };
            continue;
        }
        out.by_path.put(d.path, content) catch return .{ .fail = mergeOom(streams) };
    }

    // A symlink, a directory, or an oversized file where a regular file's bytes
    // are needed. Refused before any mutation and named, rather than guessed at.
    if (unsupported.items.len != 0) {
        for (unsupported.items) |p| {
            streams.err.print("zit merge: cannot merge local changes to {s}\n", .{p}) catch {};
        }
        streams.err.print(
            "zit merge: {d} local change(s) cannot be merged; commit or revert them first\n",
            .{unsupported.items.len},
        ) catch {};
        return .{ .fail = .failure };
    }
    return .{ .ok = out };
}

/// The alternate baseline a special merge computes over (merge-flags.md
/// semantics): with REV's primary parent PP —
///   `--cherrypick`: base = PP, other = REV — applies REV's own change.
///   `--backout`:    base = REV, other = PP — applies its reverse.
/// A root REV has `pp == null`, so the parent side is null → the EMPTY file set
/// (error defined out of existence). Pure: the whole baseline decision, unit-
/// testable on rids alone.
const SpecialBaseline = struct { base: ?repostate.Rid, other: ?repostate.Rid };

fn specialBaseline(sp: cli.SpecialMerge, rev: repostate.Rid, pp: ?repostate.Rid) SpecialBaseline {
    return switch (sp) {
        .cherrypick => .{ .base = pp, .other = rev },
        .backout => .{ .base = rev, .other = pp },
    };
}

/// What `computeAndApplyMerge` records and reports: the merge operation it
/// adds to the checkout's pending ones, the success-line verb/hash, and
/// whether a no-op application refuses (special merges) versus falls through
/// as a zero-change merge (plain merges, unchanged behavior).
const MergeApply = struct {
    pending: checkout.Pending,
    report_verb: []const u8,
    report_hash: []const u8,
    refuse_empty: bool,
    /// False when `--no-precedent` declined replay for this invocation.
    use_precedent: bool = true,
};

test "specialBaseline: cherrypick is PP→REV, backout is REV→PP (merge-flags.md)" {
    const rev: repostate.Rid = 7;
    const pp: repostate.Rid = 3;
    // cherrypick applies REV's own change: base = its primary parent, other = REV.
    const cp = specialBaseline(.cherrypick, rev, pp);
    try std.testing.expectEqual(@as(?repostate.Rid, pp), cp.base);
    try std.testing.expectEqual(@as(?repostate.Rid, rev), cp.other);
    // backout reverses it: base = REV, other = its primary parent.
    const bo = specialBaseline(.backout, rev, pp);
    try std.testing.expectEqual(@as(?repostate.Rid, rev), bo.base);
    try std.testing.expectEqual(@as(?repostate.Rid, pp), bo.other);
    // A root REV (no primary parent): the parent side is the EMPTY file set
    // (null) — cherrypick's base and backout's other. No refusal needed.
    const cp_root = specialBaseline(.cherrypick, rev, null);
    try std.testing.expectEqual(@as(?repostate.Rid, null), cp_root.base);
    try std.testing.expectEqual(@as(?repostate.Rid, rev), cp_root.other);
    const bo_root = specialBaseline(.backout, rev, null);
    try std.testing.expectEqual(@as(?repostate.Rid, rev), bo_root.base);
    try std.testing.expectEqual(@as(?repostate.Rid, null), bo_root.other);
}

/// One path's F card on each of the three merge sides (null = absent there).
const MergeSlot = struct {
    base: ?artifact.FCard = null,
    current: ?artifact.FCard = null,
    other: ?artifact.FCard = null,
};

/// The current-side attribute wins (B-merge-23); when the path is added only on
/// the other side, its attribute is the only one there.
/// Optional-hash equality for the record-level three-way: both-absent is
/// equal; one-sided absence is not; present compares byte-wise.
fn hashEql(a: ?[]const u8, b: ?[]const u8) bool {
    if (a == null and b == null) return true;
    if (a == null or b == null) return false;
    return std.mem.eql(u8, a.?, b.?);
}

/// A path's mode after a merge, Fossil's rule: a side that left the mode as
/// the base had it takes the other side's, so a mode changed on one side
/// only is kept; when both changed it, or the base lacks the path, the
/// current side wins. Null is an absent path.
pub fn mergedMode(base: ?artifact.FileMode, cur: ?artifact.FileMode, oth: ?artifact.FileMode) ?artifact.FileMode {
    const c = cur orelse return oth;
    const o = oth orelse return c;
    const b = base orelse return c;
    return if (c == b) o else c;
}

/// The perm token for a mode: `x`, `l`, or none for a regular file.
pub fn permOfMode(mode: ?artifact.FileMode) ?[]const u8 {
    return switch (mode orelse return null) {
        .executable => "x",
        .symlink => "l",
        .regular => null,
    };
}

fn modeOfCard(f: ?artifact.FCard) ?artifact.FileMode {
    return artifact.fileModeOf((f orelse return null).perm);
}

/// Step 8 of `runMerge`, split out for legibility: read the three §8.2 effective
/// file sets, classify every path with the pure `merge3` engine into a
/// `MergeEntry` list, hand it to `update.applyMerge` (which journals, records the
/// merge parent, and materializes), then report. Conflicts are written in-tree
/// and listed on stderr with exit 1; the merge parent is recorded either way.
fn computeAndApplyMerge(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    repo: *Repository,
    root_dir: std.Io.Dir,
    base: ?repostate.Rid,
    current: repostate.Rid,
    other: ?repostate.Rid,
    ck: checkout.CheckoutState,
    spec: MergeApply,
    strategy: merge3.Strategy,
    /// The working tree's own content for divergent paths. Empty on a
    /// clean tree, which reproduces the original all-sides-from-the-store read.
    local: LocalSide,
    streams: cli.Streams,
    tree: *cmd_sync.ElidedTree,
) cli.Exit {
    // The three effective file sets (§8.2 merge-walk). Kept alive until after
    // `applyMerge` — every `MergeEntry.path`/`perm` borrows these manifests. A
    // null side is the EMPTY file set (a special merge whose REV is a root, so
    // its primary-parent side has no manifest).
    var base_list: ?Repository.FileList = if (base) |b|
        (repo.files(gpa, b) catch |e| return mergeFilesFail(streams, e, tree)) orelse return mergeCorrupt(streams)
    else
        null;
    defer if (base_list) |*l| l.deinit(gpa);
    var cur_list = (repo.files(gpa, current) catch |e| return mergeFilesFail(streams, e, tree)) orelse
        return mergeCorrupt(streams);
    defer cur_list.deinit(gpa);
    var oth_list: ?Repository.FileList = if (other) |o|
        (repo.files(gpa, o) catch |e| return mergeFilesFail(streams, e, tree)) orelse return mergeCorrupt(streams)
    else
        null;
    defer if (oth_list) |*l| l.deinit(gpa);

    // The union of paths across the three sides; each slot names the side's card.
    // Iteration order is unspecified — the conflict list is sorted before it is
    // reported and `applyMerge` is order-independent, so nothing depends on it.
    var slots = std.StringHashMap(MergeSlot).init(arena);
    if (base_list) |*bl| {
        var bit = bl.iterator();
        while (bit.next()) |f| {
            const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
            if (!gop.found_existing) gop.value_ptr.* = .{};
            gop.value_ptr.base = f;
        }
    }
    var cit = cur_list.iterator();
    while (cit.next()) |f| {
        const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
        if (!gop.found_existing) gop.value_ptr.* = .{};
        gop.value_ptr.current = f;
    }
    // Deliberately NOT seeding slots for locally-added paths the manifests do
    // not name. An uncommitted add that the OTHER side also adds is already
    // reached through `oth_list`, and its current side resolves from `local`
    // below — so the add-vs-add collision conflicts rather than silently taking
    // their bytes. One the other side does NOT have is in no manifest, so the
    // walk has nothing to decide about it and it simply stays on disk.
    // Verified both ways: seeding those slots changes no outcome.
    if (oth_list) |*ol| {
        var oit = ol.iterator();
        while (oit.next()) |f| {
            const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
            if (!gop.found_existing) gop.value_ptr.* = .{};
            gop.value_ptr.other = f;
        }
    }

    // Classify every path (pure), building the outcome entries and the conflict
    // list. Bytes/results are arena-owned and outlive `applyMerge`.
    var entries: std.ArrayList(update.MergeEntry) = .empty;
    var conflicts: std.ArrayList([]const u8) = .empty;
    // Sparse-cone RFC section 4.4: out-of-cone paths resolve at HASH level
    // (record-level application) -- no blob read, no materialization. The
    // resolved outcomes accumulate into the merge_overlay the next commit
    // composes; a both-changed path is a genuine content conflict that
    // cannot resolve without bytes this checkout deliberately lacks.
    var merge_cone = update.readStoredCone(gpa, io, root_dir) catch {
        streams.err.writeAll("zit merge: cannot read the checkout state\n") catch {};
        return .failure;
    };
    defer if (merge_cone) |*c| c.deinit(gpa);
    var overlay: std.ArrayList(update.OverlayEntry) = .empty;
    var cross_conflicts: std.ArrayList([]const u8) = .empty;
    // A merge stacked on pending ones finds their out-of-cone outcomes in the
    // overlay, not in the check-in: those are this side's cards now, and they
    // carry into the new overlay unless this merge resolves the path again.
    // With nothing pending an overlay is a stale one an undo left, ignored.
    var prior = std.StringHashMap(update.OverlayEntry).init(arena);
    if (merge_cone != null and checkout.pending(ck).head != null) {
        const payload = checkout.readSectionAlloc(arena, io, root_dir, .merge_overlay) catch |e| switch (e) {
            error.OutOfMemory => return mergeOom(streams),
            else => {
                streams.err.writeAll("zit merge: cannot read the checkout state\n") catch {};
                return .failure;
            },
        };
        if (payload) |bytes| {
            const decoded = update.decodeOverlay(arena, bytes) catch |e| switch (e) {
                error.OutOfMemory => return mergeOom(streams),
                error.Corrupt => return mergeCorrupt(streams),
            };
            for (decoded) |entry| prior.put(entry.path, entry) catch return mergeOom(streams);
        }
    }
    var it = slots.iterator();
    while (it.next()) |kv| {
        const path = kv.key_ptr.*;
        const slot = kv.value_ptr.*;
        if (merge_cone) |*c| {
            if (!c.covers(path)) {
                const base_h: ?[]const u8 = if (slot.base) |f| f.hash else null;
                const earlier = prior.get(path);
                const cur_h: ?[]const u8 = if (earlier) |e| e.hash else if (slot.current) |f| f.hash else null;
                const oth_h: ?[]const u8 = if (slot.other) |f| f.hash else null;
                const cur_mode: ?artifact.FileMode = if (earlier) |e|
                    (if (e.hash == null) null else artifact.fileModeOf(e.perm))
                else
                    modeOfCard(slot.current);
                const mode = mergedMode(modeOfCard(slot.base), cur_mode, modeOfCard(slot.other));
                if (hashEql(oth_h, cur_h) or hashEql(oth_h, base_h)) {
                    // Content: ours stands, by carry. Only a mode the other
                    // side changed still has to reach the record.
                    if (cur_h != null and mode != cur_mode) overlay.append(arena, .{
                        .path = path,
                        .hash = cur_h,
                        .perm = permOfMode(mode),
                    }) catch return mergeOom(streams);
                } else if (hashEql(cur_h, base_h)) {
                    // Theirs-only change: adopt theirs' card by hash.
                    overlay.append(arena, .{
                        .path = path,
                        .hash = oth_h,
                        .perm = permOfMode(mode),
                    }) catch return mergeOom(streams);
                } else {
                    cross_conflicts.append(arena, path) catch return mergeOom(streams);
                }
                continue;
            }
        }
        // The bytes of each side (null = path absent there). The §8.2 walk
        // suppresses hash-less delete markers, so a present card always names a
        // stored blob; a missing blob is a corruption. A read fault returns an
        // already-rendered `cli.Exit` from this function verbatim.
        const base_side: merge3.Side = if (slot.base) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;
        // The current side is the WORKING TREE. A divergent path
        // answers from disk; a clean one has no entry, and its working bytes
        // are by definition the check-in's, so it still reads from the store.
        const cur_side: merge3.Side = if (local.currentOf(path)) |content| switch (content) {
            .content => |c| c.bytes,
            .absent => null,
            // `localSide` refused these before anything mutated.
            .unsupported => unreachable,
        } else if (slot.current) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;
        const oth_side: merge3.Side = if (slot.other) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;

        const outcome = merge3.classifyFile(arena, base_side, cur_side, oth_side, strategy) catch return mergeOom(streams);
        // The current side's mode is the working file's when it diverges
        // (B-merge-23: a locally changed mode counts as a local change, as a
        // changed byte does), else the card's. The merged mode then follows
        // `mergedMode`, so a mode the other side changed is not lost.
        const cur_mode: ?artifact.FileMode = if (local.currentOf(path)) |content| switch (content) {
            .content => |c| if (c.mode == .executable) .executable else .regular,
            .absent => null,
            .unsupported => unreachable,
        } else modeOfCard(slot.current);
        const mode = mergedMode(modeOfCard(slot.base), cur_mode, modeOfCard(slot.other));
        const perm: ?[]const u8 = permOfMode(mode) orelse "";
        switch (outcome) {
            // Same bytes; a mode the other side changed is still written.
            .unchanged => if (cur_side != null and mode != cur_mode) entries.append(arena, .{
                .path = path,
                .action = .{ .write = .{ .bytes = cur_side.?, .perm = perm } },
            }) catch return mergeOom(streams),
            .delete => entries.append(arena, .{ .path = path, .action = .delete }) catch return mergeOom(streams),
            .take_other => entries.append(arena, .{
                .path = path,
                .action = .{ .write = .{ .bytes = oth_side.?, .perm = perm } },
            }) catch return mergeOom(streams),
            .clean_merge => |r| entries.append(arena, .{
                .path = path,
                .action = .{ .write = .{ .bytes = r.bytes, .perm = perm } },
            }) catch return mergeOom(streams),
            .text_conflict => |r| {
                entries.append(arena, .{
                    .path = path,
                    .action = .{ .write = .{ .bytes = r.bytes, .perm = perm } },
                }) catch return mergeOom(streams);
                conflicts.append(arena, path) catch return mergeOom(streams);
            },
            .whole_file_conflict => {
                const bytes = merge3.writeEnvelope(arena, cur_side, base_side, oth_side) catch return mergeOom(streams);
                entries.append(arena, .{
                    .path = path,
                    .action = .{ .write = .{ .bytes = bytes, .perm = perm } },
                }) catch return mergeOom(streams);
                conflicts.append(arena, path) catch return mergeOom(streams);
            },
        }
    }

    // Precedent replay: a conflict whose bytes match a resolution the
    // operator already authored is resolved from it instead of being written as
    // markers, and the ones that miss are remembered so `commit` can learn how
    // they get settled. Deliberately a pass OVER the outcome set rather than a
    // branch inside the classifier switch above: this feature has no opinion
    // about how a conflict is produced, only about one that already exists.
    _ = cmd_precedent.replayAtMerge(
        gpa,
        io,
        arena,
        root_dir,
        entries.items,
        &conflicts,
        spec.use_precedent,
        streams,
    );

    // A special merge whose change is already contained in the current checkout
    // classifies to zero entries — refuse before mutating anything (B-merge-39),
    // parallel to the plain merge's up-to-date refusal. A plain merge never sets
    // `refuse_empty`, so its behavior (call `applyMerge` regardless) is unchanged.
    if (spec.refuse_empty and entries.items.len == 0) {
        streams.err.writeAll("zit merge: nothing to apply\n") catch {};
        return .failure;
    }

    // Materialize (journal-armed) and record the operation behind any already
    // pending. `applyMerge` writes the checkout FIRST, so a conflict still
    // records the pending state for `zit commit`/`zit undo` (B-merge-3/7/35).
    if (cross_conflicts.items.len != 0) {
        streams.err.print(
            "zit merge: {d} out-of-cone file(s) changed on both sides, starting with '{s}'\n" ++
                "zit merge: resolving them needs content this checkout's sparse cone excludes;\n" ++
                "zit merge: widen the cone ('zit cone add ...') and re-run the merge\n",
            .{ cross_conflicts.items.len, cross_conflicts.items[0] },
        ) catch {};
        return .failure;
    }
    // The earlier merges' outcomes this one did not resolve again ride along.
    if (prior.count() != 0) {
        var resolved = std.StringHashMap(void).init(arena);
        for (overlay.items) |entry| resolved.put(entry.path, {}) catch return mergeOom(streams);
        var pit = prior.valueIterator();
        while (pit.next()) |entry| {
            if (!resolved.contains(entry.path)) overlay.append(arena, entry.*) catch return mergeOom(streams);
        }
    }
    const overlay_bytes: ?[]u8 = if (overlay.items.len != 0)
        update.encodeOverlay(gpa, overlay.items) catch |e| switch (e) {
            error.OutOfMemory => return mergeOom(streams),
            error.Overflow => return mergeCorrupt(streams),
        }
    else
        null;
    defer if (overlay_bytes) |b| gpa.free(b);

    // A merge changes the pending set, never the check-in, the branch or the
    // checkout's manifest opt-in, which `withPending` carries from `ck`.
    var pending_buf: checkout.PendingBuf = undefined;
    const new_ck = checkout.withPending(ck, spec.pending, &pending_buf) catch {
        streams.err.print(
            "zit merge: {d} merges are already pending; commit them first\n",
            .{checkout.max_stacked + 1},
        ) catch {};
        return .failure;
    };
    update.applyMerge(gpa, io, root_dir, entries.items, overlay_bytes, new_ck) catch |e| return mergeApplyFail(streams, e);

    if (overlay.items.len != 0) {
        streams.out.print("{d} out-of-cone change(s) applied to the record\n", .{overlay.items.len}) catch {};
    }
    // Report last. Conflicts → stderr only, exit 1; clean → the confirmation to
    // stdout only, exit 0 (B-merge-28 stream separation).
    if (conflicts.items.len != 0) {
        std.mem.sort([]const u8, conflicts.items, {}, lessByHash);
        for (conflicts.items) |p| streams.err.print("zit merge: conflict in {s}\n", .{p}) catch {};
        streams.err.print(
            "zit merge: {d} conflict(s); resolve and commit, or run 'zit undo'\n",
            .{conflicts.items.len},
        ) catch {};
        return .failure;
    }
    streams.out.print(
        "{s} {s} into the working tree ({d} file(s) changed)\n",
        .{ spec.report_verb, spec.report_hash, entries.items.len },
    ) catch {};
    return .ok;
}

fn mergeOom(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit merge: out of memory\n") catch {};
    return .failure;
}

fn mergeCorrupt(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit merge: cannot read repository: repository is corrupt\n") catch {};
    return .failure;
}

/// Maps a `Repository.files` fault to the shipped diagnostic phrasing. The three
/// §8 enumeration faults and a corrupt manifest all read as "repository is
/// corrupt" — a resolved name whose manifests do not enumerate is a data fault.
fn mergeFilesFail(s: cli.Streams, err: Repository.FilesError, tree: *cmd_sync.ElidedTree) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit merge: out of memory\n") catch {},
        error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
        error.CannotRead => s.err.writeAll("zit merge: cannot read repository: input/output error\n") catch {},
        error.ImportPending => s.err.writeAll("zit merge: an incremental import is pending; run 'zit import-git --recover DIR'\n") catch {},
        error.Corrupt,
        error.NotManifest,
        error.BaselineUnresolvable,
        => s.err.writeAll("zit merge: cannot read repository: repository is corrupt\n") catch {},
        error.ElidedByCone => tree.note(s, "merge"),
    }
    return .failure;
}

/// Maps an `update.ApplyError` from the merge materialization (or the clean-tree
/// gate) to the shipped `zit merge:` phrasing, mirroring `updateApplyFail`. The
/// check-in/baseline id faults cannot arise here — `files` already validated the
/// resolved manifests — but `ApplyError` is one closed set, so they fold into
/// the corrupt-repository message rather than an invented one.
fn mergeApplyFail(s: cli.Streams, err: update.ApplyError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit merge: out of memory\n") catch {},
        error.FileContentMissing => {
            var b: [512]u8 = undefined;
            s.err.print("zit merge: {s}\n", .{update.stageFaultReason(&b)}) catch {};
        },
        error.SparseMergeUnsupported => s.err.writeAll(
            "zit merge: the merge changes files outside this checkout's sparse cone\n" ++
                "record-level application is not supported yet; widen the cone with\n" ++
                "'zit update --cone PATH' (or return to dense with --dense) and re-run the merge\n",
        ) catch {},
        error.WorktreeNotClean => s.err.writeAll("zit merge: working tree is not clean\n") catch {},
        error.CurrentStateInvalid => s.err.writeAll("zit merge: current working-tree state is invalid\n") catch {},
        error.UnmanagedCollision => s.err.writeAll("zit merge: an untracked file or directory is in the way\n") catch {},
        error.InvalidPath => s.err.writeAll("zit merge: the merge names an invalid file path\n") catch {},
        error.ReservedPath => s.err.writeAll("zit merge: the merge names a reserved file path\n") catch {},
        error.SymlinkUnsupported => s.err.writeAll("zit merge: the merge contains an unsupported symlink entry\n") catch {},
        error.Storage => s.err.writeAll("zit merge: cannot update working tree: input/output error\n") catch {},
        error.TransactionUnavailable => s.err.writeAll("zit merge: cannot create a transaction directory\n") catch {},
        error.RollbackFailed => s.err.writeAll(
            "zit merge: merge failed and could not be rolled back; the previous working-tree state is retained for recovery\n",
        ) catch {},
        error.CleanupFailed => s.err.writeAll(
            "zit merge: merge applied, but the transaction directory could not be removed\n",
        ) catch {},
        error.StateRecordInvalid => s.err.writeAll(
            "zit merge: cannot read repository: " ++ update.state_record_invalid_reason ++ "\n",
        ) catch {},
        error.Corrupt,
        error.InvalidCheckinId,
        error.CheckinNotFound,
        error.CheckinContentMissing,
        error.CheckinNameMismatch,
        error.AggregateChecksumMismatch,
        error.TargetNotManifest,
        error.BaselineNotFound,
        error.BaselineContentMissing,
        error.BaselineNameMismatch,
        error.BaselineNotManifest,
        => s.err.writeAll("zit merge: cannot read repository: repository is corrupt\n") catch {},
    }
    return .failure;
}

// Same guard as the `zit update` mapper: `Corrupt` alleges damaged storage,
// `StateRecordInvalid` does not. `zit merge` maps most read-path errors onto
// one corruption line, so these two have to be pinned apart explicitly or they
// drift back into that group.
test "merge: the two read-path failures do not share a diagnostic" {
    // `commitMapCapture` renders into one static buffer, so each message is
    // copied out before the next render overwrites it.
    var a: [256]u8 = undefined;
    var b: [256]u8 = undefined;
    const corrupt = mergeFailText(&a, error.Corrupt);
    const state = mergeFailText(&b, error.StateRecordInvalid);

    try std.testing.expect(!std.mem.eql(u8, corrupt, state));
    try std.testing.expect(std.mem.indexOf(u8, corrupt, "corrupt") != null);
    try std.testing.expect(std.mem.indexOf(u8, state, "corrupt") == null);
}

/// Render one `ApplyError` through `mergeApplyFail` into `buf`.
fn mergeFailText(buf: []u8, err: update.ApplyError) []const u8 {
    const rendered = commitMapCapture(mergeApplyFail, .{err}).err;
    // `buf` is the caller's, `rendered` borrows `commitMapCapture`'s static
    // buffer: the fit is a contract of this helper, not a coincidence of the
    // two sizes agreeing today.
    std.debug.assert(rendered.len <= buf.len);
    @memcpy(buf[0..rendered.len], rendered);
    return buf[0..rendered.len];
}

// --- mergeability -------------------------------------------------------------------------------
//
// "Would this land cleanly?", answered from the store alone — no working tree,
// no cone, nothing written. A forge has to be able to ask this before anyone
// clicks accept, because the one thing a server must never do is commit a
// conflict.
//
// It reuses `merge3.classifyFile`, the SAME pure classifier the working-tree
// merge runs, rather than deciding conflicts a second way. Two conflict
// detectors that can disagree would be worse than none: the forge would show
// "clean" on a branch that then refuses, or block a branch that would have
// merged. One engine, two callers.
//
// NOT the hash-level resolution the sparse out-of-cone path uses. That refuses
// any file touched on both sides, which would report conflicts on exactly the
// long-lived branches that merged their target back in — the landing workflow.
// Content-level or the answer is useless.

/// What one branch would do against another.
///
/// Lives beside the merge engine rather than in the verb that first needed it:
/// `landing show` was the first caller, `merge --probe` is the general one, and
/// a caller with its own record index must be able to ask about a pair
/// of check-ins without paying a scan to find records it already knows about.
/// One implementation, three callers.
pub const Mergeability = union(enum) {
    /// Already an ancestor of the target: nothing to land.
    up_to_date,
    /// No common ancestor. Not a conflict — a different repository's history.
    unrelated,
    clean,
    /// Paths that cannot be resolved without a human. Arena-owned, sorted.
    conflicts: []const []const u8,
};

/// A path on one side of a merge: its blob and its mode.
const Side = struct { hash: []const u8, mode: artifact.FileMode };

/// One side's file set by path. An absent path is not in the map.
const SideMap = std.StringHashMapUnmanaged(Side);

/// Index a check-in's file set by path. Names are arena-duped: the `FileList`
/// they borrow from dies with this call.
fn sideMapOf(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    rid: u64,
    out: *SideMap,
) !void {
    var list = (try repo.files(gpa, rid)) orelse return;
    defer list.deinit(gpa);
    var it = list.iterator();
    while (it.next()) |f| {
        const hash = f.hash orelse continue; // a delete marker is absence
        try out.put(arena, try arena.dupe(u8, f.filename), .{
            .hash = try arena.dupe(u8, hash),
            .mode = artifact.fileModeOf(f.perm),
        });
    }
}

/// A probe's full answer: the verdict, plus the paths BOTH sides changed.
///
/// The second half is not a diagnostic -- it is the cone a bare accept needs.
/// sparse-cone Section 4.4 resolves out-of-cone paths at hash level, which
/// cannot combine two edits to one file, so exactly these paths must be
/// in-cone for the merge to reach the content engine. Every other path is
/// correctly resolved at the record without materializing anything.
pub const Probe = struct {
    verdict: Mergeability,
    both_modified: []const []const u8,
};

/// Would `branch` land on `target` without a human? Store-only; writes nothing.
/// `zit merge --probe NAME [--into TARGET]`.
///
/// Reports whether NAME would merge into TARGET without a human, computed from
/// the store and writing nothing. The output is the contract a consumer reads:
///
///     merges   clean | up-to-date | unrelated | conflict (N)
///     conflict PATH                       (one per unresolvable path)
///
/// Exit 0 in every one of those cases -- "has conflicts" is an ANSWER, not a
/// failure. A caller distinguishes them by reading the line, not the status.
///
/// This exists because a consumer with its own record index should not have to
/// scan a store to ask about a pair of check-ins it already knows. The
/// same question through `landing show` costs a full-store walk to FIND the
/// record first; here the caller names both sides.
fn runMergeProbe(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    parsed: cli.MergeArgs,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
) cli.Exit {
    const name = parsed.checkin orelse return cli.usageError(streams, "merge", .no_name, "");

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    var owns_root = false;
    if (checkout_root) |given| {
        repo.open(gpa, io, given.dir, .{ .bypass_cache = false, .mode = .full }) catch |e| {
            if (repo.view.fault) |f| return diagnostics.repoDeriveFault(streams, "merge", f);
            return repoOpenFail(streams, "merge", e);
        };
        root_dir = given.dir;
    } else {
        const rc = openRepo(gpa, io, arena, streams, "merge", amb.repo_override, false, false, &repo, &root_dir);
        if (rc != .ok) return rc;
        owns_root = true;
    }
    defer if (owns_root) root_dir.close(io);
    defer repo.deinit(gpa);

    const other = repo.resolve(name, .checkin) catch {
        streams.err.print("zit merge: check-in '{s}' not found\n", .{name}) catch {};
        mergeHorizonHint(gpa, io, root_dir, streams);
        return .failure;
    };

    // The target: named, or the checkout's own check-in. With `-R` there is no
    // checkout to fall back to, so `--into` is required rather than guessed.
    const current = if (parsed.into) |target|
        repo.resolve(target, .checkin) catch {
            streams.err.print("zit merge: check-in '{s}' not found\n", .{target}) catch {};
            return .failure;
        }
    else
        repo.currentCheckoutRid() orelse {
            streams.err.writeAll(
                "zit merge: --probe against a repository needs --into TARGET (there is no checkout to merge into)\n",
            ) catch {};
            return .failure;
        };

    if (parsed.chain_len > 1) {
        const names = parsed.chain[0..parsed.chain_len];
        const rungs = arena.alloc(u64, names.len) catch return mergeOom(streams);
        rungs[0] = other;
        for (names[1..], rungs[1..]) |n, *r| {
            r.* = repo.resolve(n, .checkin) catch {
                streams.err.print("zit merge: check-in '{s}' not found\n", .{n}) catch {};
                return .failure;
            };
        }
        const verdicts = probeChain(gpa, arena, &repo, current, rungs) catch return mergeOom(streams);
        for (names, verdicts) |n, v| switch (v) {
            .up_to_date => streams.out.print("merges   {s} up-to-date\n", .{n}) catch {},
            .unrelated => streams.out.print("merges   {s} unrelated\n", .{n}) catch {},
            .clean => streams.out.print("merges   {s} clean\n", .{n}) catch {},
            .not_reached => streams.out.print("merges   {s} not-reached\n", .{n}) catch {},
            .conflicts => |paths| {
                streams.out.print("merges   {s} conflict ({d})\n", .{ n, paths.len }) catch {};
                for (paths) |path| streams.out.print("conflict {s}\n", .{path}) catch {};
            },
        };
        return .ok;
    }

    const probe = probeMergeability(gpa, arena, &repo, current, other) catch
        return mergeOom(streams);
    switch (probe.verdict) {
        .up_to_date => streams.out.writeAll("merges   up-to-date\n") catch {},
        .unrelated => streams.out.writeAll("merges   unrelated\n") catch {},
        .clean => streams.out.writeAll("merges   clean\n") catch {},
        .conflicts => |paths| {
            streams.out.print("merges   conflict ({d})\n", .{paths.len}) catch {};
            for (paths) |path| streams.out.print("conflict {s}\n", .{path}) catch {};
        },
    }
    return .ok;
}

pub fn probeMergeability(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    target_rid: u64,
    branch_rid: u64,
) !Probe {
    const m = try mergeOnStore(gpa, arena, repo, target_rid, branch_rid);
    return .{ .verdict = m.verdict, .both_modified = m.both_modified };
}

/// A path's content in a merged tree: a blob the store holds, or bytes the
/// merge produced in memory. A cleanly merged file has no name in the store
/// until someone commits it.
pub const TreeContent = union(enum) { hash: []const u8, bytes: []const u8 };

/// One path of a merged tree.
pub const TreeEntry = struct { content: TreeContent, mode: artifact.FileMode };

/// A merged tree by path. Arena-owned.
pub const TreeMap = std.StringHashMapUnmanaged(TreeEntry);

/// A merge computed from the store.
pub const StoreMerge = struct {
    verdict: Mergeability,
    /// The tree the merge produces: TARGET's own when up to date, the merge
    /// when clean. Meaningless otherwise.
    tree: TreeMap,
    /// The paths both sides changed, sorted. Not a diagnostic: it is the cone
    /// a bare accept needs (sparse-cone Section 4.4 resolves every other
    /// path at the record).
    both_modified: []const []const u8,
    /// The merge base, when there is one: null when up to date or unrelated.
    base: ?u64 = null,
    /// What each conflicting path is, in the order of `verdict.conflicts`.
    /// Empty unless the verdict is `conflicts`.
    conflict_files: []const ConflictFile = &.{},
};

/// Why a path did not merge.
pub const ConflictKind = enum {
    /// Both changed it and the line merge left at least one conflict region.
    text,
    binary,
    add_add,
    /// Current deleted it; other changed it.
    delete_modify,
    /// Current changed it; other deleted it.
    modify_delete,
    /// The store names a blob it cannot produce (a sparse store's elided
    /// content): no one can say whether it merges.
    unreadable,
};

/// One conflicting path as the merge saw it: each side's content and mode,
/// null where the path is absent, and for `text` the regions of the very
/// line merge that found the conflict. Arena-owned.
pub const ConflictFile = struct {
    path: []const u8,
    kind: ConflictKind,
    base: ?TreeContent,
    current: ?TreeContent,
    other: ?TreeContent,
    base_mode: ?artifact.FileMode,
    current_mode: ?artifact.FileMode,
    other_mode: ?artifact.FileMode,
    /// The mode a resolution of this path takes, by `mergedMode`.
    mode: ?artifact.FileMode,
    regions: []const merge3.Region = &.{},
};

/// Merge `branch` into `target` from the store alone: no working tree, no
/// cone, nothing written. The one engine behind `merge --probe`, the chained
/// probe, `landing`'s mergeability and `merge-tree`, so none of them can
/// disagree about whether a pair merges or what it merges to.
///
/// Content per path is `merge3.classifyFile`, the classifier the working-tree
/// merge runs; the mode follows `mergedMode`, the rule it applies. NOT the
/// hash-level resolution the sparse out-of-cone path uses, which refuses any
/// file touched on both sides and would report conflicts on exactly the
/// long-lived branches that merged their target back in.
pub fn mergeOnStore(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    target_rid: u64,
    branch_rid: u64,
) !StoreMerge {
    const landed = [_]u64{target_rid};
    const ours = try treeOf(gpa, arena, repo, target_rid);
    return mergeRung(gpa, arena, repo, &landed, ours, branch_rid);
}

/// A check-in's file set as a tree of stored blobs.
fn treeOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, repo: *Repository, rid: u64) !TreeMap {
    var sides: SideMap = .empty;
    try sideMapOf(gpa, arena, repo, rid, &sides);
    var tree: TreeMap = .empty;
    var it = sides.iterator();
    while (it.next()) |e| try tree.put(arena, e.key_ptr.*, .{ .content = .{ .hash = e.value_ptr.hash }, .mode = e.value_ptr.mode });
    return tree;
}

/// Merge `rung` onto `ours`, the tree of everything in `landed`.
fn mergeRung(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    landed: []const u64,
    ours: TreeMap,
    rung: u64,
) !StoreMerge {
    if (try chainHolds(gpa, repo, landed, rung))
        return .{ .verdict = .up_to_date, .tree = ours, .both_modified = &.{} };
    const base_rid = (try chainBase(gpa, repo, landed, rung)) orelse
        return .{ .verdict = .unrelated, .tree = .empty, .both_modified = &.{} };
    var base: SideMap = .empty;
    var theirs: SideMap = .empty;
    try sideMapOf(gpa, arena, repo, base_rid, &base);
    try sideMapOf(gpa, arena, repo, rung, &theirs);

    var acc: MergeAcc = .{};
    // Every path either side knows. A path in `base` alone is deleted on
    // both sides, which is agreement, not a conflict.
    var ours_it = ours.iterator();
    while (ours_it.next()) |e| try mergePath(arena, repo, e.key_ptr.*, &base, &ours, &theirs, &acc);
    var theirs_it = theirs.iterator();
    while (theirs_it.next()) |e| try mergePath(arena, repo, e.key_ptr.*, &base, &ours, &theirs, &acc);

    // Sorted so two readers of the same store see the same list in the same
    // order: a forge rendering them must not shuffle between refreshes.
    std.mem.sort([]const u8, acc.both.items, {}, pathLess);
    if (acc.conflicts.items.len != 0) {
        std.mem.sort(ConflictFile, acc.conflicts.items, {}, struct {
            fn lt(_: void, a: ConflictFile, b: ConflictFile) bool {
                return pathLess({}, a.path, b.path);
            }
        }.lt);
        const paths = try arena.alloc([]const u8, acc.conflicts.items.len);
        for (acc.conflicts.items, paths) |cf, *p| p.* = cf.path;
        return .{
            .verdict = .{ .conflicts = paths },
            .tree = .empty,
            .both_modified = acc.both.items,
            .base = base_rid,
            .conflict_files = acc.conflicts.items,
        };
    }
    return .{ .verdict = .clean, .tree = acc.next, .both_modified = acc.both.items, .base = base_rid };
}

fn pathLess(_: void, a: []const u8, b: []const u8) bool {
    return std.mem.order(u8, a, b) == .lt;
}

/// One rung's answer in a chained probe. `not_reached` follows the rung that
/// stopped: a merge that did not complete leaves no tree to continue from.
pub const ChainVerdict = union(enum) {
    up_to_date,
    unrelated,
    clean,
    conflicts: []const []const u8,
    not_reached,
};

/// Would each of `rungs` land, in order, on `target` with the ones before it
/// already landed? One verdict per rung, arena-owned, in rung order. `zit merge --probe --into TARGET NAME NAME...`. Store-only;
/// writes nothing.
///
/// Each clean rung's merged tree becomes the next rung's "ours", in memory.
/// The base is widened the same way: once rung 1 has landed, TARGET's tip has
/// it as an ancestor, so rung 2's base is the nearest common ancestor with ANY
/// landed check-in, not with TARGET alone. Merging the landed tree against
/// TARGET's old fork point instead would see rung 1's edits on the landed side
/// and rung 2's rewrite of them on the other, and report a stacked rung as
/// conflicting with the very rung beneath it.
///
/// The first rung is exactly `probeMergeability`'s question and answers it
/// the same way.
pub fn probeChain(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    target_rid: u64,
    rungs: []const u64,
) ![]ChainVerdict {
    const out = try arena.alloc(ChainVerdict, rungs.len);
    var landed: std.ArrayList(u64) = .empty;
    try landed.append(arena, target_rid);
    var ours = try treeOf(gpa, arena, repo, target_rid);

    var stopped = false;
    for (rungs, out) |rung, *verdict| {
        if (stopped) {
            verdict.* = .not_reached;
            continue;
        }
        const m = try mergeRung(gpa, arena, repo, landed.items, ours, rung);
        switch (m.verdict) {
            .up_to_date => verdict.* = .up_to_date,
            .unrelated => {
                verdict.* = .unrelated;
                stopped = true;
            },
            .conflicts => |paths| {
                verdict.* = .{ .conflicts = paths };
                stopped = true;
            },
            .clean => {
                verdict.* = .clean;
                ours = m.tree;
                try landed.append(arena, rung);
            },
        }
    }
    return out;
}

/// Whether `rung` is already in the landed tree: equal to, or an ancestor of,
/// something landed.
fn chainHolds(gpa: std.mem.Allocator, repo: *Repository, landed: []const u64, rung: u64) !bool {
    for (landed) |l| {
        if (l == rung) return true;
        if (try repo.isAncestorOf(gpa, rung, l)) return true;
    }
    return false;
}

/// The merge base of `rung` against the landed tree: the most recent of its
/// merge bases with each landed check-in. A candidate replaces the held one
/// only when it descends from it, so incomparable candidates (a criss-cross)
/// keep the first found — deterministic, and the same order the stack names.
fn chainBase(gpa: std.mem.Allocator, repo: *Repository, landed: []const u64, rung: u64) !?u64 {
    var best: ?u64 = null;
    for (landed) |l| {
        const c = (try repo.mergeBaseOf(gpa, l, rung)) orelse continue;
        if (best) |b| {
            if (b != c and try repo.isAncestorOf(gpa, b, c)) best = c;
        } else best = c;
    }
    return best;
}

/// What a rung's merge accumulates, path by path.
const MergeAcc = struct {
    next: TreeMap = .empty,
    conflicts: std.ArrayList(ConflictFile) = .empty,
    both: std.ArrayList([]const u8) = .empty,
    seen: std.StringHashMapUnmanaged(void) = .empty,
};

/// Merge one path into `acc.next`, or record it in `acc.conflicts`. Hash-level
/// short circuits first, in the order that makes the common cases free; only
/// a path both sides changed reads blobs. The landed side may be bytes rather
/// than a stored blob, so equality is by content whenever either side is in
/// memory.
fn mergePath(
    arena: std.mem.Allocator,
    repo: *Repository,
    path: []const u8,
    base: *const SideMap,
    ours: *const TreeMap,
    theirs: *const SideMap,
    acc: *MergeAcc,
) !void {
    if (acc.seen.contains(path)) return;
    try acc.seen.put(arena, path, {});
    const bs = base.get(path);
    const os = ours.get(path);
    const ts = theirs.get(path);
    const b: ?TreeContent = if (bs) |v| .{ .hash = v.hash } else null;
    const o: ?TreeContent = if (os) |v| v.content else null;
    const t: ?TreeContent = if (ts) |v| .{ .hash = v.hash } else null;
    const b_mode: ?artifact.FileMode = if (bs) |v| v.mode else null;
    const o_mode: ?artifact.FileMode = if (os) |v| v.mode else null;
    const t_mode: ?artifact.FileMode = if (ts) |v| v.mode else null;
    const mode = mergedMode(b_mode, o_mode, t_mode);

    if (try contentEql(arena, repo, o, t)) return put(arena, &acc.next, path, o, mode);
    if (try contentEql(arena, repo, b, o)) return put(arena, &acc.next, path, t, mode);
    if (try contentEql(arena, repo, b, t)) return put(arena, &acc.next, path, o, mode);

    // Both sides moved. An unreadable blob (a sparse store's elided content)
    // is a conflict: "I could not read it" and "it does not merge" are
    // different facts, but both mean a human has to do this one, and claiming
    // clean would be the dangerous direction.
    try acc.both.append(arena, path);
    var cf: ConflictFile = .{
        .path = path,
        .kind = .unreadable,
        .base = b,
        .current = o,
        .other = t,
        .base_mode = b_mode,
        .current_mode = o_mode,
        .other_mode = t_mode,
        .mode = mode,
    };
    const bb = contentBytes(arena, repo, b) catch |e| return unreadable(arena, &acc.conflicts, cf, e);
    const ob = contentBytes(arena, repo, o) catch |e| return unreadable(arena, &acc.conflicts, cf, e);
    const tb = contentBytes(arena, repo, t) catch |e| return unreadable(arena, &acc.conflicts, cf, e);
    switch (try merge3.classifyFile(arena, bb, ob, tb, .conflict)) {
        .unchanged => try put(arena, &acc.next, path, o, mode),
        .take_other => try put(arena, &acc.next, path, t, mode),
        .delete => {},
        .clean_merge => |r| try put(arena, &acc.next, path, .{ .bytes = r.bytes }, mode),
        .text_conflict => |r| {
            cf.kind = .text;
            cf.regions = r.regions;
            try acc.conflicts.append(arena, cf);
        },
        .whole_file_conflict => |why| {
            cf.kind = switch (why) {
                .binary => .binary,
                .add_add => .add_add,
                .delete_modify => .delete_modify,
                .modify_delete => .modify_delete,
            };
            try acc.conflicts.append(arena, cf);
        },
    }
}

fn put(arena: std.mem.Allocator, next: *TreeMap, path: []const u8, c: ?TreeContent, mode: ?artifact.FileMode) !void {
    const content = c orelse return;
    try next.put(arena, path, .{ .content = content, .mode = mode orelse .regular });
}

fn unreadable(arena: std.mem.Allocator, conflicts: *std.ArrayList(ConflictFile), cf: ConflictFile, e: anyerror) !void {
    if (e == error.OutOfMemory) return error.OutOfMemory;
    std.debug.assert(cf.kind == .unreadable);
    try conflicts.append(arena, cf);
}

/// A side's bytes, or null for an absent path. `error.Unreadable` when the
/// store names a blob it cannot produce.
pub fn contentBytes(arena: std.mem.Allocator, repo: *Repository, c: ?TreeContent) !?[]const u8 {
    const v = c orelse return null;
    return switch (v) {
        .bytes => |b| b,
        .hash => |h| (try repo.blob(arena, h)) orelse error.Unreadable,
    };
}

fn contentEql(arena: std.mem.Allocator, repo: *Repository, a: ?TreeContent, b: ?TreeContent) !bool {
    if (a == null and b == null) return true;
    if (a == null or b == null) return false;
    if (a.? == .hash and b.? == .hash) return std.mem.eql(u8, a.?.hash, b.?.hash);
    // A side held in memory has no name to compare, so compare bytes. A blob
    // that cannot be read equals nothing, which sends the path on to the
    // both-moved case and its unreadable-is-a-conflict rule.
    const ab = contentBytes(arena, repo, a) catch |e| {
        if (e == error.OutOfMemory) return error.OutOfMemory;
        return false;
    };
    const bb = contentBytes(arena, repo, b) catch |e| {
        if (e == error.OutOfMemory) return error.OutOfMemory;
        return false;
    };
    return std.mem.eql(u8, ab.?, bb.?);
}