Skip to content
zit Artifact [af9615e8b7]
Login

Artifact [af9615e8b7]

Artifact af9615e8b76d259d267cf0eaf71d4f96c13ae28bf0fde2d6fb2ae6a38aa3baf4:


const std = @import("std");
const checkout = @import("zit").checkout;
const support = @import("support.zig");
const MergeDiamond = support.MergeDiamond;
const addManaged = support.addManaged;
const buildMergeDiamond = support.buildMergeDiamond;
const checkinHash = support.checkinHash;
const commitHashDup = support.commitHashDup;
const expectExit = support.expectExit;
const expectExitDiag = support.expectExitDiag;
const expectFileContent = support.expectFileContent;
const expectManaged = support.expectManaged;
const fileExists = support.fileExists;
const fileIndexUnknownOf = support.fileIndexUnknownOf;
const fileIndexWalkOf = support.fileIndexWalkOf;
const freeResult = support.freeResult;
const freshLoopbackPort = support.freshLoopbackPort;
const initRepo = support.initRepo;
const initTreeRepo = support.initTreeRepo;
const manifestReadsOf = support.manifestReadsOf;
const nCardOf = support.nCardOf;
const runCommitEnv = support.runCommitEnv;
const runZit = support.runZit;
const runZitEnv = support.runZitEnv;
const runZitStdin = support.runZitStdin;
const spawnServe = support.spawnServe;
const tipHashOf = support.tipHashOf;
const waitForListen = support.waitForListen;
const writeFile = support.writeFile;

test "cli: a bare -- ends the options, so a path beginning with a dash is reachable" {
    // Without an end-of-options marker such a file could not be named at all:
    // passed bare it parses as a flag, and `./-x.txt` parses fine and then
    // matches nothing, because a path is compared literally against the
    // check-in's file list. A forge serving such a repository answered 500 for
    // every content route on that file.
    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, "-x.txt", "dash\n");
    try writeFile(io, tmp.dir, "plain.txt", "plain\n");
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "add", "--", "-x.txt", "plain.txt" });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
    }
    const tip = try commitHashDup(gpa, io, tmp.dir, "dash name");
    defer gpa.free(tip);

    // The verb the issue was filed against, and its two neighbours.
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "cat", "--", "-x.txt", "trunk" });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
        try std.testing.expectEqualStrings("dash\n", r.stdout);
    }
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "annotate", "--", "-x.txt" });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
        try std.testing.expect(std.mem.indexOf(u8, r.stdout, "dash") != null);
    }
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "log", "--", "trunk", "-x.txt" });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
        try std.testing.expect(std.mem.indexOf(u8, r.stdout, tip) != null);
    }
    // Before the marker the flag still wins, which is what makes the marker
    // the only escape rather than one of two.
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "cat", "-x.txt", "trunk" });
        defer freeResult(gpa, &r);
        try expectExit(r.term, 2);
        try std.testing.expect(std.mem.indexOf(u8, r.stderr, "unknown option") != null);
    }
    // A second `--` is an operand, not another marker.
    {
        var r = try runZit(gpa, io, tmp.dir, &.{ "cat", "--", "--", "trunk" });
        defer freeResult(gpa, &r);
        try expectExit(r.term, 1);
        try std.testing.expect(std.mem.indexOf(u8, r.stderr, "not in the check-in") != null);
    }
}

test "cli: the warm image and a cold derive resolve the branch-walk forms identically" {
    // The regression this pins is a SILENT one. `branchValueOf` read tagxref
    // directly, and tagxref is empty on an image backing -- so every check-in
    // looked like it was on `main_branch`, the §8.4 walk never left the branch,
    // and `start:`/`root:` answered with a check-in from somewhere else
    // entirely. Exit 0, no diagnostic, wrong listing.
    //
    // Compared against `--no-cache`, which forces the full-log derive: the two
    // paths must agree byte for byte. Edge equality alone does not catch this
    // (the edges were right; the branch identity read beside them was not), so
    // it is asserted here through the real binary rather than in a unit view.
    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);

    // A real second branch, so the walk has somewhere to stop. Without one
    // every rid shares a branch and the comparison proves nothing.
    try writeFile(io, tmp.dir, "b.txt", "two\n");
    try addManaged(gpa, io, tmp.dir, &.{"b.txt"});
    var c2 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "side", "--branch", "feature" });
    defer freeResult(gpa, &c2);
    try expectExit(c2.term, 0);

    try writeFile(io, tmp.dir, "c.txt", "three\n");
    try addManaged(gpa, io, tmp.dir, &.{"c.txt"});
    var c3 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "more" });
    defer freeResult(gpa, &c3);
    try expectExit(c3.term, 0);

    // Warm the cache so the first comparison runs against a real image rather
    // than against a derive that happens to write one.
    var warm = try runZit(gpa, io, tmp.dir, &.{ "ls", "tip" });
    defer freeResult(gpa, &warm);
    try expectExitDiag(warm.term, 0, warm);

    for ([_][]const u8{ "tip", "feature", "start:feature", "root:feature", "trunk", "start:trunk" }) |sel| {
        var img = try runZit(gpa, io, tmp.dir, &.{ "ls", sel });
        defer freeResult(gpa, &img);
        var derived = try runZit(gpa, io, tmp.dir, &.{ "ls", sel, "--no-cache" });
        defer freeResult(gpa, &derived);
        try expectExitDiag(img.term, 0, img);
        try expectExitDiag(derived.term, 0, derived);
        // Both the listing AND that it is not empty: two empty listings agree
        // for the wrong reason, which is how the original defect passed.
        try std.testing.expect(img.stdout.len > 0);
        try std.testing.expectEqualStrings(derived.stdout, img.stdout);

        // `info` reports the resolved check-in itself, so a walk landing on the
        // wrong rid shows up here even when the two file listings coincide.
        var i_img = try runZit(gpa, io, tmp.dir, &.{ "info", sel });
        defer freeResult(gpa, &i_img);
        var i_der = try runZit(gpa, io, tmp.dir, &.{ "info", sel, "--no-cache" });
        defer freeResult(gpa, &i_der);
        try expectExitDiag(i_img.term, 0, i_img);
        try std.testing.expectEqualStrings(i_der.stdout, i_img.stdout);
    }
}

test "cli -n stays --dry-run on the working-tree verbs: the overload is per-verb" {
    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, "f.txt", "x\n");

    // `add -n f.txt` is a DRY RUN: it must not consume "f.txt" as a limit
    // value, and must leave the managed set empty.
    var res = try runZit(gpa, io, tmp.dir, &.{ "add", "-n", "f.txt" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    try expectManaged(gpa, io, tmp.dir, &.{});
}

// ---------------------------------------------------------------------------
// Consolidation Task 6 Step 8: after a full verb sweep the checkout root
// carries exactly the three live reserved names plus working files — no
// absorbed sibling, no legacy leftover, no stranded scratch. Run on a fresh
// checkout AND on one migrated mid-life from the legacy generation.
// ---------------------------------------------------------------------------

fn expectConsolidatedRoot(io: std.Io, dir: std.Io.Dir, working: []const []const u8) !void {
    // Reopened for iteration: the caller's handle may lack iterate rights,
    // which Linux enforces at readdir time (macOS does not).
    var it_dir = try dir.openDir(io, ".", .{ .iterate = true });
    defer it_dir.close(io);
    var entries = it_dir.iterate();
    outer: while (try entries.next(io)) |entry| {
        for ([_][]const u8{ ".zit", ".zit-checkout", ".zit-cache" }) |ok| {
            if (std.mem.eql(u8, entry.name, ok)) continue :outer;
        }
        for (working) |w| {
            if (std.mem.eql(u8, entry.name, w)) continue :outer;
        }
        std.debug.print("unexpected root entry after verb sweep: {s}\n", .{entry.name});
        return error.UnexpectedRootEntry;
    }
}

fn okZit(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, args: []const []const u8) !void {
    var res = try runZit(gpa, io, dir, args);
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
}

fn okCommit(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, msg: []const u8) !void {
    var res = try runCommitEnv(gpa, io, dir, .{ .user = "u" }, &.{ "commit", "-m", msg });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
}

/// Every mutating and reading verb at least once, ending with a clean tree:
/// merge+commit, add/mv/rm (each committed), update + undo/redo, revert,
/// bisect record+reset, status/extras/clean.
fn verbSweepBody(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fx: *const MergeDiamond) !void {
    try okZit(gpa, io, dir, &.{ "merge", fx.other });
    try okCommit(gpa, io, dir, "merged");

    try writeFile(io, dir, "extra.txt", "extra\n");
    try okZit(gpa, io, dir, &.{ "add", "extra.txt" });
    try okCommit(gpa, io, dir, "add extra");
    try okZit(gpa, io, dir, &.{ "mv", "extra.txt", "moved.txt" });
    try okCommit(gpa, io, dir, "move extra");
    // Plain rm untracks and leaves the working file — which gives `extras`
    // something to report and `clean` something to sweep below.
    try okZit(gpa, io, dir, &.{ "rm", "moved.txt" });
    try okCommit(gpa, io, dir, "drop moved");

    try okZit(gpa, io, dir, &.{ "update", fx.base });
    try okZit(gpa, io, dir, &.{"undo"});
    try okZit(gpa, io, dir, &.{"redo"});
    try okZit(gpa, io, dir, &.{"undo"}); // end back at the head

    try writeFile(io, dir, "poem", "scribble\n");
    try okZit(gpa, io, dir, &.{ "revert", "poem" });

    try okZit(gpa, io, dir, &.{ "bisect", "bad", fx.current });
    try okZit(gpa, io, dir, &.{ "bisect", "reset" });

    try okZit(gpa, io, dir, &.{"status"});
    try okZit(gpa, io, dir, &.{"extras"});
    try okZit(gpa, io, dir, &.{ "clean", "--force" }); // flagless clean refuses while extras exist (B-clean-1)
}

/// Rewrites a container-generation checkout as the LEGACY generation an old
/// binary would have left: each section's raw bytes become the sibling file
/// (the payload formats are identical) and the checkout section's TLV record
/// becomes `.zit-checkout` itself (§8's byte-1 dispatch reads it as legacy).
fn devolveCheckoutToLegacy(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !void {
    inline for (.{
        .{ checkout.SectionTag.managed, ".zit-managed" },
        .{ checkout.SectionTag.undo, ".zit-undo" },
        .{ checkout.SectionTag.bisect, ".zit-bisect" },
    }) |pair| {
        if (try checkout.readSectionAlloc(gpa, io, dir, pair[0])) |bytes| {
            defer gpa.free(bytes);
            try writeFile(io, dir, pair[1], bytes);
        }
    }
    const record = (try checkout.readSectionAlloc(gpa, io, dir, .checkout)).?;
    defer gpa.free(record);
    try writeFile(io, dir, checkout.filename, record);
}

test "consolidation: a full verb sweep on a fresh checkout leaves exactly { .zit, .zit-checkout, .zit-cache } + working files" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    var fx = try buildMergeDiamond(gpa, io, tmp.dir, "A\nB\nC\n", "A\nB\nC1\n", "A1\nB\nC\n");
    defer fx.deinit(gpa);
    try verbSweepBody(gpa, io, tmp.dir, &fx);
    try expectConsolidatedRoot(io, tmp.dir, &.{"poem"});
}

test "consolidation: the same sweep on a migrated legacy checkout converges to the same root" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    var fx = try buildMergeDiamond(gpa, io, tmp.dir, "A\nB\nC\n", "A\nB\nC1\n", "A1\nB\nC\n");
    defer fx.deinit(gpa);
    try devolveCheckoutToLegacy(gpa, io, tmp.dir);
    try std.testing.expect(fileExists(io, tmp.dir, ".zit-managed")); // genuinely legacy before the sweep

    try verbSweepBody(gpa, io, tmp.dir, &fx);
    try expectConsolidatedRoot(io, tmp.dir, &.{"poem"});
    // The absorbed siblings were folded in and swept, never resurrected.
    try std.testing.expect(!fileExists(io, tmp.dir, ".zit-managed"));
    try std.testing.expect(!fileExists(io, tmp.dir, ".zit-undo"));
    try std.testing.expect(!fileExists(io, tmp.dir, ".zit-bisect"));
}

test "consolidation: every legacy leftover on an old checkout migrates or surfaces, and clean ends the story" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    // An old checkout: legacy-generation control files plus every retired
    // leftover a previous release could have stranded at the root.
    var fx = try buildMergeDiamond(gpa, io, tmp.dir, "A\nB\nC\n", "A\nB\nC1\n", "A1\nB\nC\n");
    defer fx.deinit(gpa);
    try devolveCheckoutToLegacy(gpa, io, tmp.dir);
    try writeFile(io, tmp.dir, ".zit-vstat", "stale sidecar");
    try writeFile(io, tmp.dir, ".zit-pack-tmp", "stale pack temp");
    try writeFile(io, tmp.dir, ".zit-import-map.jsonl", "{}");
    try tmp.dir.createDir(io, ".zit-update-txn-stale", .default_dir);
    try writeFile(io, tmp.dir, ".zit-update-txn-stale/f", "x");
    try tmp.dir.createDir(io, ".zit-import-tmp-stale", .default_dir);
    try writeFile(io, tmp.dir, ".zit-import-tmp-stale/f", "x");
    try tmp.dir.createDir(io, "refs", .default_dir);
    try writeFile(io, tmp.dir, "refs/heads-main", "deadbeef");

    // One mutation migrates the authoritative siblings into the container,
    // losslessly (the tracked file's dirty state survives via revert below).
    try writeFile(io, tmp.dir, "poem", "dirty\n");
    try okZit(gpa, io, tmp.dir, &.{ "revert", "poem" });
    try std.testing.expect(!fileExists(io, tmp.dir, ".zit-managed"));
    try expectManaged(gpa, io, tmp.dir, &.{"poem"}); // membership survived the fold

    // The retired leftovers lost their reservations: extras SEES them...
    var ex = try runZit(gpa, io, tmp.dir, &.{ "extras", "--dotfiles" });
    defer freeResult(gpa, &ex);
    try expectExit(ex.term, 0);
    for ([_][]const u8{ ".zit-vstat", ".zit-pack-tmp", ".zit-import-map.jsonl", ".zit-update-txn-stale/f", ".zit-import-tmp-stale/f", "refs/heads-main" }) |name| {
        try std.testing.expect(std.mem.indexOf(u8, ex.stdout, name) != null);
    }
    // ...and clean deletes them. Directory husks survive because clean
    // sweeps files, not directories — a general clean property, the same for
    // any emptied untracked directory — so they are allowed here while every
    // legacy FILE must be gone.
    try okZit(gpa, io, tmp.dir, &.{ "clean", "--force", "--dotfiles" });
    try expectConsolidatedRoot(io, tmp.dir, &.{ "poem", "refs", ".zit-update-txn-stale", ".zit-import-tmp-stale" });
    for ([_][]const u8{ ".zit-vstat", ".zit-pack-tmp", ".zit-import-map.jsonl", ".zit-update-txn-stale/f", ".zit-import-tmp-stale/f", "refs/heads-main" }) |name| {
        try std.testing.expect(!fileExists(io, tmp.dir, name));
    }
    try expectManaged(gpa, io, tmp.dir, &.{"poem"});
}

test "cli whole-tree reads on a structural horizon and cone clone fetch the nodes a zit origin withheld, or refuse naming the cone" {
    // Goal: a zit origin answering a cone clone withholds the sub-manifest
    // nodes whose slots cannot reach the cone, so ls, cat of an out-of-cone
    // path, tarball and merge each meet a tree the store holds in part. With
    // a saved remote each fetches the nodes once and answers; with none each
    // refuses naming the sparse cone and both remedies. Method: a real origin
    // whose tree is wide enough to split into nodes, a fresh clone per verb.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var src_tmp = std.testing.tmpDir(.{});
    defer src_tmp.cleanup();
    try initRepo(gpa, io, src_tmp.dir);
    var en = try runZit(gpa, io, src_tmp.dir, &.{ "submanifest", "enable", "--k", "1" });
    defer freeResult(gpa, &en);
    try expectExitDiag(en.term, 0, en);
    for ([_][]const u8{ "src", "docs", "kit" }) |d| {
        try src_tmp.dir.createDir(io, d, .default_dir);
        for (0..40) |i| {
            var name_buf: [32]u8 = undefined;
            const name = try std.fmt.bufPrint(&name_buf, "{s}/f{d}", .{ d, i });
            try writeFile(io, src_tmp.dir, name, name);
        }
    }
    try addManaged(gpa, io, src_tmp.dir, &.{ "src", "docs", "kit" });
    var c1 = try runCommitEnv(gpa, io, src_tmp.dir, .{ .user = "u" }, &.{ "commit", "--no-submanifest-advice", "-m", "one" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);
    const base = try tipHashOf(gpa, io, src_tmp.dir, "trunk");
    defer gpa.free(base);
    try writeFile(io, src_tmp.dir, "src/f1", "trunk side");
    var c2 = try runCommitEnv(gpa, io, src_tmp.dir, .{ .user = "u" }, &.{ "commit", "--no-submanifest-advice", "-m", "two" });
    defer freeResult(gpa, &c2);
    try expectExitDiag(c2.term, 0, c2);
    var back = try runZit(gpa, io, src_tmp.dir, &.{ "update", base });
    defer freeResult(gpa, &back);
    try expectExitDiag(back.term, 0, back);
    try writeFile(io, src_tmp.dir, "src/f2", "feature side");
    var c3 = try runCommitEnv(gpa, io, src_tmp.dir, .{ .user = "u" }, &.{ "commit", "--no-submanifest-advice", "--branch", "feature", "-m", "feat" });
    defer freeResult(gpa, &c3);
    try expectExitDiag(c3.term, 0, c3);

    const port = try freshLoopbackPort(io);
    var server = try spawnServe(gpa, io, src_tmp.dir, port);
    defer server.kill(io);
    try waitForListen(io, port);
    const url = try std.fmt.allocPrint(gpa, "http://127.0.0.1:{d}/", .{port});
    defer gpa.free(url);
    const horizon_arg = try std.fmt.allocPrint(gpa, "--horizon={s}", .{base});
    defer gpa.free(horizon_arg);

    const Verb = enum { ls, cat, tarball, merge };
    for ([_]bool{ true, false }) |remote| {
        for (std.enums.values(Verb)) |verb| {
            errdefer std.debug.print("verb: {s}, remote: {}\n", .{ @tagName(verb), remote });
            var tmp_b = std.testing.tmpDir(.{});
            defer tmp_b.cleanup();
            var clone = try runZit(gpa, io, tmp_b.dir, &.{ "clone", horizon_arg, "--horizon-rule=descendants", "--structural", "--cone=src", url, "repo" });
            defer freeResult(gpa, &clone);
            try expectExitDiag(clone.term, 0, clone);
            var b_dir = try tmp_b.dir.openDir(io, "repo", .{});
            defer b_dir.close(io);
            if (!remote) {
                var unset = try runZit(gpa, io, b_dir, &.{ "remote", "--unset" });
                defer freeResult(gpa, &unset);
                try expectExitDiag(unset.term, 0, unset);
            }
            const args: []const []const u8 = switch (verb) {
                .ls => &.{"ls"},
                .cat => &.{ "cat", "docs/f1" },
                .tarball => &.{ "tarball", "trunk", "out.tar.gz", "--include", "src/*" },
                .merge => &.{ "merge", "feature" },
            };
            var run = try runZit(gpa, io, b_dir, args);
            defer freeResult(gpa, &run);
            const fetching = std.mem.count(u8, run.stderr, "elided by the store's sparse cone; fetching from the saved remote");
            if (!remote) {
                try expectExitDiag(run.term, 1, run);
                try std.testing.expectEqual(@as(usize, 0), fetching);
                try std.testing.expect(std.mem.indexOf(u8, run.stderr, "elided by the store's sparse cone and no remote is saved") != null);
                try std.testing.expect(std.mem.indexOf(u8, run.stderr, "'zit remote URL'") != null);
                try std.testing.expect(std.mem.indexOf(u8, run.stderr, "'zit cone add PATH'") != null);
                continue;
            }
            try std.testing.expectEqual(@as(usize, 1), fetching);
            try std.testing.expect(std.mem.indexOf(u8, run.stderr, "baseline") == null);
            switch (verb) {
                .ls => {
                    try expectExitDiag(run.term, 0, run);
                    try std.testing.expect(std.mem.indexOf(u8, run.stdout, "docs/f1\n") != null);
                    try std.testing.expect(std.mem.indexOf(u8, run.stdout, "pull from") == null);
                    // The fetched nodes are kept: a second listing is local.
                    var again = try runZit(gpa, io, b_dir, &.{"ls"});
                    defer freeResult(gpa, &again);
                    try expectExitDiag(again.term, 0, again);
                    try std.testing.expectEqualStrings(run.stdout, again.stdout);
                    try std.testing.expect(std.mem.indexOf(u8, again.stderr, "fetching") == null);
                },
                // The tree now answers; the file's bytes lie outside the
                // store cone, which the refusal names.
                .cat => {
                    try expectExitDiag(run.term, 8, run);
                    try std.testing.expect(std.mem.indexOf(u8, run.stderr, "content for 'docs/f1' is elided by this store's sparse cone") != null);
                },
                .tarball => {
                    try expectExitDiag(run.term, 0, run);
                    try std.testing.expect(fileExists(io, b_dir, "out.tar.gz"));
                },
                .merge => {
                    try expectExitDiag(run.term, 0, run);
                    try expectFileContent(gpa, io, b_dir, "src/f2", "feature side");
                    try expectFileContent(gpa, io, b_dir, "src/f1", "trunk side");
                },
            }
        }
    }
}

test "cli verb dispatch: prefixes, aliases, ambiguity, and a two-line unknown-verb error" {
    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, "f.txt", "one\n");
    try addManaged(gpa, io, tmp.dir, &.{"f.txt"});
    var c1 = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "ci", "-m", "one" }); // alias
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);

    // A prefix dispatches with its arguments intact.
    var tl = try runZit(gpa, io, tmp.dir, &.{ "tim", "-n", "1" });
    defer freeResult(gpa, &tl);
    try expectExitDiag(tl.term, 0, tl);
    try std.testing.expect(std.mem.indexOf(u8, tl.stdout, "one") != null);
    // `changes` is `status`.
    var ch = try runZit(gpa, io, tmp.dir, &.{"changes"});
    defer freeResult(gpa, &ch);
    try expectExitDiag(ch.term, 0, ch);
    // ...minus Fossil's checkout block, exactly as Fossil's `changes` is.
    try std.testing.expect(std.mem.indexOf(u8, ch.stdout, "repository:") == null);
    // An exact verb wins over the prefix rule: `stat` is the census.
    var st = try runZit(gpa, io, tmp.dir, &.{"stat"});
    defer freeResult(gpa, &st);
    try expectExitDiag(st.term, 0, st);
    try std.testing.expect(std.mem.indexOf(u8, st.stdout, "store-bytes") != null);
    // Ambiguity names the candidates and stops.
    var amb = try runZit(gpa, io, tmp.dir, &.{ "ti", "-n", "1" });
    defer freeResult(gpa, &amb);
    try expectExit(amb.term, 2);
    try std.testing.expectEqualStrings("", amb.stdout);
    try std.testing.expect(std.mem.indexOf(u8, amb.stderr, "ambiguous command 'ti' (timeline, ticket)") != null);
    // Unknown: two lines, no suggestion for a distant token, never the verb list.
    var unk = try runZit(gpa, io, tmp.dir, &.{"florble"});
    defer freeResult(gpa, &unk);
    try expectExit(unk.term, 2);
    try std.testing.expect(std.mem.indexOf(u8, unk.stderr, "unknown command 'florble'") != null);
    try std.testing.expect(std.mem.indexOf(u8, unk.stderr, "try 'zit help'") != null);
    try std.testing.expect(std.mem.indexOf(u8, unk.stderr, "commands:") == null);
    try std.testing.expect(std.mem.count(u8, unk.stderr, "\n") == 2);
    // A short typo suggests only at distance 1: `tmi` is not `rm`.
    var tmi = try runZit(gpa, io, tmp.dir, &.{"tmi"});
    defer freeResult(gpa, &tmi);
    try expectExit(tmi.term, 2);
    try std.testing.expect(std.mem.indexOf(u8, tmi.stderr, "did you mean 'rm'") == null);
    // help resolves a prefix and names an ambiguity.
    var ht = try runZit(gpa, io, tmp.dir, &.{ "help", "tim" });
    defer freeResult(gpa, &ht);
    try expectExitDiag(ht.term, 0, ht);
    try std.testing.expect(std.mem.indexOf(u8, ht.stdout, "usage: zit timeline") != null);
    var hti = try runZit(gpa, io, tmp.dir, &.{ "help", "ti" });
    defer freeResult(gpa, &hti);
    try expectExit(hti.term, 2);
    try std.testing.expect(std.mem.indexOf(u8, hti.stderr, "ambiguous") != null);
}

test "cli names: current, prev/previous and next resolve against the checkout; ckout is an ordinary name; a bare store has none; 'trunk.' and 'current.' resolve by the §8.3 retry and 'trunk^' is not found" {
    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", "one" });
    defer freeResult(gpa, &c1);
    try expectExitDiag(c1.term, 0, c1);
    const first = 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", "two" });
    defer freeResult(gpa, &c2);
    try expectExitDiag(c2.term, 0, c2);
    const second = try checkinHash(c2.stdout);

    // `current.` re-enters the keyword after the §8.3 retry strips the '.'.
    inline for (.{ "current", "current." }) |n| {
        var r = try runZit(gpa, io, tmp.dir, &.{ "info", n });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
        try std.testing.expect(std.mem.startsWith(u8, r.stdout, second));
    }
    // §8.3: Fossil knows `ckout` only under its internal "ci+" request
    // type, so as a name it resolves like any other and names nothing here.
    var ck = try runZit(gpa, io, tmp.dir, &.{ "info", "ckout" });
    defer freeResult(gpa, &ck);
    try expectExit(ck.term, 1);
    inline for (.{ "prev", "previous", "prev." }) |n| {
        var r = try runZit(gpa, io, tmp.dir, &.{ "info", n });
        defer freeResult(gpa, &r);
        try expectExitDiag(r.term, 0, r);
        try std.testing.expect(std.mem.startsWith(u8, r.stdout, first));
    }
    // `next` from the older check-in is the newer one.
    var up = try runZit(gpa, io, tmp.dir, &.{ "update", first });
    defer freeResult(gpa, &up);
    try expectExitDiag(up.term, 0, up);
    var nx = try runZit(gpa, io, tmp.dir, &.{ "info", "next" });
    defer freeResult(gpa, &nx);
    try expectExitDiag(nx.term, 0, nx);
    try std.testing.expect(std.mem.startsWith(u8, nx.stdout, second));
    // A root check-in has no prev.
    var np = try runZit(gpa, io, tmp.dir, &.{ "info", "prev" });
    defer freeResult(gpa, &np);
    try expectExit(np.term, 1);
    // §8.3: a trailing '.' is dropped, so 'trunk.' is 'trunk'; '^' is not in
    // Fossil's trailing-punctuation set, so 'trunk^' names nothing.
    var dot = try runZit(gpa, io, tmp.dir, &.{ "info", "trunk." });
    defer freeResult(gpa, &dot);
    try expectExitDiag(dot.term, 0, dot);
    try std.testing.expect(std.mem.startsWith(u8, dot.stdout, second));
    var caret = try runZit(gpa, io, tmp.dir, &.{ "info", "trunk^" });
    defer freeResult(gpa, &caret);
    try expectExit(caret.term, 1);
    // On a bare store the checkout-relative names have no referent.
    var bare = try runZit(gpa, io, tmp.dir, &.{ "info", "current", "-R", "." });
    defer freeResult(gpa, &bare);
    try expectExit(bare.term, 1);
}

test "D card: every minted artifact carries millisecond precision; SOURCE_DATE_EPOCH pins .000" {
    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, "f", "x");
    try addManaged(gpa, io, tmp.dir, &.{"f"});

    // Deterministic run: the fraction is part of the canonical form and a
    // pinned epoch pins it to .000, so reproducible builds stay reproducible.
    var c = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "alice", .epoch = "1234567890" }, &.{ "commit", "-m", "one" });
    defer freeResult(gpa, &c);
    try expectExit(c.term, 0);
    const hash = try checkinHash(c.stdout);
    var art = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", hash });
    defer freeResult(gpa, &art);
    try expectExit(art.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, art.stdout, "D 2009-02-13T23:31:30.000\n") != null);

    // A live-clock wiki artifact carries the same 23-byte writer form — the
    // millisecond fix reaching the machine verbs whose consumer surfaced the bug.
    try writeFile(io, tmp.dir, "body.txt", "b");
    var w = try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{ "wiki", "commit", "T", "--user", "quarry" });
    defer freeResult(gpa, &w);
    try expectExit(w.term, 0);
    var wa = try runZit(gpa, io, tmp.dir, &.{ "artifact", "--raw", w.stdout[0..64] });
    defer freeResult(gpa, &wa);
    try expectExit(wa.term, 0);
    // A wiki artifact's D card is its FIRST line (D < L < N < U < W).
    const d_at = if (std.mem.startsWith(u8, wa.stdout, "D ")) @as(usize, 2) else std.mem.indexOf(u8, wa.stdout, "\nD ").? + 3;
    const d_end = std.mem.indexOfScalarPos(u8, wa.stdout, d_at, '\n').?;
    try std.testing.expectEqual(@as(usize, 23), d_end - d_at); // YYYY-MM-DDTHH:MM:SS.SSS
    try std.testing.expectEqual(@as(u8, '.'), wa.stdout[d_at + 19]);
}

test "cli: wiki and forum suppress the default mimetype; technote does not" {
    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, "body.txt", "hello\n");

    // FORUM (forum.c:1784) -- the default is never spelled out.
    var f_default = try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{
        "forum", "post", "--user", "u", "--title", "T", "--mimetype", "text/x-fossil-wiki",
    });
    defer freeResult(gpa, &f_default);
    try expectExit(f_default.term, 0);
    if (try nCardOf(gpa, io, tmp.dir, f_default.stdout[0..64])) |n| {
        defer gpa.free(n);
        std.debug.print("forum minted '{s}'; fossil omits the default\n", .{n});
        return error.TestUnexpectedResult;
    }

    // ...but a non-default one is carried.
    var f_md = try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{
        "forum", "post", "--user", "u", "--title", "T2", "--mimetype", "text/x-markdown",
    });
    defer freeResult(gpa, &f_md);
    const f_n = (try nCardOf(gpa, io, tmp.dir, f_md.stdout[0..64])).?;
    defer gpa.free(f_n);
    try std.testing.expectEqualStrings("N text/x-markdown", f_n);

    // WIKI (wiki.c:2084) -- same rule.
    var w_default = try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{
        "wiki", "commit", "Page", "--user", "u", "--mimetype", "text/x-fossil-wiki",
    });
    defer freeResult(gpa, &w_default);
    try expectExit(w_default.term, 0);
    if (try nCardOf(gpa, io, tmp.dir, w_default.stdout[0..64])) |n| {
        defer gpa.free(n);
        std.debug.print("wiki minted '{s}'; fossil omits the default\n", .{n});
        return error.TestUnexpectedResult;
    }

    // TECHNOTE (event.c:284) -- fossil writes it, so zit must too. This is the
    // arm that makes "just be consistent across the three" the WRONG fix.
    var t_default = try runZitStdin(gpa, io, tmp.dir, "body.txt", &.{
        "technote", "add", "--user", "u", "--mimetype", "text/x-fossil-wiki",
    });
    defer freeResult(gpa, &t_default);
    try expectExit(t_default.term, 0);
    // `technote add` prints "<event-id> <artifact-hash>".
    const sp = std.mem.indexOfScalar(u8, t_default.stdout, ' ').?;
    const t_hash = std.mem.trim(u8, t_default.stdout[sp + 1 ..], " \n");
    const t_n = (try nCardOf(gpa, io, tmp.dir, t_hash)).?;
    defer gpa.free(t_n);
    try std.testing.expectEqualStrings("N text/x-fossil-wiki", t_n);
}

test "cli: an empty check-in name is refused by every name-taking verb, never a crash" {
    // `zit update ""` reached the store resolver's non-empty precondition and
    // died (a segfault in release builds). Every verb that resolves a name
    // must answer an empty one with a diagnostic and a non-zero exit.
    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 c = try runCommitEnv(gpa, io, tmp.dir, .{ .user = "u" }, &.{ "commit", "-m", "one" });
    defer freeResult(gpa, &c);
    try expectExitDiag(c.term, 0, c);

    const cases = [_][]const []const u8{
        &.{ "update", "" },
        &.{ "merge", "" },
        &.{ "info", "" },
        &.{ "ls", "" },
        &.{ "cat", "a.txt", "" },
        &.{ "annotate", "a.txt", "" },
        &.{ "log", "" },
        &.{ "tag", "list", "" },
        &.{ "branch", "new", "x", "" },
        &.{ "diff", "--from", "", "--to", "tip" },
    };
    for (cases) |argv| {
        var res = try runZit(gpa, io, tmp.dir, argv);
        defer freeResult(gpa, &res);
        const code: u8 = switch (res.term) {
            .exited => |n| n,
            else => 255, // a signal (the crash this test exists to catch)
        };
        if (code == 0 or code > 2 or res.stderr.len == 0) {
            std.debug.print("\nzit {s}: term {any}, stdout {s}, stderr {s}\n", .{ argv[0], res.term, res.stdout, res.stderr });
            return error.EmptyNameNotRefused;
        }
    }
}

/// Build a repository of `commits` check-ins, each editing one tracked file.
fn seedLinearHistory(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, commits: usize) !void {
    try initRepo(gpa, io, dir);
    try writeFile(io, dir, "a.txt", "0\n");
    // Committed once and never touched again: `annotate stable.txt` must not
    // read more manifests just because history grew AROUND the file.
    try writeFile(io, dir, "stable.txt", "one\ntwo\n");
    try addManaged(gpa, io, dir, &.{ "a.txt", "stable.txt" });
    for (0..commits) |i| {
        var buf: [32]u8 = undefined;
        try writeFile(io, dir, "a.txt", try std.fmt.bufPrint(&buf, "line {d}\n", .{i}));
        var msg: [32]u8 = undefined;
        var res = try runCommitEnv(gpa, io, dir, .{}, &.{ "commit", "-m", try std.fmt.bufPrint(&msg, "c{d}", .{i}) });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
    }
}

test "cli: a listing's manifest reads do not grow with history" {
    // The regression this pins is invisible to every other test: a verb that
    // reads a manifest per row prints exactly the right answer, just
    // proportional to the store. It cost `zit leaves` a second on SQLite and
    // `zit timeline` sixty-six, and neither showed up as a failure — only as a
    // slow afternoon. Wall time cannot pin it (a loaded machine varies by a
    // third); the read COUNT can, and the sharpest form needs no magic
    // constant: run the same verb over two histories of different lengths and
    // require the count to be identical. A per-row read fails that by
    // construction, whatever the absolute numbers are.
    const gpa = std.testing.allocator;
    const io = std.testing.io;

    // Flat means IDENTICAL across history sizes, not zero: `info` and `ls`
    // legitimately read the one manifest they render, and 1 == 1 passes.
    const listings = [_][]const []const u8{
        &.{ "leaves", "--all" },
        &.{ "timeline", "-n", "0" },
        &.{ "timeline", "-n", "0", "-F", "oneline" },
        &.{ "timeline", "-n", "0", "-F", "medium" },
        &.{ "timeline", "-n", "0", "-F", "html" },
        &.{ "branch", "-v" },
        &.{ "tag", "list" },
        &.{"status"},
        &.{ "info", "tip" },
        &.{"info"}, // bare form: infoCheckout's own fast_read open
        &.{"ls"},
        &.{ "annotate", "stable.txt" },
        &.{ "grep", "one", "stable.txt" }, // one version, one read
    };

    var counts: [2][listings.len]u64 = undefined;
    for ([2]usize{ 4, 12 }, 0..) |commits, size_idx| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try seedLinearHistory(gpa, io, tmp.dir, commits);
        for (listings, 0..) |argv, i| {
            var res = try runZitEnv(gpa, io, tmp.dir, &.{.{ "ZIT_MANIFEST_READS", "1" }}, argv);
            defer freeResult(gpa, &res);
            try expectExitDiag(res.term, 0, res);
            counts[size_idx][i] = manifestReadsOf(&res) orelse {
                std.debug.print("\n{s}: no manifest-reads report\n", .{argv[0]});
                return error.NoReadCount;
            };
        }
    }

    for (listings, 0..) |argv, i| {
        if (counts[0][i] != counts[1][i]) {
            std.debug.print(
                "\n{s} {s}: manifest reads grew with history — {d} at 4 check-ins, {d} at 12.\n" ++
                    "A listing renders comment, user, branch and tags from the derived state;\n" ++
                    "a read per row means a verb fell back to the artifact for one of them.\n",
                .{ argv[0], if (argv.len > 1) argv[argv.len - 1] else "", counts[0][i], counts[1][i] },
            );
            return error.ManifestReadsScaleWithHistory;
        }
    }
}

/// The `fileindex-subs: N` the seam prints: sub-manifests the tree diff
/// resolved to build the index.
fn fileIndexSubsOf(res: *const std.process.RunResult) ?u64 {
    const marker = "fileindex-subs: ";
    const at = std.mem.lastIndexOf(u8, res.stderr, marker) orelse return null;
    const rest = res.stderr[at + marker.len ..];
    const end = std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len;
    return std.fmt.parseInt(u64, std.mem.trim(u8, rest[0..end], " \r"), 10) catch null;
}

test "the tree-manifest index build resolves only the sub-manifests that changed, not the whole tree" {
    // Diffing two trees by flattening both cost files-per-check-in, not
    // files-changed: 34 minutes and ~1 GB on a pkgsrc mirror. The S-card diff
    // skips every sub-manifest whose hash did not move. Three top-level
    // directories at k=1 are three leaf sub-manifests; a commit touching one
    // file resolves that sub-manifest's two versions and nothing else.
    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);
    const seam = [_][2][]const u8{.{ "ZIT_FILEINDEX_WALK", "1" }};
    {
        var warm = try runZitEnv(gpa, io, tmp.dir, &seam, &.{ "log", tip, "a/x.txt" });
        defer freeResult(gpa, &warm);
        try expectExitDiag(warm.term, 0, warm);
    }
    try writeFile(io, tmp.dir, "a/x.txt", "x2\n");
    gpa.free(tip);
    tip = try commitHashDup(gpa, io, tmp.dir, "touch a");

    // The query's own open extends the derive over the one new check-in and
    // the index with it — that is where the tree diff runs — so the query
    // walks nothing, and the sub-manifests resolved in this process are the
    // extend's.
    var q = try runZitEnv(gpa, io, tmp.dir, &seam, &.{ "log", tip, "a/x.txt" });
    defer freeResult(gpa, &q);
    try expectExitDiag(q.term, 0, q);
    try std.testing.expectEqual(@as(u64, 0), fileIndexWalkOf(&q) orelse return error.NoCounter);
    try std.testing.expectEqual(@as(u64, 0), fileIndexUnknownOf(&q) orelse return error.NoCounter);
    const subs = fileIndexSubsOf(&q) orelse return error.NoCounter;
    if (subs > 2) {
        std.debug.print("\nthe tree diff resolved {d} sub-manifests for a one-file commit in a three-leaf tree; it should resolve the changed leaf's two versions only\n", .{subs});
        return error.TreeDiffNotProportional;
    }
    try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, q.stdout, "checkin "));
    // b and c untouched: their history is unchanged and the index still knows it.
    var b = try runZitEnv(gpa, io, tmp.dir, &seam, &.{ "log", tip, "b/y.txt" });
    defer freeResult(gpa, &b);
    try expectExitDiag(b.term, 0, b);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, b.stdout, "checkin "));
}