Skip to content
zit Artifact [cd9f47dae5]
Login

Artifact [cd9f47dae5]

Artifact cd9f47dae5ac3bdf5190db5db8f7d754fea51dc89a988629fe0e78dc41631ada:


const std = @import("std");
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const artifact = @import("zit").artifact;
const support = @import("support.zig");
const addManaged = support.addManaged;
const appendArtifact = support.appendArtifact;
const appendArtifactAs = support.appendArtifactAs;
const appendSyntheticCheckin = support.appendSyntheticCheckin;
const appendSyntheticCheckinAs = support.appendSyntheticCheckinAs;
const checkinHash = support.checkinHash;
const chmodFile = support.chmodFile;
const commitForkDup = support.commitForkDup;
const commitHashDup = support.commitHashDup;
const countLines = support.countLines;
const expectContains = support.expectContains;
const expectExit = support.expectExit;
const expectExitDiag = support.expectExitDiag;
const expectNonzeroExit = support.expectNonzeroExit;
const fileIndexUnknownOf = support.fileIndexUnknownOf;
const freeResult = support.freeResult;
const initRepo = support.initRepo;
const initTreeRepo = support.initTreeRepo;
const manifestReadsOf = support.manifestReadsOf;
const no_index = support.no_index;
const parseCheckin = support.parseCheckin;
const renameRun = support.renameRun;
const runCommitEnv = support.runCommitEnv;
const runZit = support.runZit;
const runZitEnv = support.runZitEnv;
const seedHistory = support.seedHistory;
const thinFixture = support.thinFixture;
const withZCard = support.withZCard;
const writeFile = support.writeFile;

// ==========================================================================
// `zit log CHECKIN` end-to-end. These tests spawn the real binary to observe
// log output. Synthetic fixtures write artifacts directly when a graph or
// corruption state cannot be constructed through the public CLI.
// ==========================================================================

test "cli log: a root check-in emits exactly its full ID" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "a.txt", "a\n");
    try addManaged(gpa, io, tmp.dir, &.{"a.txt"});

    var commit = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "root" });
    defer freeResult(gpa, &commit);
    try expectExit(commit.term, 0);
    const root = try checkinHash(commit.stdout);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", root });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [80]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\n", .{root});
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: a child emits itself then its parent" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "a.txt", "one\n");
    try addManaged(gpa, io, tmp.dir, &.{"a.txt"});

    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "root" });
    defer freeResult(gpa, &c1);
    try expectExit(c1.term, 0);
    const root = try checkinHash(c1.stdout);

    try writeFile(io, tmp.dir, "a.txt", "two\n");
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "child" });
    defer freeResult(gpa, &c2);
    try expectExit(c2.term, 0);
    const child = try checkinHash(c2.stdout);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", child });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\ncheckin {s}\n", .{ child, root });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}
test "cli log: an uppercase P-card parent ID remains a reachable invalid target" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const parent = try appendSyntheticCheckin(gpa, io, tmp.dir, "parent", null);
    defer gpa.free(parent);
    var uppercase_parent: [64]u8 = undefined;
    for (parent, &uppercase_parent) |byte, *destination| {
        destination.* = std.ascii.toUpper(byte);
    }
    try std.testing.expect(std.mem.indexOfAny(u8, uppercase_parent[0..], "ABCDEF") != null);
    const child = try appendRawCheckinWithUppercaseParent(gpa, io, tmp.dir, uppercase_parent[0..]);
    defer gpa.free(child);

    var stored_child = try parseCheckin(gpa, io, tmp.dir, child);
    defer stored_child.deinit();
    var expected_parent_card_buf: [67]u8 = undefined;
    const expected_parent_card = try std.fmt.bufPrint(
        &expected_parent_card_buf,
        "P {s}\n",
        .{uppercase_parent},
    );
    try std.testing.expect(std.mem.indexOf(u8, stored_child.bytes, expected_parent_card) != null);
    try std.testing.expectEqual(@as(usize, 1), stored_child.m.p.len);
    try std.testing.expectEqualStrings(uppercase_parent[0..], stored_child.m.p[0].parents.?);

    // The default walk reads the derived adjacency rather than re-parsing every
    // reachable manifest, so an uppercase P-card target is no longer diagnosed
    // HERE: the derive never crosslinked a check-in under that name, so the
    // edge leads to a rid with no event row and the walk names it a phantom,
    // rendered with the P card's own bytes -- the identity space keeps the
    // token as written, which is why the uppercase form comes back out.
    // Fossil draws the line the same way -- `plink` is written once at
    // crosslink and every later traversal trusts it -- and the damage is still
    // reported, by the verb whose job that is. See the `verify` assertion below.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", child });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\nphantom {s}\n", .{ child, uppercase_parent[0..] });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

fn appendRawCheckinWithUppercaseParent(
    gpa: std.mem.Allocator,
    io: std.Io,
    dir: std.Io.Dir,
    uppercase_parent: []const u8,
) ![]u8 {
    std.debug.assert(uppercase_parent.len == 64);

    var body_buf: [256]u8 = undefined;
    const body = try std.fmt.bufPrint(
        &body_buf,
        "C child\n" ++
            "D 2020-01-01T00:00:00\n" ++
            "F f 0000000000000000000000000000000000000000000000000000000000000000\n" ++
            "P {s}\n" ++
            "U u\n",
        .{uppercase_parent},
    );
    var raw_buf: [256]u8 = undefined;
    @memcpy(raw_buf[0..body.len], body);
    var checksum: [32]u8 = undefined;
    const digest = artifact.selfChecksum(body, &checksum);
    raw_buf[body.len] = 'Z';
    raw_buf[body.len + 1] = ' ';
    @memcpy(raw_buf[body.len + 2 ..][0..digest.len], digest);
    raw_buf[body.len + 34] = '\n';

    return appendArtifact(gpa, io, dir, raw_buf[0 .. body.len + 35]);
}

test "cli log: merge parents are traversed depth-first in P-card order" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const a = try appendSyntheticCheckin(gpa, io, tmp.dir, "a", null);
    defer gpa.free(a);
    const b = try appendSyntheticCheckin(gpa, io, tmp.dir, "b", null);
    defer gpa.free(b);
    const c = try appendSyntheticCheckin(gpa, io, tmp.dir, "c", a);
    defer gpa.free(c);
    var parents_buf: [129]u8 = undefined;
    const parents = try std.fmt.bufPrint(&parents_buf, "{s} {s}", .{ c, b });
    const merge = try appendSyntheticCheckin(gpa, io, tmp.dir, "merge", parents);
    defer gpa.free(merge);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", merge });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [320]u8 = undefined;
    const expected = try std.fmt.bufPrint(
        &want,
        "checkin {s}\ncheckin {s}\ncheckin {s}\ncheckin {s}\n",
        .{ merge, c, a, b },
    );
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: first visit wins across a diamond" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const base = try appendSyntheticCheckin(gpa, io, tmp.dir, "base", null);
    defer gpa.free(base);
    const left = try appendSyntheticCheckin(gpa, io, tmp.dir, "left", base);
    defer gpa.free(left);
    const right = try appendSyntheticCheckin(gpa, io, tmp.dir, "right", base);
    defer gpa.free(right);
    var parents_buf: [129]u8 = undefined;
    const parents = try std.fmt.bufPrint(&parents_buf, "{s} {s}", .{ left, right });
    const top = try appendSyntheticCheckin(gpa, io, tmp.dir, "top", parents);
    defer gpa.free(top);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", top });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [320]u8 = undefined;
    const expected = try std.fmt.bufPrint(
        &want,
        "checkin {s}\ncheckin {s}\ncheckin {s}\ncheckin {s}\n",
        .{ top, left, base, right },
    );
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: a valid missing reachable parent is printed once as a phantom" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const missing = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
    var parents_buf: [129]u8 = undefined;
    const parents = try std.fmt.bufPrint(&parents_buf, "{s} {s}", .{ missing, missing });
    const top = try appendSyntheticCheckin(gpa, io, tmp.dir, "phantom-parent", parents);
    defer gpa.free(top);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", top });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\nphantom {s}\n", .{ top, missing });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: a missing root check-in fails without output" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const missing = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", missing });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "zit log: check-in '{s}' not found\n", .{missing});
    try std.testing.expectEqualStrings(expected, res.stderr);
}

test "cli log: a malformed stored root is rejected as an invalid manifest" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const bad = try appendArtifact(gpa, io, tmp.dir, "not a manifest");
    defer gpa.free(bad);
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", bad });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    var want: [192]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "zit log: check-in '{s}' is not a valid manifest\n", .{bad});
    try std.testing.expectEqualStrings(expected, res.stderr);
}

test "cli log: a malformed reachable target fails after its valid ancestor" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const bad = try appendArtifact(gpa, io, tmp.dir, "not a manifest");
    defer gpa.free(bad);
    const top = try appendSyntheticCheckin(gpa, io, tmp.dir, "bad-parent", bad);
    defer gpa.free(top);
    // The default walk trusts the derived adjacency instead of re-parsing every
    // reachable manifest, so a target the derive never crosslinked is a phantom
    // here rather than a diagnosis. Fossil splits it the same way: `plink` is
    // written once at crosslink and every later traversal reads it, with
    // `test-integrity` as the verb that re-checks the repository. `zit verify`
    // is that verb here, and the assertion below holds it to the damage.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", top });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\nphantom {s}\n", .{ top, bad });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

fn appendSyntheticCluster(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) ![]u8 {
    const members = [_]artifact.MCard{.{
        .hash = "1111111111111111111111111111111111111111111111111111111111111111",
    }};
    var manifest: artifact.Manifest = .{
        .arena_state = std.heap.ArenaAllocator.init(gpa),
        .kind = .cluster,
        .a = null,
        .b = null,
        .c = null,
        .d = null,
        .e = null,
        .g = null,
        .h = null,
        .i = null,
        .k = null,
        .l = null,
        .n = null,
        .r = null,
        .u = null,
        .z = null,
        .w = null,
        .f = &.{},
        .j = &.{},
        .m = &members,
        .p = &.{},
        .q = &.{},
        .t = &.{},
    };
    defer manifest.deinit();
    const bytes = try artifact.create(&manifest, gpa);
    defer gpa.free(bytes);
    return appendArtifact(gpa, io, dir, bytes);
}

test "cli log: a reachable non-check-in artifact is rejected" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const cluster = try appendSyntheticCluster(gpa, io, tmp.dir);
    defer gpa.free(cluster);
    const top = try appendSyntheticCheckin(gpa, io, tmp.dir, "cluster-parent", cluster);
    defer gpa.free(top);
    // The default walk trusts the derived adjacency instead of re-parsing every
    // reachable manifest, so a target the derive never crosslinked is a phantom
    // here rather than a diagnosis. Fossil splits it the same way: `plink` is
    // written once at crosslink and every later traversal reads it, with
    // `test-integrity` as the verb that re-checks the repository. `zit verify`
    // is that verb here, and the assertion below holds it to the damage.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", top });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\nphantom {s}\n", .{ top, cluster });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: a torn tail is rejected without truncating the repository" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const root = try appendSyntheticCheckin(gpa, io, tmp.dir, "root", null);
    defer gpa.free(root);
    var file = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_write });
    const before = (try file.stat(io)).size;
    try file.writePositionalAll(io, "\x00", before);
    const torn_size = (try file.stat(io)).size;
    file.close(io);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", root });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(
        "zit log: cannot read repository: repository is corrupt\n",
        res.stderr,
    );
    var after_file = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_only });
    defer after_file.close(io);
    try std.testing.expectEqual(torn_size, (try after_file.stat(io)).size);
}

test "cli log: a stored SHA-1 parent is traversed by its 40-hex P-card ID" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const parent = try appendSyntheticCheckinAs(gpa, io, tmp.dir, .sha1, "sha1-parent", null);
    defer gpa.free(parent);
    try std.testing.expectEqual(@as(usize, 40), parent.len);
    const child = try appendSyntheticCheckinAs(gpa, io, tmp.dir, .sha3_256, "sha3-child", parent);
    defer gpa.free(child);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", child });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [128]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\ncheckin {s}\n", .{ child, parent });
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: a stored SHA-1 root is addressed by its 40-hex full ID" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const root = try appendSyntheticCheckinAs(gpa, io, tmp.dir, .sha1, "sha1-root", null);
    defer gpa.free(root);
    try std.testing.expectEqual(@as(usize, 40), root.len);
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", root });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var want: [64]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "checkin {s}\n", .{root});
    try std.testing.expectEqualStrings(expected, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

test "cli log: content stored under the wrong full ID fails integrity" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const real = try appendSyntheticCheckin(gpa, io, tmp.dir, "real", null);
    defer gpa.free(real);
    var checkin = try parseCheckin(gpa, io, tmp.dir, real);
    defer checkin.deinit();
    const wrong = "2222222222222222222222222222222222222222222222222222222222222222";
    var wrong_digest: [32]u8 = undefined;
    _ = try std.fmt.hexToBytes(&wrong_digest, wrong);
    var file = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_write });
    defer file.close(io);
    const st = try file.stat(io);
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = try logstore.LogStore.open(gpa, fs.storageFile(), 0);
    defer log.deinit(gpa);
    _ = try log.put(&wrong_digest, checkin.bytes);
    try log.commit();

    // WHERE THIS INTEGRITY CHECK LIVES NOW. The default walk reads the derived
    // adjacency and never re-hashes a reachable artifact, so `log` no longer
    // notices that these bytes are stored under a name they do not hash to.
    // That is fossil's split -- a manifest is validated once at crosslink, and
    // `test-integrity` is what re-checks a repository afterwards -- and paying
    // a full-history re-verification on every history listing was the anomaly.
    //
    // The guarantee MOVED; it was not dropped. `zit verify` reconstructs every
    // stored artifact through its delta chain and re-hashes it against its own
    // name, which is exactly this damage, and the assertion below is what keeps
    // that true: if verify ever stopped catching it, this test fails and the
    // coverage lost from `log` would not silently go missing everywhere.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", wrong });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);

    var ver = try runZit(gpa, io, tmp.dir, &.{"verify"});
    defer freeResult(gpa, &ver);
    try expectNonzeroExit(ver.term);
    try std.testing.expect(std.mem.indexOf(u8, ver.stdout, wrong) != null or
        std.mem.indexOf(u8, ver.stderr, wrong) != null);
}

test "cli log: a corrupt complete frame is rejected without truncation" {
    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 initial = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_only });
    const frame_offset = (try initial.stat(io)).size;
    initial.close(io);
    const root = try appendSyntheticCheckin(gpa, io, tmp.dir, "root", null);
    defer gpa.free(root);

    var file = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_write });
    const stable_size = (try file.stat(io)).size;
    var byte: [1]u8 = undefined;
    try std.testing.expectEqual(@as(usize, 1), try file.readPositionalAll(io, &byte, frame_offset + 10));
    byte[0] ^= 0xff;
    try file.writePositionalAll(io, &byte, frame_offset + 10);
    file.close(io);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", root });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(
        "zit log: cannot read repository: repository is corrupt\n",
        res.stderr,
    );
    var after = try tmp.dir.openFile(io, ".zit", .{ .mode = .read_only });
    defer after.close(io);
    try std.testing.expectEqual(stable_size, (try after.stat(io)).size);
}

test "cli log -F json: a file's history in Fossil's field names, newest first, with what each check-in did to it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "n.md", "one\n");
    try writeFile(io, tmp.dir, "k.md", "keep\n");
    try addManaged(gpa, io, tmp.dir, &.{ "n.md", "k.md" });
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "alice" }, &.{ "commit", "-m", "first" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);
    try writeFile(io, tmp.dir, "n.md", "two\n");
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "alice" }, &.{ "commit", "-m", "second edit" });
    defer freeResult(gpa, &c2);
    try expectExitDiag(c2.term, 0, c2);
    var rm = try runZit(gpa, io, tmp.dir, &.{ "rm", "n.md" });
    defer freeResult(gpa, &rm);
    try expectExitDiag(rm.term, 0, rm);
    var c3 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "bob" }, &.{ "commit", "-m", "gone" });
    defer freeResult(gpa, &c3);
    try expectExitDiag(c3.term, 0, c3);

    var lg = try runZit(gpa, io, tmp.dir, &.{ "log", "trunk", "n.md", "-F", "json" });
    defer freeResult(gpa, &lg);
    try expectExitDiag(lg.term, 0, lg);
    var doc = try std.json.parseFromSlice(std.json.Value, gpa, lg.stdout, .{});
    defer doc.deinit();
    const root = doc.value.object;
    try std.testing.expectEqual(@as(i64, 1), root.get("schema_version").?.integer);
    try std.testing.expectEqualStrings("n.md", root.get("name").?.string);
    const rows = root.get("checkins").?.array.items;
    try std.testing.expectEqual(@as(usize, 3), rows.len);
    const want = [_]struct { state: []const u8, comment: []const u8, user: []const u8, has_uuid: bool, has_parent: bool }{
        .{ .state = "removed", .comment = "gone", .user = "bob", .has_uuid = false, .has_parent = true },
        .{ .state = "modified", .comment = "second edit", .user = "alice", .has_uuid = true, .has_parent = true },
        .{ .state = "added", .comment = "first", .user = "alice", .has_uuid = true, .has_parent = false },
    };
    for (rows, want) |row, w| {
        const o = row.object;
        try std.testing.expectEqualStrings(w.state, o.get("state").?.string);
        try std.testing.expectEqualStrings(w.comment, o.get("comment").?.string);
        try std.testing.expectEqualStrings(w.user, o.get("user").?.string);
        try std.testing.expectEqual(w.has_uuid, o.get("uuid").? == .string);
        try std.testing.expectEqual(w.has_parent, o.get("parent").? == .string);
        try std.testing.expectEqual(w.has_uuid, o.get("size").? == .integer);
        const t = o.get("time").?.string;
        try std.testing.expectEqual(@as(usize, 24), t.len); // YYYY-MM-DDTHH:MM:SS.mmmZ
        try std.testing.expect(t[10] == 'T' and t[19] == '.' and t[23] == 'Z');
    }
    // The modified row's parent is the added row's content.
    try std.testing.expectEqualStrings(rows[2].object.get("uuid").?.string, rows[1].object.get("parent").?.string);

    var bare = try runZit(gpa, io, tmp.dir, &.{ "log", "trunk", "-F", "json" });
    defer freeResult(gpa, &bare);
    try expectExit(bare.term, 2);
    var bad = try runZit(gpa, io, tmp.dir, &.{ "log", "trunk", "n.md", "-F", "yaml" });
    defer freeResult(gpa, &bad);
    try expectExit(bad.term, 2);
}

test "cli log -F json: a purged version is still listed, its size null and its content named purged" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var h = try thinFixture(gpa, io, tmp.dir, &.{"init"});
    defer h.deinit(gpa);
    {
        var res = try runZit(gpa, io, tmp.dir, &.{ "purge", "artifacts", "--force", &h.blobs[1] });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
    }
    var lg = try runZit(gpa, io, tmp.dir, &.{ "log", "trunk", "n.md", "-F", "json" });
    defer freeResult(gpa, &lg);
    try expectExitDiag(lg.term, 0, lg);
    var doc = try std.json.parseFromSlice(std.json.Value, gpa, lg.stdout, .{});
    defer doc.deinit();
    const rows = doc.value.object.get("checkins").?.array.items;
    try std.testing.expectEqual(@as(usize, 5), rows.len);
    for (rows, 0..) |row, k| {
        const o = row.object;
        const i = 4 - k; // newest first
        try std.testing.expectEqualStrings(h.checkins[i], o.get("checkin").?.string);
        try std.testing.expectEqualStrings(&h.blobs[i], o.get("uuid").?.string);
        if (i == 1) {
            try std.testing.expect(o.get("size").? == .null);
            try std.testing.expectEqualStrings("purged", o.get("content").?.string);
        } else {
            try std.testing.expect(o.get("size").? == .integer);
            try std.testing.expect(o.get("content") == null);
        }
    }
}

test "cli log: help documents only the signed one-verb surface" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const expected =
        \\usage: zit log [--long] [-n N] [--offset N] [--cursor C] [-F json] [--no-follow]
        \\               [-R <path>] CHECKIN [PATH]
        \\
        \\Show CHECKIN followed by every reachable parent check-in in depth-first
        \\P-card order. CHECKIN accepts every form 'zit help names' lists —
        \\IDs, prefixes, branches, tags, reserved forms, and timestamps. Each
        \\check-in is shown once; a referenced parent missing from this
        \\repository is shown once as a phantom.
        \\
        \\With PATH, show only the reachable check-ins that change PATH — where
        \\PATH's effective content differs from its primary parent's, including
        \\where PATH is added or deleted. PATH is an exact repo-relative path, not
        \\a pattern; a path that never changed yields no output.
        \\They are listed newest first by check-in time, in the order
        \\'zit timeline' shows them, so -n N shows the N most recent.
        \\
        \\Renames are followed: the check-in that renamed the file to PATH is
        \\shown, and below it the history continues under the old name. Across a
        \\merge, a parent that does not hold the old name ends the history on
        \\that side. A check-in reached under two names is shown once. When a
        \\file was renamed away from PATH and a new one later created there, the
        \\new file's history ends where the old one was renamed. --no-follow
        \\shows PATH's history by name alone, as if no rename were recorded.
        \\
        \\--long adds each check-in's own facts after its id:
        \\
        \\  checkin <id> <timestamp> <user> <comment>
        \\
        \\The comment is last because it is the only field that may contain
        \\spaces; a check-in with no comment prints an empty trailing field, so
        \\the column count never varies. Absent timestamp or user read '-'.
        \\
        \\This record grammar is a contract: consumers parse it positionally, and
        \\no display option, present or future, will change it. Presentation
        \\extras (the timeline's --weekday, for one) belong to the verbs whose
        \\output is for eyes, not parsers.
        \\
        \\With PATH, -F json reports the same check-ins as one JSON document in
        \\Fossil's field names: schema_version, name (PATH), and checkins, each
        \\with checkin, name (the file's name in that check-in), prior (the name
        \\a rename moved it from, null on every other entry), uuid (its content
        \\there, null when removed), parent (its content in the primary parent,
        \\null when added), state (added, modified or removed; a rename is
        \\modified), time (RFC 3339 UTC with milliseconds), user, comment and
        \\size. A version purged, shunned or elided is still listed, with a
        \\null size and content naming why (purged, shunned or elided).
        \\Without PATH it is refused.
        \\
        \\With PATH, a history is read a page at a time. --offset N skips the N
        \\most recent entries, so -n 200 --offset 400 is the third page of 200.
        \\Under -n, -F json also names a cursor where the next page starts (null
        \\on the last page), the daemon's log cursor; --cursor C lists the page
        \\after it, from the check-in the first page walked from, whatever
        \\CHECKIN names, so the pages of one history stay that history's while
        \\new check-ins land. A cursor from another PATH or --no-follow is
        \\refused, exit 4. A page by cursor costs what the page costs; one by
        \\offset also decides each entry it skips.
        \\
        \\options:
        \\      --long    add timestamp, user and comment to each entry
        \\  -n, --limit N show only the N most recent entries; 0 means all
        \\      --offset N
        \\                with PATH, skip the N most recent entries
        \\      --cursor C
        \\                with PATH, the page after the one whose -F json named C
        \\  -F, --format json
        \\                with PATH, the history as one JSON document
        \\      --no-follow
        \\                with PATH, do not continue under a file's old name
        \\                below a rename
        \\  -R, --repo <path>
        \\                read this repository instead of the one found from the
        \\                current directory; <path> is the directory holding '.zit'
        \\                (or the '.zit' file itself). No working tree is required.
        \\  -h, --help    show this help and exit
        \\
        \\exit status:
        \\  0  success
        \\  1  operational failure (not a repository, unreadable state, a refused
        \\     action) — the diagnostic on stderr names it
        \\  2  usage error (an unknown option or unexpected argument)
        \\
    ;

    var direct = try runZit(gpa, io, tmp.dir, &.{ "log", "--help", "ignored" });
    defer freeResult(gpa, &direct);
    try expectExit(direct.term, 0);
    try std.testing.expectEqualStrings(expected, direct.stdout);
    try std.testing.expectEqualStrings("", direct.stderr);

    var topic = try runZit(gpa, io, tmp.dir, &.{ "help", "log" });
    defer freeResult(gpa, &topic);
    try expectExit(topic.term, 0);
    try std.testing.expectEqualStrings(expected, topic.stdout);
    try std.testing.expectEqualStrings("", topic.stderr);
}

test "cli log: usage rejects missing, extra, flags, and non-canonical IDs" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    var missing = try runZit(gpa, io, tmp.dir, &.{"log"});
    defer freeResult(gpa, &missing);
    try expectExit(missing.term, 2);
    try std.testing.expectEqualStrings("", missing.stdout);
    try std.testing.expectEqualStrings(
        "zit log: no check-in given\ntry 'zit log --help'\n",
        missing.stderr,
    );

    var flag = try runZit(gpa, io, tmp.dir, &.{ "log", "--all" });
    defer freeResult(gpa, &flag);
    try expectExit(flag.term, 2);
    try std.testing.expectEqualStrings("", flag.stdout);
    try std.testing.expectEqualStrings(
        "zit log: unknown option '--all'\ntry 'zit log --help'\n",
        flag.stderr,
    );

    // `--` ends the options, so the token after it is the check-in name and
    // the failure is resolution, not usage. Before this it was rejected as an
    // unknown option, which left a name beginning with a dash unreachable.
    var terminator = try runZit(gpa, io, tmp.dir, &.{ "log", "--", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" });
    defer freeResult(gpa, &terminator);
    // Not a usage error any more: the marker is consumed and the token after
    // it is the check-in name, so this fails later (no checkout here) rather
    // than at the parser. Asserted as "not exit 2, never `unknown option`"
    // instead of pinning whichever operational message comes first.
    try expectExit(terminator.term, 1);
    try std.testing.expectEqualStrings("", terminator.stdout);
    try std.testing.expect(std.mem.indexOf(u8, terminator.stderr, "unknown option") == null);

    // The second positional now binds PATH; a THIRD positional is the extra
    // argument (B-log-8).
    var extra = try runZit(gpa, io, tmp.dir, &.{ "log", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "path", "third" });
    defer freeResult(gpa, &extra);
    try expectExit(extra.term, 2);
    try std.testing.expectEqualStrings("", extra.stdout);
    try std.testing.expectEqualStrings(
        "zit log: unexpected argument 'third'\ntry 'zit log --help'\n",
        extra.stderr,
    );

    // A non-hex CHECKIN is no longer a syntax error: it is a name for the
    // resolver, and resolution needs a repository first.
    const uppercase = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    var invalid = try runZit(gpa, io, tmp.dir, &.{ "log", uppercase });
    defer freeResult(gpa, &invalid);
    try expectExit(invalid.term, 1);
    try std.testing.expectEqualStrings("", invalid.stdout);
    try std.testing.expectEqualStrings(
        "zit: no zit checkout here (looked for .zit-checkout in this directory and its parents)\n" ++
            "if this is a bare repository, name it with -R, or run 'zit open' to create a working tree\n",
        invalid.stderr,
    );
}

test "cli log: CHECKIN resolves like info — branch, prefix, and an unknown name" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    try initRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "a.txt", "one\n");
    var add = try runZit(gpa, io, tmp.dir, &.{ "add", "a.txt" });
    defer freeResult(gpa, &add);
    try expectExit(add.term, 0);
    var c1 = try runZit(gpa, io, tmp.dir, &.{ "commit", "-m", "root", "--user", "u" });
    defer freeResult(gpa, &c1);
    try expectExit(c1.term, 0);
    try writeFile(io, tmp.dir, "a.txt", "two\n");
    var c2 = try runZit(gpa, io, tmp.dir, &.{ "commit", "-m", "second", "--user", "u" });
    defer freeResult(gpa, &c2);
    try expectExit(c2.term, 0);

    var info = try runZit(gpa, io, tmp.dir, &.{ "info", "trunk" });
    defer freeResult(gpa, &info);
    try expectExit(info.term, 0);
    const tip_full = info.stdout[0 .. std.mem.indexOfScalar(u8, info.stdout, '\n') orelse info.stdout.len];

    // The full-ID walk is the baseline every symbolic form must reproduce.
    var by_full = try runZit(gpa, io, tmp.dir, &.{ "log", tip_full });
    defer freeResult(gpa, &by_full);
    try expectExit(by_full.term, 0);

    var by_branch = try runZit(gpa, io, tmp.dir, &.{ "log", "trunk" });
    defer freeResult(gpa, &by_branch);
    try expectExit(by_branch.term, 0);
    try std.testing.expectEqualStrings(by_full.stdout, by_branch.stdout);

    var by_prefix = try runZit(gpa, io, tmp.dir, &.{ "log", tip_full[0..12] });
    defer freeResult(gpa, &by_prefix);
    try expectExit(by_prefix.term, 0);
    try std.testing.expectEqualStrings(by_full.stdout, by_prefix.stdout);

    var unknown = try runZit(gpa, io, tmp.dir, &.{ "log", "no-such-name" });
    defer freeResult(gpa, &unknown);
    try expectExit(unknown.term, 1);
    try std.testing.expectEqualStrings("", unknown.stdout);
    try std.testing.expectEqualStrings(
        "zit log: check-in 'no-such-name' not found\n",
        unknown.stderr,
    );
}

// ==========================================================================
// `zit log CHECKIN PATH` end-to-end — the finfo fold (contract B-log-2..9).
// Each test builds its DAG through real commits (add/modify/`rm`/`mv`/`merge`)
// and asserts the filtered walk names exactly the check-ins that change PATH,
// in the unfiltered DFS order (B-log-1's layout preserved). Teardown is
// unconditional.
// ==========================================================================

test "cli log B-log-2/-4/-1: PATH lists only the check-ins that change it; no-PATH is unchanged" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    // root: a.txt is added (a root's presence alone is a change).
    try writeFile(io, tmp.dir, "a.txt", "one\n");
    try addManaged(gpa, io, tmp.dir, &.{"a.txt"});
    const root = try commitHashDup(gpa, io, tmp.dir, "root");
    defer gpa.free(root);

    // c2: a.txt modified (content hash differs from root's).
    try writeFile(io, tmp.dir, "a.txt", "two\n");
    const c2 = try commitHashDup(gpa, io, tmp.dir, "modify-a");
    defer gpa.free(c2);

    // c3: b.txt added; a.txt untouched — c3 must NOT appear in an a.txt log.
    try writeFile(io, tmp.dir, "b.txt", "b\n");
    try addManaged(gpa, io, tmp.dir, &.{"b.txt"});
    const c3 = try commitHashDup(gpa, io, tmp.dir, "add-b");
    defer gpa.free(c3);

    // c4: a.txt modified again.
    try writeFile(io, tmp.dir, "a.txt", "three\n");
    const c4 = try commitHashDup(gpa, io, tmp.dir, "modify-a-again");
    defer gpa.free(c4);

    // B-log-2/-4: filtered by a.txt = exactly {c4 modify, c2 modify, root add},
    // newest first; c3 (b.txt only) is walked but not named.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", c4, "a.txt" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var wbuf: [256]u8 = undefined;
    const want = try std.fmt.bufPrint(&wbuf, "checkin {s}\ncheckin {s}\ncheckin {s}\n", .{ c4, c2, root });
    try std.testing.expectEqualStrings(want, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);

    // B-log-1: the no-PATH walk is unchanged — every reachable check-in, DFS.
    var full = try runZit(gpa, io, tmp.dir, &.{ "log", c4 });
    defer freeResult(gpa, &full);
    try expectExit(full.term, 0);
    var fbuf: [320]u8 = undefined;
    const fwant = try std.fmt.bufPrint(&fbuf, "checkin {s}\ncheckin {s}\ncheckin {s}\ncheckin {s}\n", .{ c4, c3, c2, root });
    try std.testing.expectEqualStrings(fwant, full.stdout);
    try std.testing.expectEqualStrings("", full.stderr);

    // B-log-6: a path that never existed in the span yields empty stdout, exit 0.
    var none = try runZit(gpa, io, tmp.dir, &.{ "log", c4, "never.txt" });
    defer freeResult(gpa, &none);
    try expectExit(none.term, 0);
    try std.testing.expectEqualStrings("", none.stdout);
    try std.testing.expectEqualStrings("", none.stderr);

    // B-log-7: PATH is a path, not a pattern — a glob matches no entry (empty).
    var pat = try runZit(gpa, io, tmp.dir, &.{ "log", c4, "a.*" });
    defer freeResult(gpa, &pat);
    try expectExit(pat.term, 0);
    try std.testing.expectEqualStrings("", pat.stdout);
    try std.testing.expectEqualStrings("", pat.stderr);
}

test "cli log B-log-4: adds, deletes, and renames are changes at the affected 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);

    // r: x.txt and old.txt both added.
    try writeFile(io, tmp.dir, "x.txt", "x\n");
    try writeFile(io, tmp.dir, "old.txt", "old\n");
    try addManaged(gpa, io, tmp.dir, &.{ "x.txt", "old.txt" });
    const r = try commitHashDup(gpa, io, tmp.dir, "add-both");
    defer gpa.free(r);

    // d: x.txt deleted (old.txt untouched).
    var rm = try runZit(gpa, io, tmp.dir, &.{ "rm", "x.txt" });
    defer freeResult(gpa, &rm);
    try expectExit(rm.term, 0);
    const d = try commitHashDup(gpa, io, tmp.dir, "delete-x");
    defer gpa.free(d);

    // m: old.txt renamed to new.txt (a delete+add at the two names).
    var mv = try runZit(gpa, io, tmp.dir, &.{ "mv", "old.txt", "new.txt" });
    defer freeResult(gpa, &mv);
    try expectExit(mv.term, 0);
    const m = try commitHashDup(gpa, io, tmp.dir, "rename-old-to-new");
    defer gpa.free(m);

    // x.txt changed at its add (r) and its delete (d); m does not touch it.
    var lx = try runZit(gpa, io, tmp.dir, &.{ "log", m, "x.txt" });
    defer freeResult(gpa, &lx);
    try expectExit(lx.term, 0);
    var xb: [256]u8 = undefined;
    try std.testing.expectEqualStrings(
        try std.fmt.bufPrint(&xb, "checkin {s}\ncheckin {s}\n", .{ d, r }),
        lx.stdout,
    );
    try std.testing.expectEqualStrings("", lx.stderr);

    // old.txt: added at r, departs at the rename m; unchanged at d.
    var lo = try runZit(gpa, io, tmp.dir, &.{ "log", m, "old.txt" });
    defer freeResult(gpa, &lo);
    try expectExit(lo.term, 0);
    var ob: [256]u8 = undefined;
    try std.testing.expectEqualStrings(
        try std.fmt.bufPrint(&ob, "checkin {s}\ncheckin {s}\n", .{ m, r }),
        lo.stdout,
    );
    try std.testing.expectEqualStrings("", lo.stderr);

    // new.txt: the rename m, then old.txt's history below it.
    var ln = try runZit(gpa, io, tmp.dir, &.{ "log", m, "new.txt" });
    defer freeResult(gpa, &ln);
    try expectExit(ln.term, 0);
    var nb: [256]u8 = undefined;
    try std.testing.expectEqualStrings(
        try std.fmt.bufPrint(&nb, "checkin {s}\ncheckin {s}\n", .{ m, r }),
        ln.stdout,
    );
    try std.testing.expectEqualStrings("", ln.stderr);

    // By name alone, new.txt arrives only at the rename m.
    var lit = try runZit(gpa, io, tmp.dir, &.{ "log", "--no-follow", m, "new.txt" });
    defer freeResult(gpa, &lit);
    try expectExit(lit.term, 0);
    var lb: [128]u8 = undefined;
    try std.testing.expectEqualStrings(
        try std.fmt.bufPrint(&lb, "checkin {s}\n", .{m}),
        lit.stdout,
    );
    try std.testing.expectEqualStrings("", lit.stderr);
}

test "cli log B-log-3: the PATH filter sees full ancestry across a merge parent" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    // base: poem added.
    try writeFile(io, tmp.dir, "poem", "base\n");
    try addManaged(gpa, io, tmp.dir, &.{"poem"});
    const base = try commitHashDup(gpa, io, tmp.dir, "base");
    defer gpa.free(base);

    // other: poem changed on a side line reachable only via the merge parent.
    try writeFile(io, tmp.dir, "poem", "otherchange\n");
    const other = try commitHashDup(gpa, io, tmp.dir, "other");
    defer gpa.free(other);

    // current: back at base, add side.txt; poem is left at base content.
    var up = try runZit(gpa, io, tmp.dir, &.{ "update", base });
    defer freeResult(gpa, &up);
    try expectExit(up.term, 0);
    try writeFile(io, tmp.dir, "side.txt", "s\n");
    try addManaged(gpa, io, tmp.dir, &.{"side.txt"});
    const current = try commitForkDup(gpa, io, tmp.dir, "current");
    defer gpa.free(current);

    // Merge other in (poem changed only on the other side → clean), then record
    // the merge as a check-in whose primary parent is current, merge parent other.
    var mg = try runZit(gpa, io, tmp.dir, &.{ "merge", other });
    defer freeResult(gpa, &mg);
    try expectExit(mg.term, 0);
    const merge_ci = try commitHashDup(gpa, io, tmp.dir, "merge");
    defer gpa.free(merge_ci);

    // Filtered by poem: merge_ci (adopts other's content vs current), base (add),
    // and other (the merged-in change) — current is walked but unchanged for poem.
    // `other` is reachable ONLY through the merge parent, so its presence proves
    // the walk spans full ancestry (a mainline-only walk would omit it).
    // The three share one commit time, so they list descendants first, as
    // the timeline orders a tie: other before its parent base.
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", merge_ci, "poem" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    var wbuf: [320]u8 = undefined;
    const want = try std.fmt.bufPrint(&wbuf, "checkin {s}\ncheckin {s}\ncheckin {s}\n", .{ merge_ci, other, base });
    try std.testing.expectEqualStrings(want, res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
}

/// A commit at SOURCE_DATE_EPOCH `epoch`, with `extra` arguments.
fn commitAtWith(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, msg: []const u8, epoch: []const u8, extra: []const []const u8) ![]const u8 {
    var argv: std.ArrayList([]const u8) = .empty;
    defer argv.deinit(gpa);
    try argv.appendSlice(gpa, &.{ "commit", "-m", msg });
    try argv.appendSlice(gpa, extra);
    var res = try runCommitEnv(gpa, io, dir, .{ .user = "u", .epoch = epoch }, argv.items);
    defer freeResult(gpa, &res);
    try expectExitDiag(res.term, 0, res);
    return gpa.dupe(u8, try checkinHash(res.stdout));
}

/// f.txt changed on trunk and on a side branch at interleaved times, the
/// side merged back, then f.txt renamed to g.txt and changed once more.
/// The first-parent chain is t9 r8 m7 t6 t4 t2 t1; s5 and s3 are reached
/// only through the merge, and their times fall between trunk's.
const BranchyFileHistory = struct {
    t1: []const u8,
    t2: []const u8,
    s3: []const u8,
    t4: []const u8,
    s5: []const u8,
    t6: []const u8,
    m7: []const u8,
    r8: []const u8,
    t9: []const u8,

    fn deinit(self: *BranchyFileHistory, gpa: std.mem.Allocator) void {
        for ([_][]const u8{ self.t1, self.t2, self.s3, self.t4, self.s5, self.t6, self.m7, self.r8, self.t9 }) |id| gpa.free(id);
    }
};

fn buildBranchyFileHistory(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !BranchyFileHistory {
    try initRepo(gpa, io, dir);
    var h: BranchyFileHistory = undefined;
    try writeFile(io, dir, "f.txt", "v1\n");
    try writeFile(io, dir, "other.txt", "o\n");
    try addManaged(gpa, io, dir, &.{ "f.txt", "other.txt" });
    h.t1 = try commitAtWith(gpa, io, dir, "t1", "1000000060", &.{});
    try writeFile(io, dir, "f.txt", "v2\n");
    h.t2 = try commitAtWith(gpa, io, dir, "t2", "1000000120", &.{});
    try writeFile(io, dir, "f.txt", "side3\n");
    h.s3 = try commitAtWith(gpa, io, dir, "s3", "1000000180", &.{ "--branch", "side" });
    for ([_][]const []const u8{ &.{ "update", "trunk" }, &.{ "update", "side" }, &.{ "update", "trunk" } }, 0..) |argv, step| {
        var up = try runZit(gpa, io, dir, argv);
        defer freeResult(gpa, &up);
        try expectExitDiag(up.term, 0, up);
        switch (step) {
            0 => {
                try writeFile(io, dir, "f.txt", "v4\n");
                try writeFile(io, dir, "other.txt", "t4\n");
                h.t4 = try commitAtWith(gpa, io, dir, "t4", "1000000240", &.{});
            },
            1 => {
                try writeFile(io, dir, "f.txt", "side5\n");
                h.s5 = try commitAtWith(gpa, io, dir, "s5", "1000000300", &.{});
            },
            else => {
                try writeFile(io, dir, "f.txt", "v6\n");
                h.t6 = try commitAtWith(gpa, io, dir, "t6", "1000000360", &.{});
            },
        }
    }
    // Both sides changed f.txt: the merge conflicts, and the resolution is
    // written over it.
    var mg = try runZit(gpa, io, dir, &.{ "merge", "side" });
    freeResult(gpa, &mg);
    try writeFile(io, dir, "f.txt", "merged7\n");
    h.m7 = try commitAtWith(gpa, io, dir, "m7", "1000000420", &.{});
    var mv = try runZit(gpa, io, dir, &.{ "mv", "f.txt", "g.txt" });
    defer freeResult(gpa, &mv);
    try expectExitDiag(mv.term, 0, mv);
    h.r8 = try commitAtWith(gpa, io, dir, "r8", "1000000480", &.{});
    try writeFile(io, dir, "g.txt", "v9\n");
    h.t9 = try commitAtWith(gpa, io, dir, "t9", "1000000540", &.{});
    return h;
}

/// The check-in IDs of `log` output lines, in order.
fn logIds(gpa: std.mem.Allocator, stdout: []const u8) ![][]const u8 {
    var ids: std.ArrayList([]const u8) = .empty;
    errdefer ids.deinit(gpa);
    var it = std.mem.splitScalar(u8, stdout, '\n');
    while (it.next()) |line| {
        if (line.len == 0) continue;
        var fields = std.mem.splitScalar(u8, line, ' ');
        try std.testing.expectEqualStrings("checkin", fields.next().?);
        try ids.append(gpa, fields.next().?);
    }
    return ids.toOwnedSlice(gpa);
}

test "cli log PATH: a branchy history lists newest first by check-in time, the same rows, and -n pages it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var h = try buildBranchyFileHistory(gpa, io, tmp.dir);
    defer h.deinit(gpa);

    // The rows the traversal-order walk listed, now in time order: s5 and
    // s3 used to trail the whole first-parent chain.
    const Case = struct { argv: []const []const u8, want: []const []const u8, names: []const []const u8 };
    const cases = [_]Case{
        .{
            .argv = &.{ "log", h.t9, "g.txt" },
            .want = &.{ h.t9, h.r8, h.m7, h.t6, h.s5, h.t4, h.s3, h.t2, h.t1 },
            .names = &.{ "g.txt", "g.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt" },
        },
        .{
            .argv = &.{ "log", "--no-follow", h.t9, "f.txt" },
            .want = &.{ h.r8, h.m7, h.t6, h.s5, h.t4, h.s3, h.t2, h.t1 },
            .names = &.{ "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt" },
        },
        .{
            .argv = &.{ "log", h.m7, "f.txt" },
            .want = &.{ h.m7, h.t6, h.s5, h.t4, h.s3, h.t2, h.t1 },
            .names = &.{ "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt", "f.txt" },
        },
    };
    for (cases) |case| {
        var argv: std.ArrayList([]const u8) = .empty;
        defer argv.deinit(gpa);
        try argv.appendSlice(gpa, case.argv);
        try argv.append(gpa, "--long");
        var full = try runZit(gpa, io, tmp.dir, argv.items);
        defer freeResult(gpa, &full);
        try expectExitDiag(full.term, 0, full);
        const ids = try logIds(gpa, full.stdout);
        defer gpa.free(ids);
        try std.testing.expectEqual(case.want.len, ids.len);
        for (case.want, ids) |w, got| try std.testing.expectEqualStrings(w, got);
        // The time column never rises.
        var prev: ?[]const u8 = null;
        var lines = std.mem.splitScalar(u8, full.stdout, '\n');
        while (lines.next()) |line| {
            if (line.len == 0) continue;
            const when = line[8 + 64 + 1 ..][0..19];
            if (prev) |p| try std.testing.expect(std.mem.order(u8, when, p) != .gt);
            prev = when;
        }

        // `-n k` is the first k rows for every k, so pages taken by
        // asking for more rows each time never repeat or drop one.
        for (1..case.want.len + 2) |k| {
            var kbuf: [8]u8 = undefined;
            const kv = try std.fmt.bufPrint(&kbuf, "{d}", .{k});
            var nargv: std.ArrayList([]const u8) = .empty;
            defer nargv.deinit(gpa);
            try nargv.appendSlice(gpa, &.{ "log", "--long", "-n", kv });
            try nargv.appendSlice(gpa, case.argv[1..]);
            var lim = try runZit(gpa, io, tmp.dir, nargv.items);
            defer freeResult(gpa, &lim);
            try expectExitDiag(lim.term, 0, lim);
            try std.testing.expect(std.mem.startsWith(u8, full.stdout, lim.stdout));
            try std.testing.expectEqual(@min(k, case.want.len), countLines(lim.stdout));
        }

        // `-F json` lists the same check-ins in the same order, each under
        // the name the file had there: renames are followed across the
        // reorder.
        var jargv: std.ArrayList([]const u8) = .empty;
        defer jargv.deinit(gpa);
        try jargv.appendSlice(gpa, case.argv);
        try jargv.appendSlice(gpa, &.{ "-F", "json" });
        var js = try runZit(gpa, io, tmp.dir, jargv.items);
        defer freeResult(gpa, &js);
        try expectExitDiag(js.term, 0, js);
        const parsed = try std.json.parseFromSlice(std.json.Value, gpa, js.stdout, .{});
        defer parsed.deinit();
        const rows = parsed.value.object.get("checkins").?.array.items;
        try std.testing.expectEqual(case.want.len, rows.len);
        for (case.want, case.names, rows) |w, name, row| {
            try std.testing.expectEqualStrings(w, row.object.get("checkin").?.string);
            try std.testing.expectEqualStrings(name, row.object.get("name").?.string);
        }
    }
}

test "cli log B-log-9: PATH adds no new refusal surface — an unresolvable CHECKIN still fails cleanly" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const missing = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
    var res = try runZit(gpa, io, tmp.dir, &.{ "log", missing, "a.txt" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    var want: [160]u8 = undefined;
    const expected = try std.fmt.bufPrint(&want, "zit log: check-in '{s}' not found\n", .{missing});
    try std.testing.expectEqualStrings(expected, res.stderr);
}

test "cli log -n: limits the ancestry walk to the N most recent check-ins" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedHistory(gpa, io, tmp.dir, 6);

    // The tip's full ID, read off `leaves` (hash column).
    var leaves = try runZit(gpa, io, tmp.dir, &.{"leaves"});
    defer freeResult(gpa, &leaves);
    try expectExit(leaves.term, 0);
    // The leaf line is Fossil's `(1) time [hash] …`; the twelve-character
    // name inside the brackets resolves like any prefix.
    const lb = std.mem.indexOfScalar(u8, leaves.stdout, '[').? + 1;
    const rb = std.mem.indexOfScalarPos(u8, leaves.stdout, lb, ']').?;
    const tip = leaves.stdout[lb..rb];

    var full = try runZit(gpa, io, tmp.dir, &.{ "log", tip });
    defer freeResult(gpa, &full);
    try expectExit(full.term, 0);
    try std.testing.expectEqual(@as(usize, 6), countLines(full.stdout));

    var lim = try runZit(gpa, io, tmp.dir, &.{ "log", "-n", "3", tip });
    defer freeResult(gpa, &lim);
    try expectExit(lim.term, 0);
    try std.testing.expectEqual(@as(usize, 3), countLines(lim.stdout));
    // Again a prefix, not merely a count: the walk order must be unchanged.
    try std.testing.expect(std.mem.startsWith(u8, full.stdout, lim.stdout));

    // `-n 0` walks the whole ancestry.
    var all = try runZit(gpa, io, tmp.dir, &.{ "log", "-n", "0", tip });
    defer freeResult(gpa, &all);
    try expectExit(all.term, 0);
    try std.testing.expectEqualStrings(full.stdout, all.stdout);
}

test "cli log: --long answers a file-history page in one invocation" {
    // `log CHECKIN PATH` already selects the check-ins that changed PATH; what
    // was missing is their facts, which cost a subprocess per row otherwise.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    try writeFile(io, tmp.dir, "a.txt", "one\n");
    try writeFile(io, tmp.dir, "b.txt", "untouched\n");
    try addManaged(gpa, io, tmp.dir, &.{ "a.txt", "b.txt" });
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "alice" }, &.{ "commit", "-m", "first commit" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);

    try writeFile(io, tmp.dir, "a.txt", "two\n");
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "bob" }, &.{ "commit", "-m", "second commit" });
    defer freeResult(gpa, &c2);
    try expectExitDiag(c2.term, 0, c2);

    var res = try runZit(gpa, io, tmp.dir, &.{ "log", "--long", "tip", "a.txt" });
    defer freeResult(gpa, &res);
    try expectExitDiag(res.term, 0, res);

    // Both authors and both comments arrive without a second invocation.
    for ([_][]const u8{ "alice", "bob", "first commit", "second commit" }) |needle| {
        try std.testing.expect(std.mem.indexOf(u8, res.stdout, needle) != null);
    }
    // The path filter still holds: b.txt changed only in the first commit.
    var only_b = try runZit(gpa, io, tmp.dir, &.{ "log", "--long", "tip", "b.txt" });
    defer freeResult(gpa, &only_b);
    try expectExit(only_b.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, only_b.stdout, "second commit") == null);

    // Default output is unchanged — two fields, no metadata.
    var plain = try runZit(gpa, io, tmp.dir, &.{ "log", "tip", "a.txt" });
    defer freeResult(gpa, &plain);
    try expectExit(plain.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, plain.stdout, "alice") == null);
}

test "cli log: a PATH-filtered log costs reads per ENTRY NAMED, not per check-in walked" {
    // The defect: the predicate reconstructed a manifest for every check-in
    // the walk visited, so one file's history on a mirror of SQLite took 129s
    // and the cost grew with how much unrelated history sat behind it.
    //
    // The invariant the file index buys, stated so it cannot regress quietly:
    // a history where most check-ins never touch PATH costs reads in
    // proportion to the entries NAMED, not to the check-ins WALKED. Most of
    // this repository's check-ins touch only `filler.txt`, and answering for
    // `a.txt` must not pay for them.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    try writeFile(io, tmp.dir, "a.txt", "a-seed\n");
    try writeFile(io, tmp.dir, "filler.txt", "f-seed\n");
    try addManaged(gpa, io, tmp.dir, &.{ "a.txt", "filler.txt" });
    var tip = try commitHashDup(gpa, io, tmp.dir, "seed");
    defer gpa.free(tip);
    const total = 40;
    var named: usize = 1; // the seed names a.txt
    var i: usize = 0;
    while (i < total) : (i += 1) {
        var body: [16]u8 = undefined;
        // Only every eighth check-in touches a.txt; the rest are noise the
        // index must let the walk skip without reading anything.
        if (i % 8 == 0) {
            try writeFile(io, tmp.dir, "a.txt", std.fmt.bufPrint(&body, "a{d}\n", .{i}) catch unreachable);
            named += 1;
        } else {
            try writeFile(io, tmp.dir, "filler.txt", std.fmt.bufPrint(&body, "f{d}\n", .{i}) catch unreachable);
        }
        gpa.free(tip);
        tip = try commitHashDup(gpa, io, tmp.dir, "edit");
    }

    const seam = [_][2][]const u8{.{ "ZIT_MANIFEST_READS", "1" }};
    var res = try runZitEnv(gpa, io, tmp.dir, &seam, &.{ "log", tip, "a.txt" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    const entries = std.mem.count(u8, res.stdout, "checkin ");
    try std.testing.expectEqual(named, entries);
    const reads = manifestReadsOf(&res) orelse return error.NoCounter;

    // Confirming a candidate reconstructs it and its primary parent, so a few
    // reads per named entry is the floor. What must NOT happen is a read per
    // walked check-in: that is the defect, and at this shape it is >= 41.
    if (reads > 4 * named) {
        std.debug.print(
            "\nlog PATH filter: naming {d} entries out of {d} check-ins cost {d} manifest reads — " ++
                "the walk is paying for check-ins that never touched the path again.\n",
            .{ entries, total + 1, reads },
        );
        return error.ReadsScaleWithHistory;
    }
}

test "cli log: a path no check-in ever held answers no rows without reading the history" {
    // A following walk reads each check-in's file list until it meets the
    // file, so a name it never meets used to cost a read per ancestor.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, "a.txt", "seed\n");
    try addManaged(gpa, io, tmp.dir, &.{"a.txt"});
    var tip = try commitHashDup(gpa, io, tmp.dir, "seed");
    defer gpa.free(tip);
    for (0..30) |i| {
        var body: [16]u8 = undefined;
        try writeFile(io, tmp.dir, "a.txt", std.fmt.bufPrint(&body, "a{d}\n", .{i}) catch unreachable);
        gpa.free(tip);
        tip = try commitHashDup(gpa, io, tmp.dir, "edit");
    }

    const seam = [_][2][]const u8{.{ "ZIT_MANIFEST_READS", "1" }};
    const forms = [_][]const []const u8{
        &.{ "log", tip, "missing.txt" },
        &.{ "log", "--long", "-n", "1", tip, "missing.txt" },
        &.{ "log", "--no-follow", tip, "missing.txt" },
    };
    for (forms) |argv| {
        var res = try runZitEnv(gpa, io, tmp.dir, &seam, argv);
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
        try std.testing.expectEqualStrings("", res.stdout);
        const reads = manifestReadsOf(&res) orelse return error.NoCounter;
        if (reads > 2) {
            std.debug.print("\nlog {s}: {d} manifest reads for a path no check-in held\n", .{ argv[1], reads });
            return error.ReadsScaleWithHistory;
        }
    }
    var js = try runZit(gpa, io, tmp.dir, &.{ "log", tip, "missing.txt", "-F", "json" });
    defer freeResult(gpa, &js);
    try expectExitDiag(js.term, 0, js);
    try expectContains(js.stdout, "\"checkins\":[]");
}

test "cli log: the file index narrows the walk without changing one byte of the answer" {
    // The index (`captureFileFacts`, inverted by path) and the B-log-2
    // predicate are NOT the same relation: an F-card-level diff reports a
    // delta manifest that restates a path with the hash it already had, while
    // the path's effective content did not move. So the index is allowed to
    // over-report and is used only to NARROW; every candidate is confirmed by
    // reconstruction. What must never happen is an OMISSION — a check-in the
    // index leaves out is skipped unread, so a miss would silently drop a
    // file's history.
    //
    // This pins exactly that: for every tracked path, the indexed answer and
    // the reconstruct-everything answer are byte-identical.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    // A history with the shapes that make the two relations diverge: repeated
    // edits (delta manifests over a shared baseline), a file added late, one
    // deleted, and a branch merged back.
    try writeFile(io, tmp.dir, "a.txt", "a1\n");
    try writeFile(io, tmp.dir, "b.txt", "b1\n");
    try addManaged(gpa, io, tmp.dir, &.{ "a.txt", "b.txt" });
    var tip = try commitHashDup(gpa, io, tmp.dir, "seed");
    defer gpa.free(tip);
    var i: usize = 0;
    while (i < 8) : (i += 1) {
        var body: [16]u8 = undefined;
        try writeFile(io, tmp.dir, "a.txt", std.fmt.bufPrint(&body, "a{d}\n", .{i}) catch unreachable);
        if (i % 3 == 0) try writeFile(io, tmp.dir, "b.txt", std.fmt.bufPrint(&body, "b{d}\n", .{i}) catch unreachable);
        gpa.free(tip);
        tip = try commitHashDup(gpa, io, tmp.dir, "edit");
    }
    try writeFile(io, tmp.dir, "c.txt", "c1\n");
    try addManaged(gpa, io, tmp.dir, &.{"c.txt"});
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "add c");
    var rm = try runZit(gpa, io, tmp.dir, &.{ "rm", "--hard", "b.txt" });
    defer freeResult(gpa, &rm);
    try expectExit(rm.term, 0);
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "drop b");

    const off = [_][2][]const u8{.{ "ZIT_NO_FILE_INDEX", "1" }};
    for ([_][]const u8{ "a.txt", "b.txt", "c.txt", "never.txt" }) |path| {
        // Indexed (built on the first query, adopted after).
        var indexed = try runZit(gpa, io, tmp.dir, &.{ "log", "--long", tip, path });
        defer freeResult(gpa, &indexed);
        try expectExit(indexed.term, 0);
        // Reconstructed, the answer the index must reproduce exactly.
        var plain = try runZitEnv(gpa, io, tmp.dir, &off, &.{ "log", "--long", tip, path });
        defer freeResult(gpa, &plain);
        try expectExit(plain.term, 0);
        if (!std.mem.eql(u8, indexed.stdout, plain.stdout)) {
            std.debug.print(
                "\nfile index: '{s}' answers differently with the index than without it.\n--- reconstructed ---\n{s}\n--- indexed ---\n{s}\n",
                .{ path, plain.stdout, indexed.stdout },
            );
            return error.IndexChangedTheAnswer;
        }
    }
}

test "cli log: on a tree-manifest store the file index answers, and answers exactly what reconstruction does" {
    // The change-set capture refused every tree manifest as "unknown at this
    // layer", so on a submanifest store the index recorded the whole log as
    // unknown: valid, adopted, never rebuilt, and answering nothing — a PATH
    // query paid the build and then reconstructed per check-in anyway. On a
    // pkgsrc mirror that was 39 minutes a query. The answer was always right;
    // this pins that it stays right AND that the index now carries it.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var tip = try initTreeRepo(gpa, io, tmp.dir);
    defer gpa.free(tip);

    // a/x.txt changes in the seed, the 1st and the 3rd commit; b/y.txt in the
    // seed and the 2nd; c/z.txt only in the seed.
    try writeFile(io, tmp.dir, "a/x.txt", "x2\n");
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "x again");
    try writeFile(io, tmp.dir, "b/y.txt", "y2\n");
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "y again");
    try writeFile(io, tmp.dir, "a/x.txt", "x3\n");
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "x third");

    const seam = [_][2][]const u8{.{ "ZIT_FILEINDEX_WALK", "1" }};
    const off = [_][2][]const u8{.{ "ZIT_NO_FILE_INDEX", "1" }};
    const want = [_]struct { path: []const u8, n: usize }{
        .{ .path = "a/x.txt", .n = 3 },
        .{ .path = "b/y.txt", .n = 2 },
        .{ .path = "c/z.txt", .n = 1 },
    };
    for (want) |w| {
        var indexed = try runZitEnv(gpa, io, tmp.dir, &seam, &.{ "log", tip, w.path });
        defer freeResult(gpa, &indexed);
        try expectExitDiag(indexed.term, 0, indexed);
        // THE FIX: a tree check-in's change set is known to the index.
        const unknown = fileIndexUnknownOf(&indexed) orelse return error.NoCounter;
        if (unknown != 0) {
            std.debug.print("\nfile index: recorded {d} check-ins as unknown on a tree-manifest store\n", .{unknown});
            return error.TreeCheckinsUnknownToIndex;
        }
        try std.testing.expectEqual(w.n, std.mem.count(u8, indexed.stdout, "checkin "));

        var plain = try runZitEnv(gpa, io, tmp.dir, &off, &.{ "log", tip, w.path });
        defer freeResult(gpa, &plain);
        try expectExitDiag(plain.term, 0, plain);
        try std.testing.expectEqualStrings(plain.stdout, indexed.stdout);
    }
}

fn footprintCounter(res: *const std.process.RunResult, key: []const u8) ?u64 {
    const at = std.mem.lastIndexOf(u8, res.stderr, key) orelse return null;
    const rest = res.stderr[at + key.len ..];
    var end: usize = 0;
    while (end < rest.len and rest[end] >= '0' and rest[end] <= '9') end += 1;
    return std.fmt.parseInt(u64, rest[0..end], 10) catch null;
}

test "log opens on the image path: a warm log replays no records on flat and tree stores" {
    // `log` reached past the open funnel and inherited the full record replay
    // meant for write verbs, twice for a symbolic name. On a million-artifact
    // store that was most of a second before the first row, and it was the
    // whole of the cold-open cost the file index could not remove. Every
    // route `log` has — literal ID, symbolic name, PATH, `--long` — now opens
    // once on the zero-parse image, and this pins that none of them replays.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    const seam = [_][2][]const u8{.{ "ZIT_DERIVE_FOOTPRINT", "1" }};
    for ([_]bool{ false, true }) |tree| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        var tip: []const u8 = undefined;
        if (tree) {
            tip = try initTreeRepo(gpa, io, tmp.dir);
        } else {
            try initRepo(gpa, io, tmp.dir);
            try tmp.dir.createDirPath(io, "a");
            try writeFile(io, tmp.dir, "a/x.txt", "x1\n");
            try addManaged(gpa, io, tmp.dir, &.{"a/x.txt"});
            tip = try commitHashDup(gpa, io, tmp.dir, "seed");
        }
        defer gpa.free(tip);
        try writeFile(io, tmp.dir, "a/x.txt", "x2\n");
        gpa.free(tip);
        tip = try commitHashDup(gpa, io, tmp.dir, "x again");

        // One read warms the cache; the commit above left a tail to adopt.
        {
            var warm = try runZit(gpa, io, tmp.dir, &.{ "log", tip });
            defer freeResult(gpa, &warm);
            try expectExitDiag(warm.term, 0, warm);
        }
        const routes = [_][]const []const u8{
            &.{ "log", tip },
            &.{ "log", "trunk" },
            &.{ "log", "-n", "1", "trunk" },
            &.{ "log", "--long", "-n", "5", "trunk", "a/x.txt" },
            &.{ "log", "-n", "5", tip, "a/x.txt" },
        };
        for (routes) |route| {
            var res = try runZitEnv(gpa, io, tmp.dir, &seam, route);
            defer freeResult(gpa, &res);
            try expectExitDiag(res.term, 0, res);
            try std.testing.expect(std.mem.count(u8, res.stdout, "\n") >= 1);
            const replayed = footprintCounter(&res, "state-records=") orelse return error.NoCounter;
            const derived = footprintCounter(&res, "records=") orelse return error.NoCounter;
            if (replayed != 0 or derived != 0) {
                std.debug.print("\nlog {s}: replayed {d} records and derived {d} on a warm {s} store\n", .{ route[1], replayed, derived, if (tree) "tree" else "flat" });
                return error.LogReplaysRecords;
            }
        }
    }
}

test "cli log: a flat store and its tree-manifest twin give the same file history for every path" {
    // The same history minted both ways — `submanifest convert` re-mints every
    // check-in as a tree under a new project code — so shape is the only
    // variable. The differential suite cannot host this: it compares zit
    // against a real fossil, and no released fossil speaks submanifests.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try tmp.dir.createDirPath(io, "flat");
    var flat = try tmp.dir.openDir(io, "flat", .{});
    defer flat.close(io);
    try initRepo(gpa, io, flat);
    for ([_][]const u8{ "a", "b", "c" }) |d| try flat.createDirPath(io, d);
    try writeFile(io, flat, "a/x.txt", "x1\n");
    try writeFile(io, flat, "b/y.txt", "y1\n");
    try writeFile(io, flat, "c/z.txt", "z1\n");
    try addManaged(gpa, io, flat, &.{ "a/x.txt", "b/y.txt", "c/z.txt" });
    gpa.free(try commitHashDup(gpa, io, flat, "seed"));
    try writeFile(io, flat, "a/x.txt", "x2\n");
    gpa.free(try commitHashDup(gpa, io, flat, "x again"));
    try writeFile(io, flat, "b/y.txt", "y2\n");
    gpa.free(try commitHashDup(gpa, io, flat, "y again"));

    {
        var conv = try runZit(gpa, io, tmp.dir, &.{ "submanifest", "convert", "flat", "sub", "--k", "1" });
        defer freeResult(gpa, &conv);
        try expectExitDiag(conv.term, 0, conv);
    }
    var sub = try tmp.dir.openDir(io, "sub", .{});
    defer sub.close(io);

    const seam = [_][2][]const u8{.{ "ZIT_FILEINDEX_WALK", "1" }};
    for ([_][]const u8{ "a/x.txt", "b/y.txt", "c/z.txt" }) |path| {
        var f = try runZit(gpa, io, flat, &.{ "log", "tip", path });
        defer freeResult(gpa, &f);
        try expectExitDiag(f.term, 0, f);
        var s = try runZitEnv(gpa, io, sub, &seam, &.{ "log", "-R", ".zit", "tip", path });
        defer freeResult(gpa, &s);
        try expectExitDiag(s.term, 0, s);
        // Hashes differ across the rebirth; the history's SHAPE must not.
        try std.testing.expectEqual(
            std.mem.count(u8, f.stdout, "checkin "),
            std.mem.count(u8, s.stdout, "checkin "),
        );
        try std.testing.expectEqual(@as(u64, 0), fileIndexUnknownOf(&s) orelse return error.NoCounter);
    }
}

/// Every `log PATH` form, each run as it ships and under
/// `ZIT_PARSE_EVERY_NODE`, which parses every node whole and reads each row
/// with fresh memos: stdout, stderr and exit must agree byte for byte.
fn expectLogFormsAgree(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, tip: []const u8, paths: []const []const u8) !void {
    const forms = [_][]const []const u8{
        &.{ "-F", "json" },
        &.{ "-F", "json", "-n", "2" },
        &.{ "-F", "json", "--offset", "1", "-n", "2" },
        &.{ "-F", "json", "--no-follow" },
        &.{},
        &.{"--long"},
        &.{"--no-follow"},
        &.{ "-n", "3" },
        &.{ "--long", "-n", "1" },
        &.{ "--long", "--offset", "2" },
    };
    // Without the file index every row is decided by these lookups, rename
    // edges included, so both readings are compared there too.
    const shipped = [_][]const [2][]const u8{ &.{}, &.{.{ "ZIT_NO_FILE_INDEX", "1" }} };
    const parsed = [_][]const [2][]const u8{
        &.{.{ "ZIT_PARSE_EVERY_NODE", "1" }},
        &.{ .{ "ZIT_PARSE_EVERY_NODE", "1" }, .{ "ZIT_NO_FILE_INDEX", "1" } },
    };
    for (paths) |path| for (forms) |form| for (shipped, parsed) |env_fast, env_slow| {
        var argv: std.ArrayList([]const u8) = .empty;
        try argv.appendSlice(arena, &.{ "log", tip, path });
        try argv.appendSlice(arena, form);
        const fast = try runZitEnv(arena, io, dir, env_fast, argv.items);
        const slow = try runZitEnv(arena, io, dir, env_slow, argv.items);
        const same = std.meta.eql(fast.term, slow.term) and
            std.mem.eql(u8, fast.stdout, slow.stdout) and std.mem.eql(u8, fast.stderr, slow.stderr);
        if (!same) {
            std.debug.print("\nlog {s} {s}: the byte descent answers differently\n--- parsed ---\n{s}{s}\n--- shipped ---\n{s}{s}\n", .{
                path, try std.mem.join(arena, " ", form), slow.stdout, slow.stderr, fast.stdout, fast.stderr,
            });
            return error.LogFormsDisagree;
        }
        try expectExitDiag(fast.term, 0, fast);
    };
}

/// A checkout history with every shape `log PATH` distinguishes: edits, a
/// rename, a new file at the renamed-away name, a branch merged back, a
/// delete, and a purged version. Padding files make a `--submanifest` store
/// several nodes deep. Returns the tip.
fn logShapesScene(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, k: ?[]const u8) ![]const u8 {
    if (k) |kk| _ = try renameRun(arena, io, dir, &.{}, &.{ "init", "--submanifest", kk }) else _ = try renameRun(arena, io, dir, &.{}, &.{"init"});
    try dir.createDir(io, "p", .default_dir);
    var i: usize = 0;
    while (i < 120) : (i += 1) {
        const name = try std.fmt.allocPrint(arena, "p/{d:0>3}.txt", .{i});
        try writeFile(io, dir, name, name);
    }
    try writeFile(io, dir, "f.txt", "f1\n");
    try writeFile(io, dir, "h.txt", "h1\n");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "add", "p", "f.txt", "h.txt" });
    _ = try commitHashDup(arena, io, dir, "seed");
    try writeFile(io, dir, "f.txt", "f2\n");
    _ = try commitHashDup(arena, io, dir, "f again");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "mv", "f.txt", "g.txt" });
    _ = try commitHashDup(arena, io, dir, "rename f to g");
    try writeFile(io, dir, "g.txt", "f2\ng\n");
    try writeFile(io, dir, "f.txt", "a new f\n");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "add", "f.txt" });
    const fork = try commitHashDup(arena, io, dir, "edit g, new f at the old name");
    try writeFile(io, dir, "h.txt", "h side\n");
    try writeFile(io, dir, "p/007.txt", "side\n");
    const side_res = try runCommitEnv(arena, io, dir, .{ .user = "u" }, &.{ "commit", "-m", "side", "--branch", "side" });
    try expectExitDiag(side_res.term, 0, side_res);
    const side = try checkinHash(side_res.stdout);
    _ = try renameRun(arena, io, dir, &.{}, &.{ "update", fork });
    try writeFile(io, dir, "g.txt", "f2\ng\ng2\n");
    _ = try commitForkDup(arena, io, dir, "trunk edits g");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "merge", side });
    _ = try commitHashDup(arena, io, dir, "merge side");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "rm", "--hard", "h.txt" });
    const tip = try commitHashDup(arena, io, dir, "drop h");
    // The purge takes g's oldest version, the seed's f, which no tip holds.
    const versions = try renameRun(arena, io, dir, &.{}, &.{ "log", tip, "g.txt", "-F", "json" });
    const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, versions, .{});
    const rows = doc.object.get("checkins").?.array.items;
    try std.testing.expect(rows.len >= 3);
    _ = try renameRun(arena, io, dir, &.{}, &.{ "purge", "artifacts", "--force", rows[rows.len - 1].object.get("uuid").?.string });
    return tip;
}

/// A `log PATH -F json` document's rows, each as the JSON it was written
/// as, and its `cursor` (null when absent or null).
const LogPage = struct { rows: []const []const u8, cursor: ?[]const u8 };

fn logPageOf(arena: std.mem.Allocator, doc_text: []const u8) !LogPage {
    const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, doc_text, .{});
    const items = doc.object.get("checkins").?.array.items;
    const rows = try arena.alloc([]const u8, items.len);
    for (items, rows) |item, *row| row.* = try std.json.Stringify.valueAlloc(arena, item, .{});
    const cursor: ?[]const u8 = if (doc.object.get("cursor")) |c| switch (c) {
        .string => |text| text,
        else => null,
    } else null;
    return .{ .rows = rows, .cursor = cursor };
}

/// `log tip PATH ARGS`, answered from the file index and by
/// reconstruction; the two must agree byte for byte. Returns stdout.
fn logBothWays(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, argv: []const []const u8) ![]const u8 {
    const indexed = try renameRun(arena, io, dir, &.{}, argv);
    const plain = try renameRun(arena, io, dir, &no_index, argv);
    if (!std.mem.eql(u8, indexed, plain)) {
        std.debug.print("\n{s}: differs with the index\n--- reconstructed ---\n{s}--- indexed ---\n{s}", .{ try std.mem.join(arena, " ", argv), plain, indexed });
        return error.IndexChangedTheAnswer;
    }
    return indexed;
}

test "cli log PATH: --offset pages and --cursor pages each add up to the whole history, indexed and reconstructed alike" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    _ = try logShapesScene(arena, io, tmp.dir, null);
    // A change of mode alone is in the file index's change set but lists no
    // row, so a page that skipped by the index's count would drift.
    try chmodFile(io, tmp.dir, "g.txt", 0o755);
    _ = try commitHashDup(arena, io, tmp.dir, "g executable");
    try writeFile(io, tmp.dir, "g.txt", "f2\ng\ng2\ng3\n");
    const tip = try commitHashDup(arena, io, tmp.dir, "g once more");

    for ([_][]const u8{ "g.txt", "f.txt", "h.txt", "p/007.txt" }) |path| {
        for ([_][]const []const u8{ &.{}, &.{"--no-follow"} }) |follow| {
            var base: std.ArrayList([]const u8) = .empty;
            try base.appendSlice(arena, &.{ "log", tip, path });
            try base.appendSlice(arena, follow);
            const whole_json = try logPageOf(arena, try logBothWays(arena, io, tmp.dir, try std.mem.concat(arena, []const u8, &.{ base.items, &.{ "-F", "json" } })));
            try std.testing.expect(whole_json.cursor == null);
            const whole_text = try logBothWays(arena, io, tmp.dir, base.items);
            var lines: std.ArrayList([]const u8) = .empty;
            var it = std.mem.splitScalar(u8, whole_text, '\n');
            while (it.next()) |line| if (line.len != 0) try lines.append(arena, line);
            try std.testing.expectEqual(whole_json.rows.len, lines.items.len);

            for ([_]usize{ 1, 2, 3 }) |k| {
                const n = try std.fmt.allocPrint(arena, "{d}", .{k});
                // By offset: page o holds rows o..o+k, in text and JSON.
                var offset: usize = 0;
                while (offset <= whole_json.rows.len) : (offset += k) {
                    const o = try std.fmt.allocPrint(arena, "{d}", .{offset});
                    const json = try logPageOf(arena, try logBothWays(arena, io, tmp.dir, try std.mem.concat(arena, []const u8, &.{ base.items, &.{ "-F", "json", "--offset", o, "-n", n } })));
                    const end = @min(whole_json.rows.len, offset + k);
                    try std.testing.expectEqual(end - offset, json.rows.len);
                    for (whole_json.rows[offset..end], json.rows) |want, got| try std.testing.expectEqualStrings(want, got);
                    try std.testing.expectEqual(end < whole_json.rows.len, json.cursor != null);
                    const text = try logBothWays(arena, io, tmp.dir, try std.mem.concat(arena, []const u8, &.{ base.items, &.{ "--offset", o, "-n", n } }));
                    const want_text = if (end == offset) "" else try std.mem.concat(arena, u8, &.{ try std.mem.join(arena, "\n", lines.items[offset..end]), "\n" });
                    try std.testing.expectEqualStrings(want_text, text);
                }
                // By cursor: each page starts after the last row of the one before.
                var got: std.ArrayList([]const u8) = .empty;
                var cursor: ?[]const u8 = null;
                var pages: usize = 0;
                while (true) : (pages += 1) {
                    try std.testing.expect(pages <= whole_json.rows.len);
                    var argv: std.ArrayList([]const u8) = .empty;
                    try argv.appendSlice(arena, base.items);
                    try argv.appendSlice(arena, &.{ "-F", "json", "-n", n });
                    if (cursor) |c| try argv.appendSlice(arena, &.{ "--cursor", c });
                    const json = try logPageOf(arena, try logBothWays(arena, io, tmp.dir, argv.items));
                    try got.appendSlice(arena, json.rows);
                    cursor = json.cursor orelse break;
                    // The text form resumes at the same row.
                    const text = try logBothWays(arena, io, tmp.dir, try std.mem.concat(arena, []const u8, &.{ base.items, &.{ "-n", n, "--cursor", cursor.? } }));
                    const from = got.items.len;
                    const to = @min(lines.items.len, from + k);
                    try std.testing.expectEqualStrings(try std.mem.concat(arena, u8, &.{ try std.mem.join(arena, "\n", lines.items[from..to]), "\n" }), text);
                }
                try std.testing.expectEqual(whole_json.rows.len, got.items.len);
                for (whole_json.rows, got.items) |want, row| try std.testing.expectEqualStrings(want, row);
            }
        }
    }

    // A cursor names its walk: another path's is refused, as the daemon
    // refuses it, and neither paging option means anything without PATH.
    const first = try logPageOf(arena, try renameRun(arena, io, tmp.dir, &.{}, &.{ "log", tip, "g.txt", "-F", "json", "-n", "1" }));
    const wrong = try runZit(arena, io, tmp.dir, &.{ "log", tip, "p/007.txt", "--cursor", first.cursor.? });
    try expectExit(wrong.term, 4);
    try std.testing.expect(std.mem.indexOf(u8, wrong.stderr, "cursor invalid") != null);
    const junk = try runZit(arena, io, tmp.dir, &.{ "log", tip, "g.txt", "--cursor", "nope" });
    try expectExit(junk.term, 4);
    const bare = try runZit(arena, io, tmp.dir, &.{ "log", tip, "--offset", "1" });
    try expectExit(bare.term, 2);
    try std.testing.expect(std.mem.indexOf(u8, bare.stderr, "need PATH") != null);
}

test "cli log PATH: reading one line of each tree node gives the history parsing every node gives, every form, flat and k=1,3,7" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const io = std.testing.io;
    for ([_]?[]const u8{ null, "1", "3", "7" }) |k| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        const tip = try logShapesScene(arena, io, tmp.dir, k);
        if (k != null) {
            // A tree store, not a flat one that merely accepted the flag.
            const raw = try renameRun(arena, io, tmp.dir, &.{}, &.{ "artifact", tip });
            try std.testing.expect(std.mem.indexOf(u8, raw, "\nS ") != null);
        }
        try expectLogFormsAgree(arena, io, tmp.dir, tip, &.{ "f.txt", "g.txt", "h.txt", "p/007.txt", "p/119.txt", "never.txt" });
    }
}

/// `logShapesScene`, then a second side branch merged back with edits on
/// both sides, a delete and a re-add at the same name, and two check-ins
/// stacked on the tip with a parent the store never received: one names it
/// as a merge parent, one as its primary, which the file index cannot
/// know. Check-ins land within a second of each other, so the order's tie
/// breaks are exercised too. Returns the tip, the two stacked check-ins,
/// and two check-ins that deleted f.txt, where a following walk starts
/// before it has met the file.
fn logPagesScene(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, k: ?[]const u8) ![5][]const u8 {
    const shapes = try logShapesScene(arena, io, dir, k);
    try writeFile(io, dir, "g.txt", "side2 g\n");
    try writeFile(io, dir, "f.txt", "side2 f\n");
    const side_res = try runCommitEnv(arena, io, dir, .{ .user = "u" }, &.{ "commit", "-m", "side2", "--branch", "side2" });
    try expectExitDiag(side_res.term, 0, side_res);
    const side = try arena.dupe(u8, try checkinHash(side_res.stdout));
    _ = try renameRun(arena, io, dir, &.{}, &.{ "update", shapes });
    try writeFile(io, dir, "g.txt", "trunk g again\n");
    _ = try commitForkDup(arena, io, dir, "trunk g again");
    try writeFile(io, dir, "f.txt", "trunk f again\n");
    _ = try commitHashDup(arena, io, dir, "trunk f again");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "update", side });
    try writeFile(io, dir, "g.txt", "side2 g again\n");
    _ = try commitHashDup(arena, io, dir, "side2 g again");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "update", "trunk" });
    // Both sides changed both files: the merge conflicts, and the
    // resolution is written over them.
    const mg = try runZitEnv(arena, io, dir, &.{}, &.{ "merge", "side2" });
    try std.testing.expect(std.meta.eql(mg.term, std.process.Child.Term{ .exited = 1 }));
    try writeFile(io, dir, "g.txt", "merged g\n");
    try writeFile(io, dir, "f.txt", "merged f\n");
    _ = try commitHashDup(arena, io, dir, "merge side2");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "rm", "--hard", "f.txt" });
    const dropped = try commitHashDup(arena, io, dir, "drop f");
    try writeFile(io, dir, "f.txt", "f once more\n");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "add", "f.txt" });
    const tip = try commitHashDup(arena, io, dir, "f once more");
    // f.txt renamed away, a new f.txt, and that one deleted: from the
    // delete, every check-in down to the rename changed f.txt, so nothing
    // between tells the walk it has met the file before the rename.
    _ = try renameRun(arena, io, dir, &.{}, &.{ "mv", "f.txt", "k.txt" });
    _ = try commitHashDup(arena, io, dir, "rename f to k");
    try writeFile(io, dir, "f.txt", "f after k\n");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "add", "f.txt" });
    _ = try commitHashDup(arena, io, dir, "f after k");
    _ = try renameRun(arena, io, dir, &.{}, &.{ "rm", "--hard", "f.txt" });
    const unmet = try commitHashDup(arena, io, dir, "drop f after k");
    const missing = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
    const merged = try appendSyntheticCheckin(arena, io, dir, "phantom merge parent", try std.fmt.allocPrint(arena, "{s} {s}", .{ tip, missing }));
    const orphaned = try appendSyntheticCheckin(arena, io, dir, "phantom primary parent", try std.fmt.allocPrint(arena, "{s} {s}", .{ missing, tip }));
    return .{ tip, merged, orphaned, dropped, unmet };
}

/// `-n K` for every K at each of `logPagesScene`'s roots, from the file index,
/// against the whole list reconstruction gives: each is its first K rows.
fn expectLogPagesAgree(arena: std.mem.Allocator, io: std.Io, k: ?[]const u8) !void {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    const roots = try logPagesScene(arena, io, tmp.dir, k);
    for (roots) |root| for ([_][]const u8{ "f.txt", "g.txt", "k.txt" }) |path| for ([_]bool{ true, false }) |follow| {
        var base: std.ArrayList([]const u8) = .empty;
        try base.appendSlice(arena, &.{ "log", root, path, "-F", "json" });
        if (!follow) try base.append(arena, "--no-follow");
        const whole = try renameRun(arena, io, tmp.dir, &no_index, base.items);
        try std.testing.expectEqualStrings(whole, try renameRun(arena, io, tmp.dir, &.{}, base.items));
        const want = (try std.json.parseFromSliceLeaky(std.json.Value, arena, whole, .{})).object.get("checkins").?.array.items;
        for (1..want.len + 2) |limit| {
            var argv: std.ArrayList([]const u8) = .empty;
            try argv.appendSlice(arena, base.items);
            try argv.appendSlice(arena, &.{ "-n", try std.fmt.allocPrint(arena, "{d}", .{limit}) });
            const page = try renameRun(arena, io, tmp.dir, &.{}, argv.items);
            const got = (try std.json.parseFromSliceLeaky(std.json.Value, arena, page, .{})).object.get("checkins").?.array.items;
            try std.testing.expectEqual(@min(limit, want.len), got.len);
            for (want[0..got.len], got) |w, g| try std.testing.expectEqualStrings(
                try std.json.Stringify.valueAlloc(arena, w, .{}),
                try std.json.Stringify.valueAlloc(arena, g, .{}),
            );
        }
    };
    // Every form, text and --long included, at the roots below the tip.
    for (roots[1..]) |root| try expectLogFormsAgree(arena, io, tmp.dir, root, &.{ "f.txt", "g.txt", "h.txt", "k.txt", "p/007.txt" });
}

test "cli log PATH: every -n page from the file index is the page reconstruction gives, branchy, renamed, purged and phantom, flat" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    try expectLogPagesAgree(arena_state.allocator(), std.testing.io, null);
}

test "cli log PATH: every -n page from the file index is the page reconstruction gives, branchy, renamed, purged and phantom, k=7" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    try expectLogPagesAgree(arena_state.allocator(), std.testing.io, "7");
}

/// A check-in written straight into the store under `algo`'s names: the
/// SHA-1 and delta-manifest dialects a Fossil import carries and `commit`
/// never mints.
fn logDialectCheckin(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, algo: artifact.HashAlgo, body: []const u8) ![]const u8 {
    return appendArtifactAs(arena, io, dir, algo, try withZCard(arena, body));
}

test "cli log PATH: SHA-1 names and delta manifests give the same history either way, every form" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const io = std.testing.io;
    for ([_]artifact.HashAlgo{ .sha1, .sha3_256 }) |algo| for ([_]bool{ false, true }) |delta| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        const d = tmp.dir;
        _ = try renameRun(arena, io, d, &.{}, &.{"init"});
        const a1 = try appendArtifactAs(arena, io, d, algo, "a1\n");
        const a2 = try appendArtifactAs(arena, io, d, algo, "a2\n");
        const a3 = try appendArtifactAs(arena, io, d, algo, "a3\n");
        const b1 = try appendArtifactAs(arena, io, d, algo, "b1\n");
        const b2 = try appendArtifactAs(arena, io, d, algo, "b2\n");
        const c0 = try logDialectCheckin(arena, io, d, algo, try std.fmt.allocPrint(arena, "C c0\nD 2020-01-01T00:00:00\nF a.txt {s}\nF b.txt {s}\nU u\n", .{ a1, b1 }));
        // Each check-in's whole file set, then the cards a delta on c0 carries.
        const c1 = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c1", "2020-01-02T00:00:00", &.{ .{ "a.txt", a2 }, .{ "b.txt", b1 } }, &.{.{ "a.txt", a2 }}, &.{c0}));
        const c2 = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c2 drops b", "2020-01-03T00:00:00", &.{.{ "a.txt", a2 }}, &.{ .{ "a.txt", a2 }, .{ "b.txt", null } }, &.{c1}));
        const c3 = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c3 side", "2020-01-04T00:00:00", &.{ .{ "a.txt", a2 }, .{ "b.txt", b2 } }, &.{ .{ "a.txt", a2 }, .{ "b.txt", b2 } }, &.{c1}));
        const c4 = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c4 merge", "2020-01-05T00:00:00", &.{ .{ "a.txt", a3 }, .{ "b.txt", b2 } }, &.{ .{ "a.txt", a3 }, .{ "b.txt", b2 } }, &.{ c2, c3 }));
        const c5 = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c5 drops a", "2020-01-06T00:00:00", &.{.{ "b.txt", b2 }}, &.{ .{ "a.txt", null }, .{ "b.txt", b2 } }, &.{c4}));
        const tip = try logDialectCheckin(arena, io, d, algo, try dialectBody(arena, delta, c0, "c6 a again", "2020-01-07T00:00:00", &.{ .{ "a.txt", a1 }, .{ "b.txt", b2 } }, &.{.{ "b.txt", b2 }}, &.{c5}));
        try expectLogFormsAgree(arena, io, d, tip, &.{ "a.txt", "b.txt", "never.txt" });
    };
}

const DialectFile = struct { []const u8, ?[]const u8 };

/// A check-in body: the whole file set, or (delta) a B card on `baseline`
/// and the cards that differ from it, a null hash deleting the name.
fn dialectBody(
    arena: std.mem.Allocator,
    delta: bool,
    baseline: []const u8,
    comment: []const u8,
    date: []const u8,
    full: []const DialectFile,
    against_baseline: []const DialectFile,
    parents: []const []const u8,
) ![]const u8 {
    var b: std.ArrayList(u8) = .empty;
    if (delta) try b.print(arena, "B {s}\n", .{baseline});
    const enc = try std.mem.replaceOwned(u8, arena, comment, " ", "\\s");
    try b.print(arena, "C {s}\nD {s}\n", .{ enc, date });
    for (if (delta) against_baseline else full) |f| {
        if (f[1]) |h| try b.print(arena, "F {s} {s}\n", .{ f[0], h }) else try b.print(arena, "F {s}\n", .{f[0]});
    }
    try b.appendSlice(arena, "P");
    for (parents) |p| try b.print(arena, " {s}", .{p});
    try b.appendSlice(arena, "\nU u\n");
    return b.items;
}