Skip to content
zit Artifact [d1e3bd3519]
Login

Artifact [d1e3bd3519]

Artifact d1e3bd3519a2e1bc58968d98ce342291b3f8ae6ffff70aa46807bc412729f0f2:


const std = @import("std");
const support = @import("support.zig");
const addManaged = support.addManaged;
const bareStoreOf = support.bareStoreOf;
const checkinHash = support.checkinHash;
const commitFile = support.commitFile;
const commit_epoch = support.commit_epoch;
const expectExit = support.expectExit;
const expectExitDiag = support.expectExitDiag;
const freeResult = support.freeResult;
const initRepo = support.initRepo;
const nCardOf = support.nCardOf;
const readFile = support.readFile;
const runCommitEnv = support.runCommitEnv;
const runZit = support.runZit;
const runZitEnv = support.runZitEnv;
const runZitStdin = support.runZitStdin;
const seedContentMergeable = support.seedContentMergeable;
const tipHashOf = support.tipHashOf;
const writeFile = support.writeFile;

// --- landing ---------------------------------------------------------------
//
// The ceremony that gives a finished branch a reviewable record and a CI
// event. These pin landing's acceptance criteria, and one thing beyond them: that
// nothing here mints an artifact kind fossil does not already understand. That
// last pin is the feature's whole compatibility story, so it is a test rather
// than a comment.

/// Seed a repository with a trunk root and one check-in on `feat/x`, leaving
/// the checkout back on trunk. The shape every landing test starts from.
fn seedLandingRepo(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !void {
    try initRepo(gpa, io, dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, dir, "a.txt", "root\n", "root", &root_c);

    try writeFile(io, dir, "a.txt", "root\nbranch work\n");
    var branch_c = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", "work", "--branch", "feat/x" });
    defer freeResult(gpa, &branch_c);
    try expectExit(branch_c.term, 0);

    var back = try runZit(gpa, io, dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExit(back.term, 0);
}

test "cli landing: open records a landing, ls lists it, and the branch stays unmerged" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the x work", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, id[0..12]) != null);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "open feat/x -> trunk") != null);

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id[0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "state    open") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "land the x work") != null);

    // Opening a landing proposes; it does not land. Trunk must not have moved.
    var status = try runZit(gpa, io, tmp.dir, &.{"status"});
    defer freeResult(gpa, &status);
    try std.testing.expect(std.mem.indexOf(u8, status.stdout, "nothing to report") != null);

    // One open landing per branch, refused by name rather than silently
    // minting a second permanent record.
    var again = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "again", "--user", "u" });
    defer freeResult(gpa, &again);
    try expectExit(again.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, again.stderr, "already has an open landing") != null);
}

/// How many store entries this run's forum index walked, from
/// `ZIT_LANDING_STATS`.
fn landingWalked(stderr: []const u8) !u64 {
    const tag = "landing-stats: forum index walked ";
    const at = std.mem.indexOf(u8, stderr, tag) orelse return error.NoLandingStats;
    const rest = stderr[at + tag.len ..];
    const end = std.mem.indexOfScalar(u8, rest, ' ') orelse return error.NoLandingStats;
    return std.fmt.parseInt(u64, rest[0..end], 10);
}

test "cli landing: a read walks only what was appended since the last one, and a shun or a rewrite is honoured" {
    // Finding the landing threads used to read every entry in the store on
    // every landing verb, so an accept grew with the store. The forum index
    // keeps their names keyed to the log prefix: a read walks the tail, a
    // rewrite rebuilds it, and a shunned post drops out when it is read.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);
    const stats = [_][2][]const u8{.{ "ZIT_LANDING_STATS", "1" }};

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the x work", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExitDiag(opened.term, 0, opened);
    const id = opened.stdout[0..64];

    // Built by `open`; this read walks only the thread root `open` appended.
    var first = try runZitEnv(gpa, io, tmp.dir, &stats, &.{ "landing", "ls" });
    defer freeResult(gpa, &first);
    try expectExitDiag(first.term, 0, first);
    try std.testing.expectEqual(@as(u64, 1), try landingWalked(first.stderr));
    // Nothing appended since: nothing walked, same answer.
    var warm = try runZitEnv(gpa, io, tmp.dir, &stats, &.{ "landing", "ls" });
    defer freeResult(gpa, &warm);
    try std.testing.expectEqual(@as(u64, 0), try landingWalked(warm.stderr));
    try std.testing.expectEqualStrings(first.stdout, warm.stdout);

    // One reply appended: one entry walked, and the reply is in the thread.
    var said = try runZit(gpa, io, tmp.dir, &.{ "landing", "comment", id[0..12], "-m", "one more thing", "--user", "u" });
    defer freeResult(gpa, &said);
    try expectExitDiag(said.term, 0, said);
    var shown = try runZitEnv(gpa, io, tmp.dir, &stats, &.{ "landing", "show", id[0..12] });
    defer freeResult(gpa, &shown);
    try expectExitDiag(shown.term, 0, shown);
    try std.testing.expectEqual(@as(u64, 1), try landingWalked(shown.stderr));
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "one more thing") != null);

    // A deferred shun masks the root without rewriting the store: the index
    // still names it, and the read drops it.
    var masked = try runZit(gpa, io, tmp.dir, &.{ "shun", "--defer", "--force", id });
    defer freeResult(gpa, &masked);
    try expectExitDiag(masked.term, 0, masked);
    var after_mask = try runZitEnv(gpa, io, tmp.dir, &stats, &.{ "landing", "ls" });
    defer freeResult(gpa, &after_mask);
    try expectExitDiag(after_mask.term, 0, after_mask);
    try std.testing.expect(std.mem.indexOf(u8, after_mask.stdout, id[0..12]) == null);

    // A rewrite replaces the store: the index's key no longer holds, so it is
    // rebuilt by one full walk, and still nothing names the shunned landing.
    var rewritten = try runZit(gpa, io, tmp.dir, &.{ "shun", "--force", id });
    defer freeResult(gpa, &rewritten);
    try expectExitDiag(rewritten.term, 0, rewritten);
    var after_rewrite = try runZitEnv(gpa, io, tmp.dir, &stats, &.{ "landing", "ls" });
    defer freeResult(gpa, &after_rewrite);
    try expectExitDiag(after_rewrite.term, 0, after_rewrite);
    try std.testing.expect(try landingWalked(after_rewrite.stderr) > 1);
    try std.testing.expect(std.mem.indexOf(u8, after_rewrite.stdout, id[0..12]) == null);

    // The rewrite the length check cannot see: the store shrinks by one
    // entry, then grows back by one before any landing read. The new entry
    // sits at a rid the index already covered, so only the prefix key tells
    // the index it was built over a different store.
    try writeFile(io, tmp.dir, "junk.txt", "not a landing\n");
    var junk = try runZitStdin(gpa, io, tmp.dir, "junk.txt", &.{ "forum", "post", "--title", "junk", "--user", "u" });
    defer freeResult(gpa, &junk);
    try expectExitDiag(junk.term, 0, junk);
    var covered = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &covered);
    try expectExitDiag(covered.term, 0, covered);
    var dropped = try runZit(gpa, io, tmp.dir, &.{ "shun", "--force", std.mem.trimEnd(u8, junk.stdout, "\n") });
    defer freeResult(gpa, &dropped);
    try expectExitDiag(dropped.term, 0, dropped);
    try writeFile(io, tmp.dir, "root.txt", "zit-landing: 1\nbranch: feat/x\ntarget: trunk\n\nposted directly\n");
    var direct = try runZitStdin(gpa, io, tmp.dir, "root.txt", &.{ "forum", "post", "--title", "land x again", "--user", "u" });
    defer freeResult(gpa, &direct);
    try expectExitDiag(direct.term, 0, direct);
    var found = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &found);
    try expectExitDiag(found.term, 0, found);
    try std.testing.expect(std.mem.indexOf(u8, found.stdout, direct.stdout[0..12]) != null);
}

test "cli landing: accept merges the branch, settles the record, and tags the check-in" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    var accepted = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", id[0..12], "--user", "u" });
    defer freeResult(gpa, &accepted);
    try expectExit(accepted.term, 0);
    // The interface hides the encoding: one landing-shaped line, never the
    // merge/check-in/tag lines of the verbs it composes.
    try std.testing.expect(std.mem.indexOf(u8, accepted.stdout, "accepted ") != null);
    try std.testing.expect(std.mem.indexOf(u8, accepted.stdout, "check-in ") == null);
    try std.testing.expect(std.mem.indexOf(u8, accepted.stdout, "tag ") == null);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqualStrings("", listed.stdout); // no longer open

    var all = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &all);
    try std.testing.expect(std.mem.indexOf(u8, all.stdout, "accepted feat/x -> trunk") != null);

    // The durable, check-in-oriented fact: a raw tag naming the landing.
    var tags = try runZit(gpa, io, tmp.dir, &.{ "tag", "list", "--raw", "trunk" });
    defer freeResult(gpa, &tags);
    try std.testing.expect(std.mem.indexOf(u8, tags.stdout, "landing ") != null);
    try std.testing.expect(std.mem.indexOf(u8, tags.stdout, id) != null);

    // A settled landing takes no second verdict.
    var twice = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", id[0..12], "--user", "u" });
    defer freeResult(gpa, &twice);
    try expectExit(twice.term, 1);

    var verified = try runZit(gpa, io, tmp.dir, &.{"verify"});
    defer freeResult(gpa, &verified);
    try expectExit(verified.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, verified.stdout, "0 faults") != null);
}

test "cli landing: reject settles the record and leaves the target untouched" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var before = try runZit(gpa, io, tmp.dir, &.{ "info", "trunk" });
    defer freeResult(gpa, &before);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "maybe", "--user", "u" });
    defer freeResult(gpa, &opened);
    const id = opened.stdout[0..64];

    var rejected = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", id[0..12], "-m", "not yet", "--user", "u" });
    defer freeResult(gpa, &rejected);
    try expectExit(rejected.term, 0);

    var all = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &all);
    try std.testing.expect(std.mem.indexOf(u8, all.stdout, "rejected feat/x -> trunk") != null);

    var after = try runZit(gpa, io, tmp.dir, &.{ "info", "trunk" });
    defer freeResult(gpa, &after);
    try std.testing.expectEqualStrings(before.stdout, after.stdout);
}

test "cli landing: the record tracks the branch, not a frozen range" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "in progress", "--user", "u" });
    defer freeResult(gpa, &opened);
    const id = opened.stdout[0..64];

    // Work continues after the landing opens — the workflow this serves keeps
    // committing to the branch, so a snapshot would be wrong by now.
    var to_branch = try runZit(gpa, io, tmp.dir, &.{ "update", "feat/x" });
    defer freeResult(gpa, &to_branch);
    try expectExit(to_branch.term, 0);
    try writeFile(io, tmp.dir, "a.txt", "root\nbranch work\nmore work\n");
    var more = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "more" });
    defer freeResult(gpa, &more);
    try expectExit(more.term, 0);

    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExit(back.term, 0);

    // Still one open landing on the same branch, unchanged by the new commit.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "open feat/x -> trunk") != null);

    // And accepting it lands the LATER work, which is the whole point.
    var accepted = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", id[0..12], "--user", "u" });
    defer freeResult(gpa, &accepted);
    try expectExit(accepted.term, 0);
    var cat = try runZit(gpa, io, tmp.dir, &.{ "cat", "a.txt" });
    defer freeResult(gpa, &cat);
    try std.testing.expect(std.mem.indexOf(u8, cat.stdout, "more work") != null);
}

test "cli landing: a landing record is an ordinary forum artifact (compatibility pin)" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "ordinary", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    // Landing's invariant: a stock fossil clone must meet only artifacts it
    // already understands. The record is a forum post — H card, W body, no
    // card fossil does not know. If this ever fails because a new card was
    // minted, the design went wrong, not the test.
    var raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", id });
    defer freeResult(gpa, &raw);
    try expectExit(raw.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\nH ") != null);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "zit-landing: 1") != null);
    // No K card (that would be a ticket), no T-card run in the record itself.
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\nK ") == null);
}

test "cli landing: --reply-to aims the I-card at a post while G stays the thread root" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "a proposal", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const root = try gpa.dupe(u8, opened.stdout[0..64]);
    defer gpa.free(root);

    var g_buf: [80]u8 = undefined;
    const g_root = try std.fmt.bufPrint(&g_buf, "G {s}\n", .{root});

    // A plain comment replies to the record opener: G and I both name the root.
    var a = try runZit(gpa, io, tmp.dir, &.{ "landing", "comment", root, "-m", "first remark", "--user", "u" });
    defer freeResult(gpa, &a);
    try expectExit(a.term, 0);
    const a_id = try gpa.dupe(u8, a.stdout[0..64]);
    defer gpa.free(a_id);

    var a_raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", a_id });
    defer freeResult(gpa, &a_raw);
    var ir_buf: [80]u8 = undefined;
    const i_root = try std.fmt.bufPrint(&ir_buf, "I {s}\n", .{root});
    try std.testing.expect(std.mem.indexOf(u8, a_raw.stdout, g_root) != null);
    try std.testing.expect(std.mem.indexOf(u8, a_raw.stdout, i_root) != null);

    // --reply-to A aims the I-card at A while G still names the thread root,
    // so a reader can tell an answer from a new point.
    var b = try runZit(gpa, io, tmp.dir, &.{ "landing", "comment", root, "-m", "answering A", "--reply-to", a_id, "--user", "u" });
    defer freeResult(gpa, &b);
    try expectExit(b.term, 0);

    var b_raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", b.stdout[0..64] });
    defer freeResult(gpa, &b_raw);
    var ia_buf: [80]u8 = undefined;
    const i_a = try std.fmt.bufPrint(&ia_buf, "I {s}\n", .{a_id});
    try std.testing.expect(std.mem.indexOf(u8, b_raw.stdout, i_a) != null);
    try std.testing.expect(std.mem.indexOf(u8, b_raw.stdout, g_root) != null);
}

test "cli landing: --reply-to refuses a post outside the landing's own thread" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    // A second branch carries a second, independent landing thread.
    try writeFile(io, tmp.dir, "a.txt", "root\nother work\n");
    var oc = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "other", "--branch", "feat/y" });
    defer freeResult(gpa, &oc);
    try expectExit(oc.term, 0);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExit(back.term, 0);

    var l1 = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "one", "--user", "u" });
    defer freeResult(gpa, &l1);
    try expectExit(l1.term, 0);
    const one = try gpa.dupe(u8, l1.stdout[0..64]);
    defer gpa.free(one);

    var l2 = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/y", "-m", "two", "--user", "u" });
    defer freeResult(gpa, &l2);
    try expectExit(l2.term, 0);
    const two = try gpa.dupe(u8, l2.stdout[0..64]);
    defer gpa.free(two);

    // Aiming landing one's comment at landing two's root is refused: the
    // capability check keeps a reply inside its own thread.
    var bad = try runZit(gpa, io, tmp.dir, &.{ "landing", "comment", one, "-m", "cross-thread", "--reply-to", two, "--user", "u" });
    defer freeResult(gpa, &bad);
    try expectExit(bad.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, bad.stderr, "thread") != null);
}

// --- landing title/prose split ---------------------------------------------

/// A stack `depth` segments tall on one shared file, each segment editing a
/// different line of it so the merges have every chance to collide. Returns the
/// landing ids, bottom first. The checkout is left on trunk.
///
/// One file on purpose: a stack whose segments touch disjoint files proves
/// nothing about merging, and the whole claim under test is that a
/// segment still merges cleanly once the one below it has landed.
fn seedStack(
    gpa: std.mem.Allocator,
    io: std.Io,
    dir: std.Io.Dir,
    comptime depth: usize,
    ids: *[depth][]u8,
) !void {
    try initRepo(gpa, io, dir);
    var lines: std.ArrayList(u8) = .empty;
    defer lines.deinit(gpa);
    for (0..depth * 2 + 1) |i| try lines.print(gpa, "line{d}\n", .{i});
    try writeFile(io, dir, "shared.txt", lines.items);
    try addManaged(gpa, io, dir, &.{"shared.txt"});
    var root_c = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", "base" });
    defer freeResult(gpa, &root_c);
    try expectExit(root_c.term, 0);

    // Each segment rewrites one line and commits onto its own branch, which
    // therefore descends from the segment before it.
    for (0..depth) |n| {
        var body: std.ArrayList(u8) = .empty;
        defer body.deinit(gpa);
        for (0..depth * 2 + 1) |i| {
            if (i == n * 2 + 1) {
                try body.print(gpa, "SEG{d}\n", .{n + 1});
            } else {
                try body.print(gpa, "line{d}\n", .{i});
            }
        }
        // Keep the edits from earlier segments: read back and patch one line.
        const cur = try readFile(gpa, io, dir, "shared.txt");
        defer gpa.free(cur);
        var patched: std.ArrayList(u8) = .empty;
        defer patched.deinit(gpa);
        var it = std.mem.splitScalar(u8, cur, '\n');
        var idx: usize = 0;
        while (it.next()) |line| {
            if (line.len == 0 and it.rest().len == 0) break;
            if (idx == n * 2 + 1) {
                try patched.print(gpa, "SEG{d}\n", .{n + 1});
            } else {
                try patched.print(gpa, "{s}\n", .{line});
            }
            idx += 1;
        }
        try writeFile(io, dir, "shared.txt", patched.items);

        var name_buf: [16]u8 = undefined;
        const branch = try std.fmt.bufPrint(&name_buf, "seg{d}", .{n + 1});
        var c = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", branch, "--branch", branch });
        defer freeResult(gpa, &c);
        try expectExit(c.term, 0);
    }

    var back = try runZit(gpa, io, dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExit(back.term, 0);

    // Bottom targets trunk; every other segment targets the one below it.
    for (0..depth) |n| {
        var b_buf: [16]u8 = undefined;
        var t_buf: [16]u8 = undefined;
        const branch = try std.fmt.bufPrint(&b_buf, "seg{d}", .{n + 1});
        const target = if (n == 0)
            "trunk"
        else
            try std.fmt.bufPrint(&t_buf, "seg{d}", .{n});
        var o = try runZit(gpa, io, dir, &.{ "landing", "open", "--branch", branch, "--to", target, "-m", branch, "--user", "u" });
        defer freeResult(gpa, &o);
        try expectExit(o.term, 0);
        ids[n] = try gpa.dupe(u8, o.stdout[0..64]);
    }
}

test "cli landing: a six-deep stack lands bottom-up, retargeting as it goes" {
    // The claim this whole feature rests on: a segment still merges cleanly
    // once the one below it has landed, at any depth and on a shared file, with
    // no rebase anywhere. Six deep because three proved nothing about depth.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 6;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    for (0..depth) |n| {
        var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[n][0..12], "--user", "u" });
        defer freeResult(gpa, &acc);
        try expectExit(acc.term, 0);
        // Every accept but the last unblocks the next segment by moving it onto
        // trunk. That is the whole of the restack.
        if (n + 1 < depth) {
            try std.testing.expect(std.mem.indexOf(u8, acc.stdout, "retargeted 1 stacked landing(s) onto 'trunk'") != null);
        }
    }

    // Every segment's edit is on trunk, and none overwrote another.
    const final = try readFile(gpa, io, tmp.dir, "shared.txt");
    defer gpa.free(final);
    for (0..depth) |n| {
        var want: [8]u8 = undefined;
        const tag = try std.fmt.bufPrint(&want, "SEG{d}", .{n + 1});
        try std.testing.expect(std.mem.indexOf(u8, final, tag) != null);
    }

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, listed.stdout, " open "));

    // Each landed segment closed its own branch, so the stack leaves exactly
    // one open leaf behind: trunk. Before this, a six-deep stack left seven,
    // and `leaves` is how an operator finds work that still needs doing.
    var leaves = try runZit(gpa, io, tmp.dir, &.{"leaves"});
    defer freeResult(gpa, &leaves);
    try expectExit(leaves.term, 0);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, leaves.stdout, "\n"));
}

test "cli landing: accept refuses a segment whose base has not landed" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 3;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // The middle segment: its base is open, so landing it would silently widen
    // its own diff to include work nobody reviewed under it.
    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, "which has its own open landing") != null);
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, ids[0][0..12]) != null);

    // Refused means refused: nothing merged, every landing still open.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqual(@as(usize, depth), std.mem.count(u8, listed.stdout, " open "));
}

test "cli landing: a stacked landing reviews only its own check-ins" {
    // The reviewer-facing half. A segment's diff is computed against the branch
    // below it, so the work under review is the segment's own -- which is what
    // makes small stacked landings worth proposing at all.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 4;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    for (1..depth) |n| {
        var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", ids[n][0..12] });
        defer freeResult(gpa, &shown);
        try expectExit(shown.term, 0);
        try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, shown.stdout, "\ncheckin "));
        // And it names what it sits on.
        try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "\non       ") != null);
    }
}

test "cli landing: retarget moves a landing, and refuses the cases that mean nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rt = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "trunk", "--user", "u" });
    defer freeResult(gpa, &rt);
    try expectExit(rt.term, 0);

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", ids[1][0..12] });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "seg2 -> trunk") != null);

    // A no-op retarget is refused rather than written: a permanent record does
    // not need a reply that changes nothing.
    var again = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "trunk", "--user", "u" });
    defer freeResult(gpa, &again);
    try expectExit(again.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, again.stderr, "already lands on") != null);

    // And a landing cannot land on itself.
    var self = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "seg2", "--user", "u" });
    defer freeResult(gpa, &self);
    try expectExit(self.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, self.stderr, "cannot land on itself") != null);
}

test "cli landing: a rejected base is flagged on what was stacked over it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rej = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", ids[0][0..12], "-m", "not this way", "--user", "u" });
    defer freeResult(gpa, &rej);
    try expectExit(rej.term, 0);

    // seg2 still merges cleanly into seg1 -- true, and useless, because nobody
    // is going to land seg1. The record says so rather than leaving the
    // mergeability line to imply everything is fine.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", ids[1][0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "WARNING") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "was rejected") != null);
}

test "cli landing: a retargeted landing is still an ordinary forum thread" {
    // The compatibility pin, matching the landing one: a stock fossil clone must
    // read every part of a stack, including the retarget replies. If this ever
    // needs a new card, the design was wrong.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rt = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "trunk", "--user", "u" });
    defer freeResult(gpa, &rt);
    try expectExit(rt.term, 0);
    const reply = rt.stdout[rt.stdout.len - 65 ..][0..64];

    var art = try runZit(gpa, io, tmp.dir, &.{ "artifact", reply });
    defer freeResult(gpa, &art);
    try expectExit(art.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, art.stdout, "forum") != null);
}

test "cli landing: a forge lands a stack against a bare store" {
    // The forge path. `accept -R` merges in a working area it creates and
    // removes, and a stack must land through it exactly as it does from
    // a checkout -- including the retarget that unblocks the next segment.
    // Tested separately because it is a different accept implementation, not a
    // different flag on the same one.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 3;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    for (0..depth) |n| {
        var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[n][0..12], "--user", "u", "-R", ".zit" });
        defer freeResult(gpa, &acc);
        try expectExit(acc.term, 0);
        if (n + 1 < depth) {
            try std.testing.expect(std.mem.indexOf(u8, acc.stdout, "retargeted 1 stacked landing(s) onto 'trunk'") != null);
        }
    }

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all", "-R", ".zit" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, listed.stdout, " open "));
    try std.testing.expectEqual(@as(usize, depth), std.mem.count(u8, listed.stdout, " accepted "));
}

test "cli landing: the ordering guard holds against a bare store too" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // Refused BEFORE the ephemeral checkout is built, so a forge never pays for
    // a merge it was always going to decline.
    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u", "-R", ".zit" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, "which has its own open landing") != null);
}

test "cli landing: an accepted branch closes; a rejected one stays open" {
    // A landed branch is finished, and saying so is what keeps `leaves` a list
    // of work in progress. A REJECTED branch is not finished — the author may
    // revise and propose it again — so closing that one would be the tooling
    // making their decision for them.
    const gpa = std.testing.allocator;
    const io = std.testing.io;

    {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try seedLandingRepo(gpa, io, tmp.dir);
        var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "u" });
        defer freeResult(gpa, &opened);
        try expectExit(opened.term, 0);
        var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", opened.stdout[0..12], "--user", "u" });
        defer freeResult(gpa, &acc);
        try expectExit(acc.term, 0);

        var branches = try runZit(gpa, io, tmp.dir, &.{"branch"});
        defer freeResult(gpa, &branches);
        try expectExit(branches.term, 0);
        try std.testing.expect(std.mem.indexOf(u8, branches.stdout, "closed") != null);
    }
    {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try seedLandingRepo(gpa, io, tmp.dir);
        var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "maybe", "--user", "u" });
        defer freeResult(gpa, &opened);
        try expectExit(opened.term, 0);
        var rej = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", opened.stdout[0..12], "-m", "no", "--user", "u" });
        defer freeResult(gpa, &rej);
        try expectExit(rej.term, 0);

        var branches = try runZit(gpa, io, tmp.dir, &.{"branch"});
        defer freeResult(gpa, &branches);
        try expectExit(branches.term, 0);
        try std.testing.expect(std.mem.indexOf(u8, branches.stdout, "closed") == null);
    }
}

test "cli landing: closing a landed segment does not close the ones above it" {
    // The regression this pins was live for about ten minutes: closing the
    // landed branch with a PROPAGATING `closed` tag marked every segment above
    // it closed too, because in a stack those check-ins are descendants of the
    // landed tip. The effect was invisible in the landing records — which stayed
    // open, correctly — and visible only in `branch` and `leaves`, i.e. exactly
    // where someone looks to find work that still needs doing.
    //
    // Fossil's own propagating close is safe because it closes a check-in with
    // no descendants. A landed stack segment is a leaf by the same-branch rule
    // while still having children on the branch above it, so it is not.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 3;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 0);

    var branches = try runZit(gpa, io, tmp.dir, &.{"branch"});
    defer freeResult(gpa, &branches);
    try expectExit(branches.term, 0);
    // Exactly one branch closed: the one that landed.
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, branches.stdout, "closed"));
    try std.testing.expect(std.mem.indexOf(u8, branches.stdout, "seg2") != null);
    try std.testing.expect(std.mem.indexOf(u8, branches.stdout, "seg3") != null);

    // And the segments above are still landable, which is the fact the closed
    // tag would otherwise have quietly contradicted.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqual(@as(usize, depth - 1), std.mem.count(u8, listed.stdout, " open "));
}

test "cli landing: concurrent accepts of adjacent segments cannot both land" {
    // The guard reads state and then acts, so two processes accepting adjacent
    // segments at once could in principle both pass. They cannot both WIN: the
    // loser either refuses on the guard or fails to merge, and the outcome is a
    // spurious refusal rather than an out-of-order landing. Failing closed is
    // the property worth pinning; which side loses is not.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // Sequential here, in the order that exercises the guard: the store's
    // append lock already serialises the writes, so the interesting question is
    // whether the SECOND accept can slip past a stale read. It cannot, because
    // it re-folds.
    var top = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &top);
    try expectExit(top.term, 1);

    var bottom = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &bottom);
    try expectExit(bottom.term, 0);

    // Exactly one landed, and the other is now unblocked rather than lost.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, listed.stdout, " accepted "));
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, listed.stdout, " open "));
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "seg2 -> trunk") != null);
}

test "cli landing: a rejected base refuses the segment above it" {
    // Before this guard the accept SUCCEEDED and put the work on the rejected
    // branch -- `accepted seg2 -> seg1`, where seg1 is a branch nobody is going
    // to land. Nothing failed, nothing warned, and the work was simply
    // somewhere trunk would never see it. A merge cannot catch this because the
    // merge is fine; only a rule can.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rej = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", ids[0][0..12], "-m", "no", "--user", "u" });
    defer freeResult(gpa, &rej);
    try expectExit(rej.term, 0);

    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, "was rejected") != null);
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, "nobody will land") != null);
    // The remedy is named, and it is the one that works.
    try std.testing.expect(std.mem.indexOf(u8, acc.stderr, "landing retarget") != null);

    // Following it lands the work on trunk.
    var rt = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "trunk", "--user", "u" });
    defer freeResult(gpa, &rt);
    try expectExit(rt.term, 0);
    var acc2 = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &acc2);
    try expectExit(acc2.term, 0);

    // AND THE REJECTED SEGMENT'S CONTENT COMES WITH IT. seg2's branch descends
    // from seg1's, so it literally contains seg1's check-ins; rejecting the
    // landing rejects the PROPOSAL, not the code underneath the segment above
    // it. Anyone who wants seg1's change gone has to revert it, not reject it.
    // Pinned because it is the surprising half of this outcome.
    const final = try readFile(gpa, io, tmp.dir, "shared.txt");
    defer gpa.free(final);
    try std.testing.expect(std.mem.indexOf(u8, final, "SEG1") != null);
    try std.testing.expect(std.mem.indexOf(u8, final, "SEG2") != null);
}

test "cli landing: a landing whose base already landed refuses rather than misfiling" {
    // Reachable when the auto-retarget after an accept did not run -- it is
    // best-effort by design. The child then still points at a branch that has
    // landed, and accepting it would merge into that branch instead of trunk.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 0);

    // Put the child back where a failed auto-retarget would have left it.
    var back = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "seg1", "--user", "u" });
    defer freeResult(gpa, &back);
    try expectExit(back.term, 0);

    var acc2 = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &acc2);
    try expectExit(acc2.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, acc2.stderr, "already landed") != null);
}

test "cli landing: a retarget that would make a cycle is refused" {
    // A cycle is worse than untidy: the ordering guard then refuses every
    // segment in it forever, each waiting on the next, with nothing in the
    // record saying why. It also drove `ls` into an indent computation that
    // panicked outright.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 3;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // Direct: the bottom onto the one directly above it.
    var direct = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[0][0..12], "--to", "seg2", "--user", "u" });
    defer freeResult(gpa, &direct);
    try expectExit(direct.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, direct.stderr, "cycle") != null);

    // Indirect: the bottom onto the top, two hops away.
    var indirect = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[0][0..12], "--to", "seg3", "--user", "u" });
    defer freeResult(gpa, &indirect);
    try expectExit(indirect.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, indirect.stderr, "cycle") != null);

    // And the stack still lists, which is the symptom the panic took out.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expectEqual(@as(usize, depth), std.mem.count(u8, listed.stdout, " open "));
}

test "cli landing: retarget checks the branch it names exists" {
    // `open` refuses a target that does not resolve, because minting a record
    // aimed at nothing is a footprint nobody can retract. `retarget` mints the
    // same kind of record and was not checking.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rt = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "no-such-branch", "--user", "u" });
    defer freeResult(gpa, &rt);
    try expectExit(rt.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, rt.stderr, "not found") != null);

    // Unchanged: the refusal wrote nothing.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", ids[1][0..12] });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "seg2 -> seg1") != null);
}

test "cli landing: a branch already contained in its target settles instead of failing" {
    // Reachable from a stack: retarget the TOP segment to trunk and land it,
    // and it carries the segment below it in -- so that segment's landing is
    // open over work that is already there. `merge` says "already up to date",
    // which the accept path reported as "did not merge cleanly; resolve and
    // commit". Nothing to resolve, and `reject` was the only way to close the
    // record -- recording the opposite of what happened.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    var rt = try runZit(gpa, io, tmp.dir, &.{ "landing", "retarget", ids[1][0..12], "--to", "trunk", "--user", "u" });
    defer freeResult(gpa, &rt);
    try expectExit(rt.term, 0);
    var top = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[1][0..12], "--user", "u" });
    defer freeResult(gpa, &top);
    try expectExit(top.term, 0);

    // The bottom's work rode in with it.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", ids[0][0..12] });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "up-to-date") != null);

    var bottom = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &bottom);
    try expectExit(bottom.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, bottom.stdout, "already contained") != null);

    // Settled as accepted, which is what actually happened to the work.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, listed.stdout, " accepted "));
    try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, listed.stdout, " open "));
}

/// Merge `branch` into the trunk checkout and commit it, the way a clone
/// lands a branch by hand: no landing verb, no reply on any thread. `epoch`
/// dates the merge; null is the live clock, which is after any landing the
/// test opened, and the suite's pinned epoch is before it.
fn mergeIntoTrunk(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, branch: []const u8, epoch: ?[]const u8) !void {
    var merged = try runZit(gpa, io, dir, &.{ "merge", branch });
    defer freeResult(gpa, &merged);
    try expectExitDiag(merged.term, 0, merged);
    var ci = try runCommitEnv(gpa, io, dir, .{ .user = "u", .epoch = epoch }, &.{ "commit", "-m", "merge by hand" });
    defer freeResult(gpa, &ci);
    try expectExitDiag(ci.term, 0, ci);
}

/// One more check-in on `branch`, leaving the checkout back on trunk.
fn commitOnBranch(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, branch: []const u8, file: []const u8) !void {
    var away = try runZit(gpa, io, dir, &.{ "update", branch });
    defer freeResult(gpa, &away);
    try expectExitDiag(away.term, 0, away);
    try writeFile(io, dir, file, "more work\n");
    try addManaged(gpa, io, dir, &.{file});
    var ci = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", "more work" });
    defer freeResult(gpa, &ci);
    try expectExitDiag(ci.term, 0, ci);
    var back = try runZit(gpa, io, dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExitDiag(back.term, 0, back);
}

test "cli landing: a merge into the target settles the landing with no reply, and the branch can be proposed again" {
    // The merge is the fact and the reply is the claim: a branch merged into
    // its target from a clone, with nobody posting the accept, has landed.
    // Counting it open forever refused every later proposal of the branch.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var first = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "u" });
    defer freeResult(gpa, &first);
    try expectExitDiag(first.term, 0, first);
    const id = first.stdout[0..64];

    try mergeIntoTrunk(gpa, io, tmp.dir, "feat/x", null);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExitDiag(listed.term, 0, listed);
    try std.testing.expectEqualStrings("", listed.stdout);
    var all = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &all);
    try std.testing.expect(std.mem.indexOf(u8, all.stdout, "accepted feat/x -> trunk") != null);
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id[0..12] });
    defer freeResult(gpa, &shown);
    try expectExitDiag(shown.term, 0, shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "state    accepted") != null);

    // The branch grows past its merge, and the new work is proposed.
    try commitOnBranch(gpa, io, tmp.dir, "feat/x", "b.txt");
    var second = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the rest", "--user", "u" });
    defer freeResult(gpa, &second);
    try expectExitDiag(second.term, 0, second);

    // The old merge predates the new landing, so it does not settle it.
    var after = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &after);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, after.stdout, " accepted "));
    try std.testing.expect(std.mem.indexOf(u8, after.stdout, second.stdout[0..12]) != null);
    try std.testing.expect(std.mem.indexOf(u8, after.stdout, "open feat/x -> trunk") != null);
}

test "cli landing: a merge made before the landing opened does not settle it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    try mergeIntoTrunk(gpa, io, tmp.dir, "feat/x", commit_epoch);
    try commitOnBranch(gpa, io, tmp.dir, "feat/x", "b.txt");

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the rest", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExitDiag(opened.term, 0, opened);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "open feat/x -> trunk") != null);
    var again = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "again", "--user", "u" });
    defer freeResult(gpa, &again);
    try expectExit(again.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, again.stderr, "already has an open landing") != null);
}

test "cli landing: a merge of a different branch into the target does not settle it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    try writeFile(io, tmp.dir, "y.txt", "other work\n");
    try addManaged(gpa, io, tmp.dir, &.{"y.txt"});
    var y = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "y work", "--branch", "feat/y" });
    defer freeResult(gpa, &y);
    try expectExitDiag(y.term, 0, y);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExitDiag(back.term, 0, back);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land x", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExitDiag(opened.term, 0, opened);

    try mergeIntoTrunk(gpa, io, tmp.dir, "feat/y", null);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "open feat/x -> trunk") != null);
}

test "cli landing: an accepted landing lets the branch be proposed again" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var first = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "u" });
    defer freeResult(gpa, &first);
    try expectExitDiag(first.term, 0, first);
    var accepted = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", first.stdout[0..12], "--user", "u" });
    defer freeResult(gpa, &accepted);
    try expectExitDiag(accepted.term, 0, accepted);

    // `accept` closes the branch's tip; new work reopens it as a leaf.
    try commitOnBranch(gpa, io, tmp.dir, "feat/x", "b.txt");
    var second = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the rest", "--user", "u" });
    defer freeResult(gpa, &second);
    try expectExitDiag(second.term, 0, second);

    var all = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls", "--all" });
    defer freeResult(gpa, &all);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all.stdout, " accepted "));
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all.stdout, " open "));
}

test "cli landing: two segments on one base both retarget when it lands" {
    // A stack is a chain per segment, not per repository: two landings may sit
    // on the same base. Both must move when it lands, or whichever was missed
    // is left pointing at a branch that already landed.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "f.txt", "base\n", "base", &root_c);

    try writeFile(io, tmp.dir, "a.txt", "a\n");
    try addManaged(gpa, io, tmp.dir, &.{"a.txt"});
    var ca = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "A", "--branch", "segA" });
    defer freeResult(gpa, &ca);
    try expectExit(ca.term, 0);

    try writeFile(io, tmp.dir, "b.txt", "b\n");
    try addManaged(gpa, io, tmp.dir, &.{"b.txt"});
    var cb = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "B", "--branch", "segB" });
    defer freeResult(gpa, &cb);
    try expectExit(cb.term, 0);

    var back_a = try runZit(gpa, io, tmp.dir, &.{ "update", "segA" });
    defer freeResult(gpa, &back_a);
    try expectExit(back_a.term, 0);
    try writeFile(io, tmp.dir, "c.txt", "c\n");
    try addManaged(gpa, io, tmp.dir, &.{"c.txt"});
    var cc = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "C", "--branch", "segC" });
    defer freeResult(gpa, &cc);
    try expectExit(cc.term, 0);

    var to_trunk = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &to_trunk);
    try expectExit(to_trunk.term, 0);

    var oa = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "segA", "--to", "trunk", "-m", "A", "--user", "u" });
    defer freeResult(gpa, &oa);
    try expectExit(oa.term, 0);
    for ([_][]const u8{ "segB", "segC" }) |b| {
        var o = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", b, "--to", "segA", "-m", b, "--user", "u" });
        defer freeResult(gpa, &o);
        try expectExit(o.term, 0);
    }

    var acc = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", oa.stdout[0..12], "--user", "u" });
    defer freeResult(gpa, &acc);
    try expectExit(acc.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, acc.stdout, "retargeted 2 stacked landing(s)") != null);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, listed.stdout, "-> trunk"));
}

test "cli landing: a multi-line -m puts only its first line in the H card" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    const message =
        \\Adds a demo document.
        \\
        \\This exists to exercise the ceremony end to end.
    ;
    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", message, "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    // An H card is one token (§4.7.7): the title is the first line, and the
    // prose below it appears ONCE, in the body, not a second time as a heading.
    var raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", id });
    defer freeResult(gpa, &raw);
    try expectExit(raw.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\nH Adds\\sa\\sdemo\\sdocument.\n") != null);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "This exists to exercise the ceremony end to end.") != null);
    // The prose is not also in the title, and the title is not also in the body.
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\\nThis\\sexists") == null);
    const body_at = std.mem.indexOf(u8, raw.stdout, "zit-landing: 1").?;
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout[body_at..], "Adds a demo document.") == null);

    // One record is one row.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, listed.stdout, "\n"));
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "Adds a demo document.") != null);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "This exists") == null);

    // show prints the heading, then the prose beneath it.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id[0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    const head_at = std.mem.indexOf(u8, shown.stdout, "Adds a demo document.").?;
    const prose_at = std.mem.indexOf(u8, shown.stdout, "This exists to exercise").?;
    try std.testing.expect(head_at < prose_at);
}

test "cli landing: a one-line -m is a title with no prose" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land the x work", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    // The behaviour a one-line proposal had before the title/prose split, unchanged: the title
    // is the message, and the body is the header block and nothing else.
    var raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", id });
    defer freeResult(gpa, &raw);
    try expectExit(raw.term, 0);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, raw.stdout, "\nH land\\sthe\\sx\\swork\n"));
    // The W body is the header block and nothing else — the title is not
    // repeated there, which is what carrying it once means.
    try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, raw.stdout, "land the x work"));

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id[0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, shown.stdout, "land the x work"));
}

test "cli landing: the split is the first newline, not the first blank line" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    // No blank line anywhere. Splitting on one would mint a two-line heading,
    // which is the whole defect — so the split is at the first newline.
    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "line one\nline two", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..64];

    var raw = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", id });
    defer freeResult(gpa, &raw);
    try expectExit(raw.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\nH line\\sone\n") != null);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "\\nline\\stwo") == null);
    try std.testing.expect(std.mem.indexOf(u8, raw.stdout, "line two") != null);
}

test "cli landing: a message with no title line is refused, not minted titleless" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);

    // An H card's token is 1*tchar: a landing with no first line has no title
    // to mint. Refusing beats writing a permanent artifact nobody can retract.
    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "\n\nbody only", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, opened.stderr, "must open with a title line") != null);

    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExit(listed.term, 0);
    try std.testing.expectEqualStrings("", listed.stdout);
}

test "cli landing: the probe reports a content-mergeable branch clean, not conflicted" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedContentMergeable(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "clean", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", opened.stdout[0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    // Both sides edited f.txt. Hash-level resolution refuses this; a
    // content-level probe must not, or every long-lived branch reads as
    // conflicted and the flag stops meaning anything.
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "merges   clean") != null);

    // And the real merge agrees, which is the property that matters.
    var merged = try runZit(gpa, io, tmp.dir, &.{ "merge", "feat/x" });
    defer freeResult(gpa, &merged);
    try expectExit(merged.term, 0);
}

test "cli landing: the probe names conflicting paths and agrees with the merge engine" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "keep.txt", "keep\n", "root", &root_c);

    // add-vs-add with differing content: an unconditional whole-file conflict.
    try writeFile(io, tmp.dir, "h.txt", "BRANCH\n");
    try addManaged(gpa, io, tmp.dir, &.{"h.txt"});
    var br = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "branch", "--branch", "feat/bad" });
    defer freeResult(gpa, &br);
    try expectExit(br.term, 0);

    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try writeFile(io, tmp.dir, "h.txt", "TRUNK\n");
    try addManaged(gpa, io, tmp.dir, &.{"h.txt"});
    var tr = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "trunk" });
    defer freeResult(gpa, &tr);
    try expectExit(tr.term, 0);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/bad", "-m", "bad", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", opened.stdout[0..12] });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "merges   conflict (1)") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "conflict h.txt") != null);

    // The engine must name the same file. Two conflict detectors that can
    // disagree would be worse than one: the forge would either block a branch
    // that merges or clear one that does not.
    var merged = try runZit(gpa, io, tmp.dir, &.{ "merge", "feat/bad" });
    defer freeResult(gpa, &merged);
    try std.testing.expect(std.mem.indexOf(u8, merged.stderr, "h.txt") != null);
}

test "cli landing: the probe answers against a bare store and writes nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedContentMergeable(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "clean", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);

    var before = try runZit(gpa, io, tmp.dir, &.{"verify"});
    defer freeResult(gpa, &before);
    try expectExit(before.term, 0);

    // A genuinely BARE store -- the store bytes alone, no checkout beside them,
    // which is the shape quarry serves. The bare-store idiom.
    var away = std.testing.tmpDir(.{});
    defer away.cleanup();
    const store_bytes = try tmp.dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(store_bytes);
    try away.dir.createDir(io, "store", .default_dir);
    var store_dir = try away.dir.openDir(io, "store", .{});
    defer store_dir.close(io);
    try writeFile(io, store_dir, ".zit", store_bytes);

    var shown = try runZit(gpa, io, away.dir, &.{ "landing", "show", "-R", "store", opened.stdout[0..12] });
    defer freeResult(gpa, &shown);
    try expectExitDiag(shown.term, 0, shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "merges   clean") != null);

    // Asking must not change the store: a probe that writes is not a probe.
    var after = try runZit(gpa, io, tmp.dir, &.{"verify"});
    defer freeResult(gpa, &after);
    try expectExit(after.term, 0);
    try std.testing.expectEqualStrings(before.stdout, after.stdout);
}

test "cli landing: an already-merged branch reads up-to-date, not clean" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedContentMergeable(gpa, io, tmp.dir);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "clean", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);

    var accepted = try runZit(gpa, io, tmp.dir, &.{ "landing", "accept", opened.stdout[0..12], "--user", "u" });
    defer freeResult(gpa, &accepted);
    try expectExit(accepted.term, 0);

    // After landing, the branch is an ancestor of the target. "up-to-date" and
    // "clean" are different answers and a forge renders them differently.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", opened.stdout[0..12] });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "merges   up-to-date") != null);
}

test "cli landing: accept -R lands a branch with no checkout, and mints what a dense merge would" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    // f.txt is edited on both sides in different regions; k.txt is untouched
    // and must carry forward. Both halves matter to the card comparison.
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "f.txt", "top\nMID\nbottom\n", "root", &root_c);
    try writeFile(io, tmp.dir, "k.txt", "keep\n");
    try addManaged(gpa, io, tmp.dir, &.{"k.txt"});
    var k_c = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "keep" });
    defer freeResult(gpa, &k_c);

    try writeFile(io, tmp.dir, "f.txt", "top\nMID\nBOTTOM-CHANGED\n");
    var br = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "branch", "--branch", "feat/x" });
    defer freeResult(gpa, &br);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try writeFile(io, tmp.dir, "f.txt", "TOP-CHANGED\nMID\nbottom\n");
    var tr = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "trunk" });
    defer freeResult(gpa, &tr);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..12];

    var away = std.testing.tmpDir(.{});
    defer away.cleanup();
    try bareStoreOf(gpa, io, tmp.dir, away.dir, "store");

    var accepted = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u" });
    defer freeResult(gpa, &accepted);
    try expectExitDiag(accepted.term, 0, accepted);
    try std.testing.expect(std.mem.indexOf(u8, accepted.stdout, "accepted ") != null);

    // sparse-cone Section 4.4: out-of-cone changes are applied "to the record
    // (manifest synthesis) without materializing the files". k.txt was never
    // materialized anywhere, yet the record carries it.
    var listed = try runZit(gpa, io, away.dir, &.{ "ls", "-R", "store", "trunk" });
    defer freeResult(gpa, &listed);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "k.txt") != null);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "f.txt") != null);

    // The merged bytes combine BOTH sides -- content-level, not hash-level.
    var content = try runZit(gpa, io, away.dir, &.{ "cat", "f.txt", "trunk", "-R", "store" });
    defer freeResult(gpa, &content);
    try std.testing.expect(std.mem.indexOf(u8, content.stdout, "TOP-CHANGED") != null);
    try std.testing.expect(std.mem.indexOf(u8, content.stdout, "BOTTOM-CHANGED") != null);

    // The ephemeral worktree is gone: a forge that leaks working areas beside
    // its stores accumulates them forever.
    var store_dir = try away.dir.openDir(io, "store", .{});
    defer store_dir.close(io);
    try std.testing.expectError(error.FileNotFound, store_dir.statFile(io, ".zit-landing-" ++ "000000000000", .{}));

    var verified = try runZit(gpa, io, away.dir, &.{ "verify", "-R", "store" });
    defer freeResult(gpa, &verified);
    try expectExit(verified.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, verified.stdout, "0 faults") != null);

    // artifact-format equivalence: the same merge from a dense checkout mints
    // the same F, P and R cards. D and U differ per invocation by definition,
    // so they are excluded -- this is the whole acceptance criterion.
    var dense_merge = try runZit(gpa, io, tmp.dir, &.{ "merge", "feat/x" });
    defer freeResult(gpa, &dense_merge);
    try expectExit(dense_merge.term, 0);
    var dense_commit = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "land it" });
    defer freeResult(gpa, &dense_commit);
    try expectExit(dense_commit.term, 0);

    var bare_art = try runZit(gpa, io, away.dir, &.{ "artifact", "--raw", "trunk", "-R", "store" });
    defer freeResult(gpa, &bare_art);
    var dense_art = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", "trunk" });
    defer freeResult(gpa, &dense_art);
    try expectCardsEqual(gpa, bare_art.stdout, dense_art.stdout);
}

/// Compare two manifests on the cards accept -R pins: F, P and R. D (timestamp) and
/// Z (which covers D) differ per invocation by construction, so a byte
/// comparison of whole manifests could never pass and would be the wrong test.
fn expectCardsEqual(gpa: std.mem.Allocator, a: []const u8, b: []const u8) !void {
    for ([_][]const u8{ "F ", "P ", "R " }) |prefix| {
        const ca = try cardsWithPrefix(gpa, a, prefix);
        defer gpa.free(ca);
        const cb = try cardsWithPrefix(gpa, b, prefix);
        defer gpa.free(cb);
        std.testing.expectEqualStrings(ca, cb) catch |e| {
            std.debug.print("manifest '{s}' cards differ between a bare accept and a dense merge\n", .{prefix});
            return e;
        };
    }
}

fn cardsWithPrefix(gpa: std.mem.Allocator, manifest: []const u8, prefix: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(gpa);
    var it = std.mem.splitScalar(u8, manifest, '\n');
    while (it.next()) |line| {
        if (!std.mem.startsWith(u8, line, prefix)) continue;
        try out.appendSlice(gpa, line);
        try out.append(gpa, '\n');
    }
    return out.toOwnedSlice(gpa);
}

test "cli landing: a conflicting accept -R refuses, writes nothing, and says which paths" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "h.txt", "base\n", "root", &root_c);

    try writeFile(io, tmp.dir, "h.txt", "THEIRS\n");
    var br = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "branch", "--branch", "feat/bad" });
    defer freeResult(gpa, &br);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try writeFile(io, tmp.dir, "h.txt", "OURS\n");
    var tr = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "trunk" });
    defer freeResult(gpa, &tr);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/bad", "-m", "bad", "--user", "u" });
    defer freeResult(gpa, &opened);
    const id = opened.stdout[0..12];

    var away = std.testing.tmpDir(.{});
    defer away.cleanup();
    try bareStoreOf(gpa, io, tmp.dir, away.dir, "store");
    var store_dir = try away.dir.openDir(io, "store", .{});
    defer store_dir.close(io);
    const before = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(before);

    var refused = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u" });
    defer freeResult(gpa, &refused);
    // Exit 5, not 1: "needs a human" is a state a forge renders, not a bug it
    // reports. A caller must be able to tell them apart without reading prose.
    try expectExit(refused.term, 5);
    try std.testing.expect(std.mem.indexOf(u8, refused.stderr, "conflict h.txt") != null);
    try std.testing.expect(std.mem.indexOf(u8, refused.stderr, "nothing was written") != null);

    // The whole point: a server must never hold a half-finished merge, and
    // must never mint a check-in carrying conflict markers. Byte equality is
    // the only assertion that actually proves it.
    const after = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(after);
    try std.testing.expectEqualSlices(u8, before, after);

    // And the record is still open, so the forge shows it as awaiting a human.
    var listed = try runZit(gpa, io, away.dir, &.{ "landing", "ls", "-R", "store" });
    defer freeResult(gpa, &listed);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "open feat/bad -> trunk") != null);
}

test "cli landing: accept --expect-tip refuses a branch that moved after it was checked, and lands the tip it names" {
    // A forge checks a landing (CI, a preflight) against one tip, then accepts.
    // A push in between moves the branch. Without a way to name the checked
    // tip, the accept merged whatever the branch was by then, which nothing
    // had checked.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "f.txt", "a\n", "root", &root_c);

    try writeFile(io, tmp.dir, "f.txt", "checked\n");
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "checked", "--branch", "feat/x" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);
    const checked = try checkinHash(c1.stdout);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "x", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExitDiag(opened.term, 0, opened);
    const id = opened.stdout[0..12];

    // The branch moves after the check.
    try writeFile(io, tmp.dir, "f.txt", "unchecked\n");
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "unchecked" });
    defer freeResult(gpa, &c2);
    try expectExitDiag(c2.term, 0, c2);
    const moved = try checkinHash(c2.stdout);

    var away = std.testing.tmpDir(.{});
    defer away.cleanup();
    try bareStoreOf(gpa, io, tmp.dir, away.dir, "store");
    var store_dir = try away.dir.openDir(io, "store", .{});
    defer store_dir.close(io);
    const before = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(before);

    // Exit 6: its own status, so a caller re-checks rather than reporting an
    // error or rendering a conflict. The message names where the branch is.
    var stale = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u", "--expect-tip", checked });
    defer freeResult(gpa, &stale);
    try expectExit(stale.term, 6);
    const want = try std.fmt.allocPrint(gpa, "branch feat/x is at {s}, not {s}; nothing was written", .{ moved, checked });
    defer gpa.free(want);
    try std.testing.expect(std.mem.indexOf(u8, stale.stderr, want) != null);
    const after = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(after);
    try std.testing.expectEqualSlices(u8, before, after);

    // Naming the tip the branch is actually at lands it.
    var ok = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u", "--expect-tip", moved });
    defer freeResult(gpa, &ok);
    try expectExitDiag(ok.term, 0, ok);
    var probe = try runZit(gpa, io, away.dir, &.{ "merge", "--probe", moved, "--into", "trunk", "-R", "store" });
    defer freeResult(gpa, &probe);
    try std.testing.expectEqualStrings("merges   up-to-date\n", probe.stdout);

    // The flag belongs to accept alone.
    var misuse = try runZit(gpa, io, away.dir, &.{ "landing", "reject", "-R", "store", id, "--expect-tip", moved });
    defer freeResult(gpa, &misuse);
    try expectExit(misuse.term, 2);
}

test "cli landing: accept --expect-target refuses a target that moved after the pair was judged, and lands on the target it names" {
    // A premerge forge judges the pair (branch tip, target tip), then accepts.
    // Another landing lands meanwhile and moves the target. Without a way to
    // name the judged target, the accept merged onto the new one, a pair
    // nothing tested.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    const judged = try commitFile(gpa, io, tmp.dir, "f.txt", "a\n", "root", &root_c);

    try writeFile(io, tmp.dir, "f.txt", "feature\n");
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "feature", "--branch", "feat/x" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "x", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExitDiag(opened.term, 0, opened);
    const id = opened.stdout[0..12];

    // The target moves after the pair was judged.
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);
    try expectExitDiag(back.term, 0, back);
    var c2: std.process.RunResult = undefined;
    defer freeResult(gpa, &c2);
    const moved = try commitFile(gpa, io, tmp.dir, "g.txt", "g\n", "another landing", &c2);

    var away = std.testing.tmpDir(.{});
    defer away.cleanup();
    try bareStoreOf(gpa, io, tmp.dir, away.dir, "store");
    var store_dir = try away.dir.openDir(io, "store", .{});
    defer store_dir.close(io);
    const before = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(before);

    // Exit 7, apart from 6, so a caller re-judges the pair. The message names
    // where the target is now, and nothing is written.
    var stale = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u", "--expect-target", judged });
    defer freeResult(gpa, &stale);
    try expectExit(stale.term, 7);
    const want = try std.fmt.allocPrint(gpa, "target trunk is at {s}, not {s}; nothing was written", .{ moved, judged });
    defer gpa.free(want);
    try std.testing.expect(std.mem.indexOf(u8, stale.stderr, want) != null);
    const after = try store_dir.readFileAlloc(io, ".zit", gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(after);
    try std.testing.expectEqualSlices(u8, before, after);

    // Naming the target as it is lands the landing on it.
    var ok = try runZit(gpa, io, away.dir, &.{ "landing", "accept", "-R", "store", id, "--user", "u", "--expect-target", moved });
    defer freeResult(gpa, &ok);
    try expectExitDiag(ok.term, 0, ok);
    var probe = try runZit(gpa, io, away.dir, &.{ "merge", "--probe", moved, "--into", "trunk", "-R", "store" });
    defer freeResult(gpa, &probe);
    try std.testing.expectEqualStrings("merges   up-to-date\n", probe.stdout);

    // The flag belongs to accept alone.
    var misuse = try runZit(gpa, io, away.dir, &.{ "landing", "reject", "-R", "store", id, "--expect-target", moved });
    defer freeResult(gpa, &misuse);
    try expectExit(misuse.term, 2);
}

// --- landing show: check-ins and thread -------------------------------------

test "cli landing: show lists the branch's check-ins, newest first, and tracks later ones" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "f.txt", "a\n", "root", &root_c);

    try writeFile(io, tmp.dir, "f.txt", "b\n");
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "first branch commit", "--branch", "feat/x" });
    defer freeResult(gpa, &c1);
    try writeFile(io, tmp.dir, "f.txt", "c\n");
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "second branch commit" });
    defer freeResult(gpa, &c2);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "dan" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);
    const id = opened.stdout[0..12];

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id });
    defer freeResult(gpa, &shown);
    try expectExitDiag(shown.term, 0, shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "first branch commit") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "second branch commit") != null);
    // The root is on BOTH sides, so it is not part of what is proposed.
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "  root") == null);
    // Newest first.
    const first = std.mem.indexOf(u8, shown.stdout, "first branch commit").?;
    const second = std.mem.indexOf(u8, shown.stdout, "second branch commit").?;
    try std.testing.expect(second < first);

    // Landing's rule: the record names a branch, so work added after it opened
    // belongs to it. This is the display half of that.
    var to_branch = try runZit(gpa, io, tmp.dir, &.{ "update", "feat/x" });
    defer freeResult(gpa, &to_branch);
    try writeFile(io, tmp.dir, "f.txt", "d\n");
    var c3 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "added after opening" });
    defer freeResult(gpa, &c3);
    var back2 = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back2);

    var again = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id });
    defer freeResult(gpa, &again);
    try std.testing.expect(std.mem.indexOf(u8, again.stdout, "added after opening") != null);
}

test "cli landing: a transition renders as an event, a remark as a comment, and an empty thread as nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "f.txt", "a\n", "root", &root_c);
    try writeFile(io, tmp.dir, "f.txt", "b\n");
    var br = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "work", "--branch", "feat/x" });
    defer freeResult(gpa, &br);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "land it", "--user", "dan" });
    defer freeResult(gpa, &opened);
    const id = opened.stdout[0..12];

    // A record nobody has spoken on prints no thread section at all -- not an
    // empty heading.
    var bare = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id });
    defer freeResult(gpa, &bare);
    try std.testing.expect(std.mem.indexOf(u8, bare.stdout, "this\n") == null);

    var commented = try runZit(gpa, io, tmp.dir, &.{ "landing", "comment", id, "-m", "one nit", "--user", "reviewer" });
    defer freeResult(gpa, &commented);
    try expectExit(commented.term, 0);
    var rejected = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", id, "-m", "needs a rethink", "--user", "dan" });
    defer freeResult(gpa, &rejected);
    try expectExit(rejected.term, 0);

    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id });
    defer freeResult(gpa, &shown);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "reviewer") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "one nit") != null);
    // The transition is an EVENT, not a remark whose body happens to start
    // with a marker: the encoding must not leak into the display.
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "dan  rejected this") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "needs a rethink") != null);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, state_marker_probe) == null);
}

/// The on-the-wire marker, spelled here so the test fails if it ever leaks into
/// rendered output. Deliberately a literal rather than an import: this asserts
/// what a READER sees, and should not move because the writer moved.
const state_marker_probe = "zit-landing-state:";

test "cli landing: the fold's pre-screen only rejects — a card-shaped blob is not mistaken for a record" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    // Content that PASSES the two-byte screen: a file whose first bytes are
    // `<LETTER><SP>`, and one that opens like a signature wrapper. Both reach
    // the full parse, which is what must reject them. The screen may only ever
    // reject; if it ever admitted, this is where that shows up.
    var root_c: std.process.RunResult = undefined;
    defer freeResult(gpa, &root_c);
    _ = try commitFile(gpa, io, tmp.dir, "cardish.txt", "F not/a/card 0123\nW nope\n", "root", &root_c);
    try writeFile(io, tmp.dir, "wrapperish.txt", "-----BEGIN SOMETHING-----\nnot an artifact\n");
    try writeFile(io, tmp.dir, "plain.bin", "\x00\x01\x02 not card shaped\n");
    try addManaged(gpa, io, tmp.dir, &.{ "wrapperish.txt", "plain.bin" });
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "decoys" });
    defer freeResult(gpa, &c2);

    try writeFile(io, tmp.dir, "cardish.txt", "F not/a/card 9999\nW nope\n");
    var br = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "work", "--branch", "feat/x" });
    defer freeResult(gpa, &br);
    var back = try runZit(gpa, io, tmp.dir, &.{ "update", "trunk" });
    defer freeResult(gpa, &back);

    var opened = try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "the only landing", "--user", "u" });
    defer freeResult(gpa, &opened);
    try expectExit(opened.term, 0);

    // Exactly one landing: the real one. A decoy admitted by the screen and
    // then mis-parsed would show up as a second row or a crash.
    var listed = try runZit(gpa, io, tmp.dir, &.{ "landing", "ls" });
    defer freeResult(gpa, &listed);
    try expectExitDiag(listed.term, 0, listed);
    var rows: usize = 0;
    var it = std.mem.splitScalar(u8, listed.stdout, '\n');
    while (it.next()) |line| {
        if (line.len != 0) rows += 1;
    }
    try std.testing.expectEqual(@as(usize, 1), rows);
    try std.testing.expect(std.mem.indexOf(u8, listed.stdout, "the only landing") != null);

    // And the record still reads in full: the screen must not have skipped
    // the landing's own artifact on its way past the decoys.
    var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", opened.stdout[0..12] });
    defer freeResult(gpa, &shown);
    try expectExit(shown.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "branch   feat/x -> trunk") != null);
}

test "cli landing: a landing record carries the same N card a forum post would" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedLandingRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "body.txt", "hello\n");

    // The pin that would have caught the hardcoded mimetype: a landing MINTS a forum artifact,
    // so given the same mimetype the two must agree card for card. They used
    // to disagree -- landing hardcoded `N text/plain` and could not be told
    // otherwise, which overrode §4.7.12's default on every record it wrote.
    for ([_]?[]const u8{ null, "text/x-markdown", "text/x-fossil-wiki" }) |mt| {
        var opened = if (mt) |m|
            try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "msg", "--user", "u", "--mimetype", m })
        else
            try runZit(gpa, io, tmp.dir, &.{ "landing", "open", "--branch", "feat/x", "-m", "msg", "--user", "u" });
        defer freeResult(gpa, &opened);
        try expectExitDiag(opened.term, 0, opened);

        var posted = if (mt) |m|
            try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{ "forum", "post", "--user", "u", "--title", "T", "--mimetype", m })
        else
            try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{ "forum", "post", "--user", "u", "--title", "T" });
        defer freeResult(gpa, &posted);
        try expectExit(posted.term, 0);

        const landing_n = try nCardOf(gpa, io, tmp.dir, opened.stdout[0..64]);
        defer if (landing_n) |n| gpa.free(n);
        const forum_n = try nCardOf(gpa, io, tmp.dir, posted.stdout[0..64]);
        defer if (forum_n) |n| gpa.free(n);

        if (landing_n == null and forum_n == null) {
            // Both omitted: §4.7.12's default applies to both. Settle the
            // landing so the next iteration's branch is free.
            var rejected = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", opened.stdout[0..12], "--user", "u" });
            defer freeResult(gpa, &rejected);
            continue;
        }
        try std.testing.expect(landing_n != null and forum_n != null);
        try std.testing.expectEqualStrings(forum_n.?, landing_n.?);

        var rejected = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", opened.stdout[0..12], "--user", "u" });
        defer freeResult(gpa, &rejected);
    }
}

/// Rewrite one line of `shared.txt` (the seedStack file) and commit
/// on whatever branch the checkout is on.
fn editSharedLine(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, index: usize, text: []const u8, msg: []const u8) !void {
    const cur = try readFile(gpa, io, dir, "shared.txt");
    defer gpa.free(cur);
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(gpa);
    var it = std.mem.splitScalar(u8, cur, '\n');
    var i: usize = 0;
    while (it.next()) |line| : (i += 1) {
        if (line.len == 0 and it.rest().len == 0) break;
        try out.print(gpa, "{s}\n", .{if (i == index) text else line});
    }
    try writeFile(io, dir, "shared.txt", out.items);
    var c = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", msg });
    defer freeResult(gpa, &c);
    try expectExit(c.term, 0);
}

test "cli landing: update brings the target into the branch on the store, records it, and leaves the checkout alone" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    // seg1 -> trunk, seg2 -> seg1; the checkout is left on trunk.
    const depth = 2;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // trunk moves, in a file no segment touches -- a hunk adjacent to a
    // segment's line would be a legitimate conflict, not the clean case.
    try writeFile(io, tmp.dir, "trunk.txt", "trunk moved on\n");
    try addManaged(gpa, io, tmp.dir, &.{"trunk.txt"});
    var mv = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "trunk moves" });
    defer freeResult(gpa, &mv);
    try expectExit(mv.term, 0);
    const trunk_tip = try tipHashOf(gpa, io, tmp.dir, "trunk");
    defer gpa.free(trunk_tip);
    const seg1_before = try tipHashOf(gpa, io, tmp.dir, "seg1");
    defer gpa.free(seg1_before);

    // From the checkout, with no -R: the merge still happens in an ephemeral
    // working area, and this tree is not touched.
    var up = try runZit(gpa, io, tmp.dir, &.{ "landing", "update", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &up);
    try expectExitDiag(up.term, 0, up);
    try std.testing.expect(std.mem.startsWith(u8, up.stdout, "updated "));

    // One merge check-in on seg1: old seg1 tip as the primary parent, trunk's
    // tip as the other.
    const seg1_after = try tipHashOf(gpa, io, tmp.dir, "seg1");
    defer gpa.free(seg1_after);
    try std.testing.expect(!std.mem.eql(u8, seg1_before, seg1_after));
    var art = try runZit(gpa, io, tmp.dir, &.{ "artifact", seg1_after, "--raw" });
    defer freeResult(gpa, &art);
    try expectExit(art.term, 0);
    const p_at = std.mem.indexOf(u8, art.stdout, "\nP ") orelse return error.TestUnexpectedResult;
    const p_end = std.mem.indexOfScalarPos(u8, art.stdout, p_at + 3, '\n') orelse art.stdout.len;
    var parents = std.mem.tokenizeScalar(u8, art.stdout[p_at + 3 .. p_end], ' ');
    try std.testing.expectEqualStrings(seg1_before, parents.next() orelse return error.TestUnexpectedResult);
    try std.testing.expectEqualStrings(trunk_tip, parents.next() orelse return error.TestUnexpectedResult);
    try std.testing.expect(parents.next() == null);

    // The record carries the refresh: the second output line is the reply,
    // whose body opens with the marker and the merge hash.
    const nl = std.mem.indexOfScalar(u8, up.stdout, '\n') orelse return error.TestUnexpectedResult;
    const reply = std.mem.trim(u8, up.stdout[nl + 1 ..], "\n");
    var post = try runZit(gpa, io, tmp.dir, &.{ "artifact", reply, "--raw" });
    defer freeResult(gpa, &post);
    try expectExit(post.term, 0);
    const marker_line = try std.fmt.allocPrint(gpa, "zit-landing-updated: {s}", .{seg1_after});
    defer gpa.free(marker_line);
    try std.testing.expect(std.mem.indexOf(u8, post.stdout, marker_line) != null);

    // The checkout: still on trunk, nothing to report.
    var st = try runZit(gpa, io, tmp.dir, &.{"status"});
    defer freeResult(gpa, &st);
    try std.testing.expect(std.mem.indexOf(u8, st.stdout, "tags:         trunk") != null);
    try std.testing.expect(std.mem.indexOf(u8, st.stdout, "nothing to report") != null);

    // Both probes now read clean: seg1 against trunk's new tip, and the rung
    // stacked on seg1 against seg1's new tip.
    for (ids) |id| {
        var shown = try runZit(gpa, io, tmp.dir, &.{ "landing", "show", id[0..12] });
        defer freeResult(gpa, &shown);
        try expectExit(shown.term, 0);
        try std.testing.expect(std.mem.indexOf(u8, shown.stdout, "merges   clean") != null);
    }

    // Again: nothing to do, nothing written, exit 0.
    var again = try runZit(gpa, io, tmp.dir, &.{ "landing", "update", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &again);
    try expectExitDiag(again.term, 0, again);
    try std.testing.expect(std.mem.indexOf(u8, again.stdout, "already contains") != null);
    const seg1_final = try tipHashOf(gpa, io, tmp.dir, "seg1");
    defer gpa.free(seg1_final);
    try std.testing.expectEqualStrings(seg1_after, seg1_final);
}

test "cli landing: a conflicting update writes nothing and names the path; a settled record is refused" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const depth = 1;
    var ids: [depth][]u8 = undefined;
    try seedStack(gpa, io, tmp.dir, depth, &ids);
    defer for (ids) |id| gpa.free(id);

    // trunk rewrites the very line seg1 rewrote.
    try editSharedLine(gpa, io, tmp.dir, 1, "TRUNK1", "trunk collides");
    const before = try tipHashOf(gpa, io, tmp.dir, "seg1");
    defer gpa.free(before);

    var up = try runZit(gpa, io, tmp.dir, &.{ "landing", "update", ids[0][0..12], "--user", "u", "-R", ".zit" });
    defer freeResult(gpa, &up);
    try expectExit(up.term, 5);
    try std.testing.expect(std.mem.indexOf(u8, up.stderr, "shared.txt") != null);
    try std.testing.expect(std.mem.indexOf(u8, up.stderr, "nothing was written") != null);
    const after = try tipHashOf(gpa, io, tmp.dir, "seg1");
    defer gpa.free(after);
    try std.testing.expectEqualStrings(before, after);

    var rej = try runZit(gpa, io, tmp.dir, &.{ "landing", "reject", ids[0][0..12], "-m", "no", "--user", "u" });
    defer freeResult(gpa, &rej);
    try expectExit(rej.term, 0);
    var settled = try runZit(gpa, io, tmp.dir, &.{ "landing", "update", ids[0][0..12], "--user", "u" });
    defer freeResult(gpa, &settled);
    try expectExit(settled.term, 1);
    try std.testing.expect(std.mem.indexOf(u8, settled.stderr, "is already rejected") != null);
}