Skip to content
zit Artifact [baaa7d82e9]
Login

Artifact [baaa7d82e9]

Artifact baaa7d82e9180bd4e08a821daf99da36144d3504165ac71d8a5372ef522fe2b6:


//! zit — command-line entry point.
//!
//! The heavy lifting lives in the `zit` library module (src/root.zig and the
//! per-RFC / storage modules it re-exports); this file is only the CLI surface.
//! `main` wires I/O and flushes; `run` is a pure-ish dispatcher over an
//! injected `std.Io` that returns an exit code, so every verb is exercisable
//! without a subprocess (design-seams rule). No `std.http` appears here.

const std = @import("std");
const repeat = @import("zit").repeat;
const Io = std.Io;
const zit = @import("zit");
const cli = @import("zit").cli;

// The store layers and the repository facade are all part of the one `zit`
// library module (root.zig re-exports them), so the CLU imports a single
// dependency.
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const Repository = @import("zit").Repository;
// The clone verb's two CLI-layer seams: `transport` is the sole HTTP/IO module
// on the client side (sync §4), `sync_driver` the sans-IO round loop that pumps
// `sync.Client` to §3.7 convergence over it. `sync.zig` itself stays sans-IO.
const transport = @import("transport.zig");
const sync_driver = @import("sync_driver.zig");
const cmd_sync = @import("cmd/sync.zig");
const cmd_clone = @import("cmd/clone.zig");
const cmd_config = @import("cmd/config.zig");
const cmd_open = @import("cmd/open.zig");
const cmd_pack = @import("cmd/pack.zig");
const cmd_pull = @import("cmd/pull.zig");
const cmd_push = @import("cmd/push.zig");
const cmd_remote = @import("cmd/remote.zig");
const cmd_serve = @import("cmd/serve.zig");
const cmd_settings = @import("cmd/settings.zig");
const cmd_shun = @import("cmd/shun.zig");
const cmd_uv = @import("cmd/uv.zig");
const sync_exchange = @import("cmd/sync_exchange.zig");
const cmd_tracking = @import("cmd/tracking.zig");
const cmd_users = @import("cmd/users.zig");
const cmd_stat = @import("cmd/stat.zig");
const cmd_log = @import("cmd/log.zig");
const cmd_leaves = @import("cmd/leaves.zig");
const cmd_timeline = @import("cmd/timeline.zig");
const cmd_branch = @import("cmd/branch.zig");
const cmd_tag = @import("cmd/tag.zig");
const cmd_info = @import("cmd/info.zig");
const cmd_ls = @import("cmd/ls.zig");
const cmd_merge_base = @import("cmd/merge_base.zig");
const cmd_cat = @import("cmd/cat.zig");
const cmd_artifact = @import("cmd/artifact.zig");
const cmd_annotate = @import("cmd/annotate.zig");
const cmd_frames = @import("cmd/frames.zig");
const cmd_grep = @import("cmd/grep.zig");
const cmd_crosslink = @import("cmd/crosslink.zig");
const cmd_purge = @import("cmd/purge.zig");
const cmd_amend = @import("cmd/amend.zig");
const cmd_bisect = @import("cmd/bisect.zig");
const cmd_checkpoint = @import("cmd/checkpoint.zig");
const cmd_commit = @import("cmd/commit.zig");
const cmd_cone = @import("cmd/cone.zig");
const cmd_merge = @import("cmd/merge.zig");
const cmd_revert = @import("cmd/revert.zig");
const cmd_submanifest = @import("cmd/submanifest.zig");
const cmd_trust = @import("cmd/trust.zig");
const cmd_undo = @import("cmd/undo.zig");
const cmd_update = @import("cmd/update.zig");
const cmd_worktrees = @import("cmd/worktrees.zig");
const cmd_stash = @import("cmd/stash.zig");
const cmd_precedent = @import("cmd/precedent.zig");
const cmd_verify = @import("cmd/verify.zig");
const cmd_records = @import("cmd/records.zig");
const cmd_landing = @import("cmd/landing.zig");
const cmd_modules = @import("cmd/modules.zig");
const cmd_gitmirror = @import("cmd/gitmirror.zig");
const cmd_archive = @import("cmd/archive.zig");
const cmd_mergetree = @import("cmd/mergetree.zig");
const cmd_daemon = @import("cmd/daemon.zig");
const repostate = zit.repostate;
const managed = zit.managed;
// The artifact-format vocabulary `commit` assembles a check-in from: the
// `Manifest`/card structs it populates, `create` (serializes + computes the Z
// self-check), `parse` (reads the parent F-set), and `artifactName` (names each
// blob and the manifest). Reached through the same `zit` module cli.zig uses, so
// the `FCard` values flow between them without a type mismatch.
const artifact = zit.artifact;
const git_import_cli = @import("git/git_import_cli.zig");
const fossil_import_cli = @import("fossil/fossil_import_cli.zig");
const git_export_cli = @import("git/git_export_cli.zig");
const diagnostics = @import("diagnostics.zig");
const help_pages = @import("help.zig");
const cmd_init = @import("cmd/init.zig");

pub fn main(init: std.process.Init) !void {
    // Resident memory follows each size class's peak rather than growing
    // with how much was freed; see `class_heap.zig`. Process exit returns it.
    var heap: zit.class_heap.ClassHeap = .{ .backing = init.gpa };
    const gpa = heap.allocator();
    const arena = init.arena.allocator();
    // Every file read and write moves at most 1 GiB per call: Darwin refuses
    // larger ones, and the cache files of a large store pass 2 GiB.
    const io = zit.clamped_io.wrap(init.io);

    // `toSlice` yields sentinel-terminated argv; widen to plain `[]const u8`
    // slices so the verb runner never depends on NUL termination (a slice of
    // `[:0]const u8` does not coerce to a slice of `[]const u8`).
    const argv_z = try init.minimal.args.toSlice(arena);
    const args = try arena.alloc([]const u8, argv_z.len);
    for (argv_z, args) |src, *dst| dst.* = src;

    // Streaming (not positional) writers: `Io.File.Writer.init` defaults to
    // `.positional`, which writes via `pwrite` from an internal `pos` that
    // starts at 0 — ignoring the OS file offset zit inherited on stdout/stderr.
    // That silently clobbers `zit … >> logfile` (O_APPEND) and grouped/shared-fd
    // redirections (`{ echo a; zit …; } > log`), overwriting bytes another
    // writer already put there. Streaming mode uses plain `write`/`writev`,
    // honoring the inherited offset and O_APPEND — the pipe-safe, composable
    // behavior a process's standard streams must have (contracts/rm.md B-rm-14).
    var out_buf: [4096]u8 = undefined;
    var out_writer: Io.File.Writer = .initStreaming(.stdout(), io, &out_buf);
    var err_buf: [4096]u8 = undefined;
    var err_writer: Io.File.Writer = .initStreaming(.stderr(), io, &err_buf);
    const streams: cli.Streams = .{ .out = &out_writer.interface, .err = &err_writer.interface };

    // The ambient clock/environment values the runners need, read here — the
    // single place time and environment enter the CLI (design-seams rule) — and
    // threaded as plain values so every verb runner stays deterministic under
    // test. `$ZIT_PASSWORD` (sync §6.3) is a no-persistence password source for
    // `push`, read at this one seam like `$USER`.
    const amb: cli.Ambient = .{
        .now_epoch = commitEpoch(io, init.environ_map),
        .now_ms = commitEpochMs(io, init.environ_map),
        .user_env = init.environ_map.get("USER") orelse init.environ_map.get("LOGNAME"),
        .push_password = init.environ_map.get("ZIT_PASSWORD"),
        .environ = init.minimal.environ,
    };
    // A signed erasure's not-before is compared against the CLI's one clock:
    // `SOURCE_DATE_EPOCH` pins it as it pins `now_epoch`, and otherwise every
    // store open reads the wall clock, so a long-running `zit serve` sees an
    // erasure pass its not-before without a restart.
    zit.logstore.erasure_clock = if (init.environ_map.get("SOURCE_DATE_EPOCH") != null)
        .{ .fixed = amb.now_epoch }
    else
        .{ .live = io };
    // The file-history index is an accelerator; this turns it off so
    // the same query is answered by reconstruction, which is how the
    // differential test proves the two agree.
    zit.filelog.no_file_index = init.environ_map.get("ZIT_NO_FILE_INDEX") != null;
    // A history's tree lookups parse every node whole, the reading the
    // byte descent replaced, so the differential test can compare the two.
    Repository.parse_every_node = init.environ_map.get("ZIT_PARSE_EVERY_NODE") != null;
    // Line counts look each changed file's old side up by name; this takes
    // it from the parent's whole file set instead, so the differential test
    // can prove the two count the same.
    cmd_crosslink.lines_whole_tree = init.environ_map.get("ZIT_LINES_WHOLE_TREE") != null;
    // A filtered origin's cone clone streams its rounds to disk; this keeps
    // the batched local-filter path instead, so the differential test can
    // prove the two store the same bytes.
    cmd_clone.clone_batched_persist = init.environ_map.get("ZIT_CLONE_BATCHED") != null;
    // The daemon's socket directory defaults under $TMPDIR; the rest
    // are its crash-test, size-limit and timing seams.
    cmd_daemon.tmpdir_env = init.environ_map.get("TMPDIR");
    cmd_daemon.fault_env = init.environ_map.get("ZIT_DAEMON_FAULT");
    cmd_daemon.max_file_bytes_env = init.environ_map.get("ZIT_DAEMON_MAX_FILE_BYTES");
    cmd_daemon.max_request_bytes_env = init.environ_map.get("ZIT_DAEMON_MAX_REQUEST_BYTES");
    cmd_daemon.stall_ms_env = init.environ_map.get("ZIT_DAEMON_STALL_MS");
    cmd_daemon.drain_ms_env = init.environ_map.get("ZIT_DAEMON_DRAIN_MS");
    cmd_daemon.drain_bytes_env = init.environ_map.get("ZIT_DAEMON_DRAIN_BYTES");

    // A damaged log index over a log that no longer scans ends the process
    // as the scan's failed open would have, wherever the read that met it.
    fatal_streams = streams;
    fatal_verb = if (args.len >= 2) args[1] else "help";
    zit.logstore.LogStore.on_unrepairable = unrepairableStore;
    const code = run(gpa, io, arena, args, streams, amb);

    // Evidence seam. A listing renders comment, user, branch and
    // tags from the derived state; a manifest read per row is the regression
    // this reports, and `src/e2e.zig` asserts the count stays flat as history
    // grows. Off unless asked for, and it changes nothing else.
    if (init.environ_map.get("ZIT_FILEINDEX_WALK") != null) {
        streams.err.print("fileindex-walk: {d}\n", .{zit.repoview.change_set_visits}) catch {};
        streams.err.print("fileindex-subs: {d}\n", .{zit.repoview.tree_subs_resolved}) catch {};
        streams.err.print("fileindex-annotate: {d}\n", .{zit.blame.indexed_walks.load(.monotonic)}) catch {};
        streams.err.print("fileindex-annotate-walked: {d}\n", .{zit.blame.versions_walked.load(.monotonic)}) catch {};
        streams.err.print("fileindex-annotate-diffs: {d}\n", .{zit.blame.edges_diffed.load(.monotonic)}) catch {};
        if (zit.filelog.file_index_unknown) |n| {
            streams.err.print("fileindex-unknown: {d}\n", .{n}) catch {};
        } else {
            streams.err.writeAll("fileindex-unknown: none\n") catch {};
        }
    }
    if (init.environ_map.get("ZIT_HEAL_SCANS") != null) {
        streams.err.print("heal-scans: {d}\n", .{zit.repoview.heal_scans}) catch {};
    }
    if (init.environ_map.get("ZIT_MANIFEST_READS") != null) {
        streams.err.print("manifest-reads: {d}\n", .{Repository.manifest_reads}) catch {};
    }
    if (init.environ_map.get("ZIT_TREE_FLATTENS") != null) {
        streams.err.print("tree-flattens: {d}\n", .{Repository.tree_flattens}) catch {};
    }
    if (init.environ_map.get("ZIT_LS_CONTENT_READS") != null) {
        streams.err.print("ls-content-reads: {d}\n", .{cmd_ls.ls_content_reads}) catch {};
    }
    // Evidence seam (clone memory): the persist drain's peak deferred
    // waiting set — what a streaming persist would have to keep resident or
    // spill. The streaming decision is gated on this number being measured.
    // Evidence seam (derive memory): what the derive's record body is
    // made of and what the state retains, so a rung of the derive ladder is
    // bought or declined on measured composition rather than a guess.
    if (init.environ_map.get("ZIT_DERIVE_FOOTPRINT") != null) {
        const rv = zit.repoview;
        const rs = zit.repostate;
        streams.err.print(
            "derive-footprint: records={d} body-peak-capacity={d} hash={d} parent={d} tag={d} comment={d} user={d} path={d} filehash={d} state-records={d} state-comment={d} state-user={d}\n",
            .{
                rv.derive_records,      rv.derive_body_peak_capacity, rv.derive_hash_bytes,
                rv.derive_parent_bytes, rv.derive_tag_bytes,          rv.derive_comment_bytes,
                rv.derive_user_bytes,   rv.derive_path_bytes,         rv.derive_filehash_bytes,
                rs.state_records,       rs.state_comment_bytes,       rs.state_user_bytes,
            },
        ) catch {};
    }
    if (init.environ_map.get("ZIT_PERSIST_WAITING") != null) {
        streams.err.print("persist-waiting-peak: {d} frames, {d} bytes\n", .{
            zit.receive.persist_waiting_peak,
            zit.receive.persist_waiting_peak_bytes,
        }) catch {};
    }
    if (init.environ_map.get("ZIT_LANDING_STATS") != null) {
        streams.err.print("landing-stats: forum index walked {d} rids\n", .{zit.nameindex.walk_rids}) catch {};
    }
    if (init.environ_map.get("ZIT_SYNC_STATS") != null) {
        streams.err.print("sync-stats: {d} rounds, sent {d} bytes, received {d} bytes; cluster index {d} clusters, walked {d} rids\n", .{
            sync_exchange.sync_rounds,
            sync_exchange.sync_sent_bytes,
            sync_exchange.sync_received_bytes,
            zit.receive.cluster_index_names,
            zit.clusterindex.walk_rids,
        }) catch {};
    }

    streams.out.flush() catch {};
    streams.err.flush() catch {};
    if (code != .ok) std.process.exit(@backingInt(code));
}

var fatal_streams: ?cli.Streams = null;
var fatal_verb: []const u8 = "help";

/// `LogStore.on_unrepairable` for the CLI and the daemon: the message and
/// exit status of a failed store open (`storeReadFail`). Nothing buffered on
/// stdout is flushed, so no partial answer is printed.
fn unrepairableStore(err: zit.logstore.OpenError) void {
    if (fatal_streams) |s| {
        _ = diagnostics.storeReadFail(s, fatal_verb, err);
        s.err.flush() catch {};
    }
    std.process.exit(@backingInt(cli.Exit.failure));
}

/// An ambiguous prefix names its candidates and, so the next attempt lands,
/// the shortest spelling that reaches each one:
/// `zit: ambiguous command 'st' (stash, stat, status); try stas, stat, or statu`.
fn ambiguousVerb(streams: cli.Streams, who: []const u8, typed: []const u8, a: cli.Ambiguity) cli.Exit {
    const e = streams.err;
    e.print("{s}: ambiguous command '{s}' (", .{ who, typed }) catch {};
    for (a.names[0..a.n], 0..) |n, i| e.print("{s}{s}", .{ if (i == 0) "" else ", ", n }) catch {};
    e.writeAll(if (a.more) ", …); try " else "); try ") catch {};
    for (a.names[0..a.n], 0..) |n, i| {
        const sep: []const u8 = if (i == 0) "" else if (i + 1 == a.n and !a.more) (if (a.n == 2) " or " else ", or ") else ", ";
        e.print("{s}{s}", .{ sep, cli.shortestPrefix(n) }) catch {};
    }
    e.writeAll(if (a.more) ", …\n" else "\n") catch {};
    return .usage;
}

/// Dispatches on the verb (a total switch) and returns the process exit code.
/// Never errors: every failure is rendered as an educating diagnostic by the
/// verb and folded into the returned `Exit`.
pub fn run(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const verb = if (args.len >= 2) args[1] else "help";

    // `-R`/`--repo <path>` is a GLOBAL option: it is lifted out here, before the
    // verb's own parser runs, so ten read verbs share one implementation instead
    // of each re-declaring the flag. The verb then sees exactly the arguments it
    // has always seen, and the resolved store rides along in `Ambient`.
    // Bare `zit` carries no verb and therefore no verb arguments; `args[2..]`
    // would be out of bounds on it.
    const raw_args: []const []const u8 = if (args.len >= 2) args[2..] else &.{};
    // Exact verb or alias, else an unambiguous prefix; an ambiguous
    // one names its candidates and stops here.
    const resolved: cli.Verb = switch (cli.resolveVerb(verb)) {
        .verb => |v| v,
        .ambiguous => |a| return ambiguousVerb(streams, "zit", verb, a),
        .unknown => .unknown,
    };
    const global = cli.parseGlobalArgs(arena, raw_args) catch
        return diagnostics.stateOom(streams, verb);
    const verb_args = switch (global) {
        .ok => |g| blk: {
            if (g.repo != null and !cli.acceptsRepoOverride(resolved))
                return cli.usageError(streams, verb, .repo_unsupported, "-R/--repo");
            break :blk g.args;
        },
        // A dangling `-R` is a dangling value option, phrased the way every
        // other value option in the CLI phrases one.
        .missing_value => |tok| return cli.usageError(streams, verb, .unknown_option, tok),
        .repeated_option => |tok| return cli.usageError(streams, verb, .repeated_option, tok),
        .empty_value => |tok| return cli.usageError(streams, verb, .empty_value, tok),
    };
    const amb_r: cli.Ambient = .{
        .now_epoch = amb.now_epoch,
        .now_ms = amb.now_ms,
        .user_env = amb.user_env,
        .push_password = amb.push_password,
        .environ = amb.environ,
        .repo_override = switch (global) {
            .ok => |g| g.repo,
            else => unreachable, // every other arm returned above
        },
    };

    switch (resolved) {
        .init => return cmd_init.runInit(gpa, io, arena, verb_args, streams),
        .add => return cmd_tracking.runAdd(gpa, io, arena, verb_args, streams, amb),
        .rm => return cmd_tracking.runRm(gpa, io, arena, verb_args, streams),
        .mv => return cmd_tracking.runMv(gpa, io, arena, verb_args, streams),
        .status => return cmd_tracking.runStatus(gpa, io, arena, verb_args, streams, !std.mem.eql(u8, verb, "changes"), amb),
        .stat => return cmd_stat.runStat(gpa, io, arena, verb_args, streams, amb_r),
        .diff => return cmd_tracking.runDiff(gpa, io, arena, verb_args, streams, amb_r),
        .extras => return cmd_tracking.runExtras(gpa, io, arena, verb_args, streams, amb),
        .clean => return cmd_tracking.runClean(gpa, io, arena, verb_args, streams, amb),
        .addremove => return cmd_tracking.runAddremove(gpa, io, arena, verb_args, streams, amb),
        .commit => return cmd_commit.runCommit(gpa, io, arena, verb_args, streams, amb_r),
        .log => return cmd_log.runLog(gpa, io, arena, verb_args, streams, amb_r),
        .open => return cmd_open.runOpen(gpa, io, arena, verb_args, streams, amb),
        .update => return cmd_update.runUpdate(gpa, io, arena, verb_args, streams, amb),
        .merge => return cmd_merge.runMerge(gpa, io, arena, verb_args, streams, amb_r),
        .revert => return cmd_revert.runRevert(gpa, io, arena, verb_args, streams),
        .undo => return cmd_undo.runUndo(gpa, io, arena, verb_args, streams),
        .redo => return cmd_undo.runRedo(gpa, io, arena, verb_args, streams),
        .leaves => return cmd_leaves.runLeaves(gpa, io, arena, verb_args, streams, amb_r),
        .ui => return runUi(gpa, io, arena, verb_args, streams, amb_r),
        .timeline => return cmd_timeline.runTimeline(gpa, io, arena, verb_args, streams, amb_r),
        .branch => return cmd_branch.runBranch(gpa, io, arena, verb_args, streams, amb_r),
        .tag => return cmd_tag.runTag(gpa, io, arena, verb_args, streams, amb_r),
        .amend => return cmd_amend.runAmend(gpa, io, arena, verb_args, streams, amb_r),
        .info => return cmd_info.runInfo(gpa, io, arena, verb_args, streams, amb_r),
        .ls => return cmd_ls.runLs(gpa, io, arena, verb_args, streams, amb_r),
        .cat => return cmd_cat.runCat(gpa, io, arena, verb_args, streams, amb_r),
        .artifact => return cmd_artifact.runArtifact(gpa, io, arena, verb_args, streams, amb_r),
        .annotate => return cmd_annotate.runAnnotate(gpa, io, arena, verb_args, streams, amb_r, std.mem.eql(u8, verb, "blame") or std.mem.eql(u8, verb, "praise")),
        .grep => return cmd_grep.runGrep(gpa, io, arena, verb_args, streams, amb_r),
        .frames => return cmd_frames.runFrames(gpa, io, arena, verb_args, streams, amb_r),
        .crosslink => return cmd_crosslink.runCrosslink(gpa, io, arena, verb_args, streams, amb_r),
        .bisect => return cmd_bisect.runBisect(gpa, io, arena, verb_args, streams),
        .serve => return cmd_serve.runServe(gpa, io, arena, verb_args, streams, amb_r),
        .daemon => return cmd_daemon.runDaemon(gpa, io, arena, verb_args, streams, amb_r, zit_version),
        .clone => return cmd_clone.runClone(gpa, io, arena, verb_args, streams, amb_r),
        .import_git => return runImportGit(gpa, io, verb_args, streams, amb_r),
        .import_fossil => return runImportFossil(gpa, io, arena, verb_args, streams, amb_r),
        .export_git => return runExportGit(gpa, io, verb_args, streams),
        .pull => return cmd_pull.runPullVerb(gpa, io, arena, verb_args, streams, amb_r),
        .push => return cmd_push.runPush(gpa, io, arena, verb_args, streams, amb_r),
        .uv => return cmd_uv.runUv(gpa, io, arena, verb_args, streams, amb_r),
        .sync => return cmd_sync.runSync(gpa, io, arena, verb_args, streams, amb_r),
        .remote => return cmd_remote.runRemote(gpa, io, arena, verb_args, streams, amb_r.repo_override),
        .settings => return cmd_settings.runSettings(gpa, io, arena, verb_args, streams, amb_r),
        .pack => return cmd_pack.runPack(gpa, io, arena, verb_args, streams, amb_r),
        .submanifest => {
            // `convert SRC DEST` is the converter under the verb that owns
            // sub-manifests; it needs no checkout, so it is routed
            // before the settings actions resolve one.
            switch (cli.parseSubmanifestArgs(verb_args)) {
                .ok => |p| if (p.action == .convert and !p.help) {
                    const src = p.src orelse {
                        streams.err.writeAll("zit submanifest convert: wants SRC (a flat zit store) and DEST (a directory to create)\n") catch {};
                        streams.err.writeAll("try 'zit submanifest --help'\n") catch {};
                        return .usage;
                    };
                    const dest = p.dest orelse {
                        streams.err.writeAll("zit submanifest convert: wants DEST, the directory to create\n") catch {};
                        streams.err.writeAll("try 'zit submanifest --help'\n") catch {};
                        return .usage;
                    };
                    if (p.names_path != null or p.replay_all) {
                        streams.err.writeAll("zit submanifest convert: --names and --replay-all are 'analyze' options\n") catch {};
                        return .usage;
                    }
                    return fossil_import_cli.runSubmanifestImport(gpa, io, arena, src, dest, p.k, "submanifest convert", streams, amb_r);
                },
                else => {},
            }
            return cmd_submanifest.runSubmanifest(gpa, io, arena, verb_args, streams, amb_r);
        },
        .cone => return cmd_cone.runCone(gpa, io, arena, verb_args, streams, amb),
        .worktrees => return cmd_worktrees.runWorktrees(gpa, io, arena, verb_args, streams, amb_r),
        .trust => return cmd_trust.runTrust(gpa, io, arena, verb_args, streams, amb),
        .config => return cmd_config.runConfig(gpa, io, arena, verb_args, streams, amb_r),
        .users => return cmd_users.runUsers(gpa, io, arena, verb_args, streams, amb_r),
        .tarball => return cmd_archive.runTarball(gpa, io, arena, verb_args, streams, amb_r),
        .merge_tree => return cmd_mergetree.runMergeTree(gpa, io, arena, verb_args, streams, amb_r),
        .merge_base => return cmd_merge_base.runMergeBase(gpa, io, arena, verb_args, streams, amb_r),
        .zip => return cmd_archive.runZip(gpa, io, arena, verb_args, streams, amb_r),
        .checkpoint => return cmd_checkpoint.runCheckpoint(gpa, io, arena, verb_args, streams),
        .stash => return cmd_stash.runStash(gpa, io, arena, verb_args, streams, amb),
        .precedent => return cmd_precedent.runPrecedent(gpa, io, arena, verb_args, streams),
        .shun => return cmd_shun.runShun(gpa, io, arena, verb_args, streams, amb_r),
        .purge => return cmd_purge.runPurge(gpa, io, arena, verb_args, streams, amb_r),
        .verify => return cmd_verify.runVerify(gpa, io, arena, verb_args, streams, amb_r),
        .wiki => return cmd_records.runWiki(gpa, io, arena, verb_args, streams, amb_r),
        .ticket => return cmd_records.runTicket(gpa, io, arena, verb_args, streams, amb_r),
        .forum => return cmd_records.runForum(gpa, io, arena, verb_args, streams, amb_r),
        .landing => return cmd_landing.runLanding(gpa, io, arena, verb_args, streams, amb_r),
        .modules => return cmd_modules.runModules(gpa, io, arena, verb_args, streams, amb_r),
        .git => return cmd_gitmirror.runGit(gpa, io, arena, verb_args, streams, amb_r),
        .technote => return cmd_records.runTechnote(gpa, io, arena, verb_args, streams, amb_r),
        .attach => return cmd_records.runAttach(gpa, io, arena, verb_args, streams, amb_r),
        .version => {
            streams.out.writeAll("zit " ++ zit_version ++ " (targets Fossil RFC rev " ++ zit.rfc_revision ++ ")\n") catch {};
            return .ok;
        },
        .help => {
            // `zit help <verb>` teaches that verb's own help — the same text as
            // `zit <verb> --help` (DX D4). Bare `zit`, `zit help`, and
            // `zit --help` list the commands. An unknown or help-less topic
            // (e.g. `version`) falls back to the command list, which now names
            // every real verb including `status`, so nothing reads as absent.
            if (args.len >= 3) {
                if (help_pages.helpFor(args[2])) |topic_help| {
                    streams.out.writeAll(topic_help) catch {};
                    return .ok;
                }
                // A REAL verb with no dedicated help (e.g. `version`) keeps
                // the command-list fallback below; only a token that is
                // neither a verb nor a topic is refused: a typo
                // deserves a diagnostic in a CLI that refuses everywhere else.
                if (cli.resolveVerb(args[2]) == .ambiguous) {
                    return ambiguousVerb(streams, "zit help", args[2], cli.resolveVerb(args[2]).ambiguous);
                }
                if (cli.resolveVerb(args[2]) != .verb) {
                    streams.err.print("zit help: no command or topic named '{s}'\n", .{args[2]}) catch {};
                    streams.err.writeAll("run 'zit help' for the command and topic list\n") catch {};
                    return .usage;
                }
            }
            streams.out.writeAll(help_pages.top_usage) catch {};
            return .ok;
        },
        .unknown => {
            // A git muscle-memory verb (rebase, checkout, push, …) gets a
            // lesson that corrects the zit model instead of a bare error, so
            // the diagnostic teaches (DX D2). Still a usage error: exit 2,
            // stderr only, nothing on stdout.
            if (cli.reflexLesson(verb)) |lesson| {
                streams.err.print("zit: '{s}' is not a zit command. {s}\n", .{ verb, lesson }) catch {};
                return .usage;
            }
            // A planned-but-unbuilt zit command (e.g. `commit`, which init's
            // help points the user at) resolves to a promise, not a dead-end:
            // every verb the shipped help names owns a handler or this stub.
            if (cli.isPlanned(verb)) {
                streams.err.print("zit: '{s}' is planned but not implemented yet.\n", .{verb}) catch {};
                return .usage;
            }
            // Otherwise the generic path: name the unknown command, offer a
            // near-miss suggestion when one is close (DX D4), then the command
            // list so discoverability survives a growing verb set.
            streams.err.print("zit: unknown command '{s}'\n", .{verb}) catch {};
            if (cli.didYouMean(verb)) |suggestion| {
                streams.err.print("did you mean '{s}'?\n", .{suggestion}) catch {};
            }
            // Two lines, never the whole command list: a typo is
            // not a request for the manual.
            streams.err.writeAll("try 'zit help' for the command list\n") catch {};
            return .usage;
        },
    }
}

/// `zit import-git` — the option surface is `cli.import_git_usage`, named
/// rather than re-transcribed here because this comment was a fourth copy of
/// that line and had already fallen behind it.
///
/// Parse the command surface, split DEST into the parent handle and basename
/// the transaction owns, then run the production Git/import dependencies.
/// `zit export-git SOURCE DEST` — mirror the source repository's canonical
/// check-in graph into a Git repository, incrementally (see git_export_cli).
fn runExportGit(
    gpa: std.mem.Allocator,
    io: std.Io,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    const parsed = cli.parseExportGitArgs(verb_args) catch |err| {
        streams.err.print("zit export-git: {s}\n", .{switch (err) {
            error.MissingSource => "SOURCE is required",
            error.MissingDestination => "DEST is required",
            error.ExtraArgument => "too many arguments",
            error.UnknownOption => "unknown option",
            error.MissingValue => "--email-domain wants a value",
            error.DuplicateOption => "--email-domain given twice",
        }}) catch {};
        streams.err.writeAll("usage: " ++ cli.export_git_usage ++ "\n") catch {};
        return .usage;
    };
    if (parsed.help) {
        streams.out.writeAll(help_pages.export_git_help) catch {};
        return .ok;
    }
    if (parsed.email_domain) |d| if (!cmd_gitmirror.emailDomainOk(d, "export-git", streams)) return .usage;

    // SOURCE resolves the way `serve`/`open` document it: a directory
    // holding `.zit`, or the `.zit` file itself (use its directory).
    var source_dir = blk: {
        const st = std.Io.Dir.cwd().statFile(io, parsed.source, .{}) catch {
            streams.err.print("zit export-git: cannot read SOURCE '{s}'\n", .{parsed.source}) catch {};
            return .failure;
        };
        if (st.kind == .directory) {
            break :blk std.Io.Dir.cwd().openDir(io, parsed.source, .{}) catch {
                streams.err.print("zit export-git: cannot open SOURCE '{s}'\n", .{parsed.source}) catch {};
                return .failure;
            };
        }
        const dirname = std.fs.path.dirname(parsed.source) orelse ".";
        break :blk std.Io.Dir.cwd().openDir(io, dirname, .{}) catch {
            streams.err.print("zit export-git: cannot open SOURCE '{s}'\n", .{parsed.source}) catch {};
            return .failure;
        };
    };
    defer source_dir.close(io);

    var repo: zit.Repository = undefined;
    zit.Repository.open(&repo, gpa, io, source_dir, .{ .mode = .full }) catch {
        streams.err.print("zit export-git: '{s}' is not a readable zit repository\n", .{parsed.source}) catch {};
        return .failure;
    };
    defer repo.deinit(gpa);
    const emitted = cmd_gitmirror.exportOnce(gpa, io, &repo, parsed.destination, parsed.rebuild, parsed.email_domain, "export-git", streams) orelse
        return .failure;
    streams.out.print("exported {d} commits into {s}\n", .{ emitted, parsed.destination }) catch {};
    return .ok;
}

fn runImportFossil(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const parsed = switch (cli.parseImportFossilArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "import-fossil", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "import-fossil", .extra_argument, tok),
        .bad_k => |tok| {
            streams.err.print("zit import-fossil: --k wants an integer 1..12 (got '{s}')\n", .{tok}) catch {};
            return .usage;
        },
        .both_modes => {
            streams.err.writeAll("zit import-fossil: --compatible and --submanifest are exclusive; the choice is the point\n") catch {};
            return .usage;
        },
    };
    if (parsed.help) {
        streams.out.writeAll(help_pages.import_fossil_help) catch {};
        return .ok;
    }
    const source = parsed.source orelse return cli.usageError(streams, "import-fossil", .no_file, "");
    const dir = parsed.dir orelse return cli.usageError(streams, "import-fossil", .no_file, "");
    const mode = parsed.mode orelse {
        streams.err.writeAll(
            "zit import-fossil: choose --compatible or --submanifest. The difference is\n" ++
                "permanent: --compatible keeps the corpus verbatim and stays in sync with the\n" ++
                "origin; --submanifest re-mints history as sub-manifest trees under a new\n" ++
                "project code and can never sync with the origin again.\n",
        ) catch {};
        return .usage;
    };
    if (mode == .compatible) {
        if (parsed.k != null) {
            streams.err.writeAll("zit import-fossil: --k belongs to --submanifest\n") catch {};
            return .usage;
        }
        // The compatible import IS the clone: fossil's sync protocol is the
        // import path, and preserving the corpus verbatim is what clone does.
        streams.out.writeAll("compatible import: preserving the corpus verbatim via the sync protocol\n") catch {};
        return cmd_clone.runClone(gpa, io, arena, &.{ source, dir }, streams, amb);
    }
    return fossil_import_cli.runSubmanifestImport(gpa, io, arena, source, dir, parsed.k, "import-fossil", streams, amb);
}

fn runImportGit(
    gpa: std.mem.Allocator,
    io: std.Io,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const parsed = cli.parseImportGitArgs(verb_args) catch |err| {
        // The conflict gets its own sentence: the generic form would print
        // "invalid arguments (ConflictingSubmanifestOptions)", which names the
        // cause without saying which two options collided or why.
        if (err == error.ConflictingSubmanifestOptions) {
            streams.err.writeAll("zit import-git: --no-submanifests and --submanifest-k cannot be combined; --submanifest-k tunes which k a tree import uses, it does not turn trees off\n") catch {};
            return .usage;
        }
        if (err == error.ConflictingAttributionOptions) {
            streams.err.writeAll("zit import-git: --use-author and --attribution committer cannot be combined; --use-author is --attribution author\n") catch {};
            return .usage;
        }
        streams.err.print("zit import-git: invalid arguments ({s}); see 'zit import-git --help'\n", .{@errorName(err)}) catch {};
        return .usage;
    };
    if (parsed.help) {
        streams.out.writeAll(help_pages.import_git_help) catch {};
        return .ok;
    }
    if (parsed.recorded_refs) return listRecordedRefs(gpa, io, parsed, streams);

    var result: git_import_cli.Result = .{};
    const rc = runImportGitParsed(gpa, io, parsed, streams, amb, &result);
    if (parsed.format == .json) result.write(streams.out) catch return .failure;
    return rc;
}

/// `zit import-git --recorded-refs DEST`: the refs DEST's map holds from its
/// last import, for a caller to compare with `git ls-remote` before it fetches.
fn listRecordedRefs(gpa: std.mem.Allocator, io: std.Io, parsed: cli.ImportGitArgs, streams: cli.Streams) cli.Exit {
    var destination = std.Io.Dir.cwd().openDir(io, parsed.destination, .{}) catch |err| {
        streams.err.print("import-git: cannot open '{s}': {s}\n", .{ parsed.destination, @errorName(err) }) catch {};
        return .failure;
    };
    defer destination.close(io);
    var map = zit.git_import_map.load(gpa, io, destination) catch |err| {
        if (err == error.Absent) {
            streams.err.print("import-git: '{s}' has no commit map; it was not written by import-git\n", .{parsed.destination}) catch {};
        } else {
            streams.err.print("import-git: cannot read the commit map of '{s}': {s}\n", .{ parsed.destination, @errorName(err) }) catch {};
        }
        return .failure;
    };
    defer map.deinit();
    zit.git_import_map.writeRecordedRefs(gpa, map.contents.refs, streams.out, switch (parsed.format) {
        .text => .text,
        .json => .json,
    }) catch |err| {
        streams.err.print("import-git: cannot list recorded refs: {s}\n", .{@errorName(err)}) catch {};
        return .failure;
    };
    return .ok;
}

fn runImportGitParsed(
    gpa: std.mem.Allocator,
    io: std.Io,
    parsed: cli.ImportGitArgs,
    streams: cli.Streams,
    amb: cli.Ambient,
    result: *git_import_cli.Result,
) cli.Exit {
    if (parsed.recover) {
        var destination = std.Io.Dir.cwd().openDir(io, parsed.destination, .{}) catch |err| {
            result.refuse("destination_missing");
            streams.err.print("import-git: cannot open recovery destination: {s}\n", .{@errorName(err)}) catch {};
            return .failure;
        };
        defer destination.close(io);
        return @import("git/git_import_into.zig").recoverResult(io, destination, streams, .{}, result);
    }
    const parent_path = std.fs.path.dirname(parsed.destination) orelse ".";
    const destination_name = std.fs.path.basename(parsed.destination);
    // The project code, derived from the new store's absolute path exactly as
    // `init` derives its own.
    const cwd = (cli.currentPathAlloc(gpa, io) catch |err| {
        streams.err.print("zit import-git: cannot determine the current directory: {s}\n", .{@errorName(err)}) catch {};
        return .failure;
    }) orelse {
        streams.err.writeAll("zit import-git: cannot determine the current directory\n") catch {};
        return .failure;
    };
    defer gpa.free(cwd);
    const abs_zit = std.fs.path.resolve(gpa, &.{ cwd, parsed.destination, zit.repo_filename }) catch |err| {
        streams.err.print("zit import-git: cannot resolve destination '{s}': {s}\n", .{ parsed.destination, @errorName(err) }) catch {};
        return .failure;
    };
    defer gpa.free(abs_zit);
    var destination_parent = std.Io.Dir.cwd().openDir(io, parent_path, .{}) catch |err| {
        streams.err.print("zit import-git: cannot open destination parent '{s}': {s}\n", .{ parent_path, @errorName(err) }) catch {};
        return .failure;
    };
    defer destination_parent.close(io);

    // `--with-submodules`: each submodule is imported beside DEST first, so
    // the parent's ledger can name the check-ins its pins became.
    var targets: ?@import("git/git_import_modules.zig").Targets = null;
    defer if (targets) |*t| t.deinit();
    if (parsed.with_submodules and !parsed.recover) {
        var env = amb.environ.createMap(gpa) catch return oomExit(streams);
        defer env.deinit();
        env.put("GIT_TERMINAL_PROMPT", "0") catch return oomExit(streams);
        const parent_abs = std.fs.path.resolve(gpa, &.{ cwd, parent_path }) catch return oomExit(streams);
        defer gpa.free(parent_abs);
        targets = @import("git/git_import_modules.zig").importSiblings(gpa, io, &env, parsed.source, parent_abs, streams, parsed.quiet) catch return oomExit(streams);
    }

    var git = git_import_cli.ProductionGit.init(gpa, io, amb.environ);
    defer git.deinit();
    git.setDefaultBranch(parsed.default_branch);
    git.setRefuseSigned(parsed.refuse_signed);
    var dependencies = git.dependencies(.real_filesystem);
    if (parsed.max_export_payload_bytes) |bytes| dependencies.limits.max_export_payload_bytes = bytes;
    return git_import_cli.run(gpa, io, .{
        .source = parsed.source,
        .destination_parent = destination_parent,
        .destination_name = destination_name,
        .project_code = zit.sync.deriveProjectCode(&.{abs_zit}),
        // The parser has already made the pair unreachable, so the branch is
        // total: `no_submanifests` implies `submanifest_k == null`.
        .submanifest = if (parsed.no_submanifests) .flat else .{ .tree = parsed.submanifest_k },
        .attribution = if (parsed.attribution) |attribution| switch (attribution) {
            .committer => .committer,
            .author => .author,
        } else null,
        .default_branch = parsed.default_branch,
        .migrate_default_branch = parsed.migrate_default_branch,
        .expect_default_branch = parsed.expect_default_branch,
        .expect_imported_head = parsed.expect_imported_head,
        .result = result,
        .json = parsed.format == .json,
        .quiet = parsed.quiet,
        .provenance = parsed.provenance,
        .into = parsed.into,
        .threads = parsed.threads orelse zit.store_workers.defaultThreads(),
        .refuse_signed = parsed.refuse_signed,
        .module_targets = if (targets) |*t| &t.by_oid else null,
    }, streams, dependencies);
}

fn oomExit(streams: cli.Streams) cli.Exit {
    streams.err.writeAll("zit import-git: out of memory\n") catch {};
    return .failure;
}

// ==========================================================================
// `zit commit` — mints a check-in (contracts/commit.md B-commit-1..20). The
// first verb that appends to the log AND advances the working state. A thin
// consumer: it decides which files at which content, hands the library RFC card
// structs, and the library owns all format work (`artifact.create` computes the
// Z self-check, orders/escapes cards, frames the artifact). No logic enters any
// library module; no `std.http`, no network; history is append-only. The one
// deep, RFC-normative unit — the F-set composition — is `cli.composeFCards`,
// pure and separately unit-tested; `runCommit` is thin wiring around it.
// ==========================================================================

/// Reads the whole-second wall clock for the D card (B-commit-7), preferring the
/// `SOURCE_DATE_EPOCH` reproducible-build convention when set (a well-known,
/// tell-free way to pin the clock across a process boundary — how the e2e suite
/// fixes the timestamp of the spawned binary). Falls back to the real
/// (wall-clock) `Io.Clock`. The single ambient-time read in the CLI.
fn commitEpoch(io: std.Io, env: *const std.process.Environ.Map) i64 {
    if (env.get("SOURCE_DATE_EPOCH")) |raw| {
        const trimmed = std.mem.trim(u8, raw, " \t\r\n");
        if (std.fmt.parseInt(i64, trimmed, 10)) |v| return v else |_| {}
    }
    return Io.Timestamp.now(io, .real).toSeconds();
}

/// The millisecond within `commitEpoch`'s second. Deterministic runs
/// (SOURCE_DATE_EPOCH) pin 0, so a reproducible build stays reproducible;
/// a live clock reads the real sub-second remainder.
fn commitEpochMs(io: std.Io, env: *const std.process.Environ.Map) u16 {
    if (env.get("SOURCE_DATE_EPOCH") != null) return 0;
    const ns = Io.Timestamp.now(io, .real).nanoseconds;
    const ms: i64 = @intCast(@mod(@divFloor(ns, std.time.ns_per_ms), 1000));
    return @intCast(ms);
}

fn runUi(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, verb_args: []const []const u8, streams: cli.Streams, amb: cli.Ambient) cli.Exit {
    if (verb_args.len != 0 and (std.mem.eql(u8, verb_args[0], "-h") or std.mem.eql(u8, verb_args[0], "--help"))) {
        streams.out.writeAll(help_pages.ui_help) catch {};
        return .ok;
    }
    const root = (cli.discoverRoot(arena, io) catch return diagnostics.stateOom(streams, "ui")) orelse {
        streams.err.writeAll(diagnostics.not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    root_dir.close(io);
    var env_map = amb.environ.createMap(gpa) catch return diagnostics.stateOom(streams, "ui");
    defer env_map.deinit();
    const bin: []const u8 = env_map.get("ZIT_QUARRY") orelse "quarry";
    var argv: std.ArrayList([]const u8) = .empty;
    argv.append(arena, bin) catch return diagnostics.stateOom(streams, "ui");
    argv.append(arena, "ui") catch return diagnostics.stateOom(streams, "ui");
    argv.append(arena, root.abs) catch return diagnostics.stateOom(streams, "ui");
    for (verb_args) |a| argv.append(arena, a) catch return diagnostics.stateOom(streams, "ui");
    streams.out.flush() catch {};
    streams.err.flush() catch {};
    var child = std.process.spawn(io, .{ .argv = argv.items, .environ_map = &env_map }) catch {
        streams.err.print(
            "zit ui: '{s}' could not be started; the browser view is quarry's single-repository local mode\n" ++
                "install quarry (https://github.com/danmestas/quarry) or set ZIT_QUARRY to the binary\n" ++
                "meanwhile: 'zit diff --by' renders a side-by-side page and 'zit timeline -F html' renders the timeline\n",
            .{bin},
        ) catch {};
        return .failure;
    };
    const term = child.wait(io) catch return .failure;
    return switch (term) {
        .exited => |code| if (code == 0) .ok else .failure,
        else => .failure,
    };
}

/// What `zit version` prints and the daemon's `hello` reports.
pub const zit_version = "0.14.7";

test {
    // Pull the CLI harness's inline unit tests into `zig build test`. The
    // repo-view loader and its cache now live in the `zit` module and aggregate
    // through root.zig, so they are not re-imported here.

    _ = @import("transport.zig");
    _ = @import("serve.zig");
    _ = @import("sync_driver.zig");
    _ = @import("sync_driver_test.zig");
    _ = @import("cmd/sync.zig");
    _ = @import("cmd/serve.zig");
    _ = @import("cmd/clone.zig");
    _ = @import("cmd/open.zig");
    _ = @import("cmd/pull.zig");
    _ = @import("cmd/push.zig");
    _ = @import("cmd/pack.zig");
    _ = @import("cmd/shun.zig");
    _ = @import("cmd/uv.zig");
    _ = @import("cmd/remote.zig");
    _ = @import("cmd/settings.zig");
    _ = @import("cmd/config.zig");
    _ = @import("cmd/sync_dialogue.zig");
    _ = @import("cmd/sync_test_support.zig");
    _ = @import("bench/submanifest_benchmark.zig");
    _ = @import("cmd/tracking.zig");
    _ = @import("cmd/users.zig");
    _ = @import("cmd/stat.zig");
    _ = @import("cmd/log.zig");
    _ = @import("cmd/leaves.zig");
    _ = @import("cmd/timeline.zig");
    _ = @import("cmd/branch.zig");
    _ = @import("cmd/tag.zig");
    _ = @import("cmd/info.zig");
    _ = @import("cmd/ls.zig");
    _ = @import("cmd/merge_base.zig");
    _ = @import("cmd/cat.zig");
    _ = @import("cmd/artifact.zig");
    _ = @import("cmd/annotate.zig");
    _ = @import("cmd/frames.zig");
    _ = @import("cmd/grep.zig");
    _ = @import("cmd/crosslink.zig");
    _ = @import("cmd/checkin_display.zig");
    _ = @import("cmd/update.zig");
    _ = @import("cmd/cone.zig");
    _ = @import("cmd/bisect.zig");
    _ = @import("cmd/merge.zig");
    _ = @import("cmd/revert.zig");
    _ = @import("cmd/undo.zig");
    _ = @import("cmd/commit.zig");
    _ = @import("cmd/amend.zig");
    _ = @import("cmd/submanifest.zig");
    _ = @import("cmd/checkpoint.zig");
    _ = @import("cmd/worktrees.zig");
    _ = @import("cmd/trust.zig");
    _ = @import("cmd/control_artifact.zig");
    _ = @import("cmd/verify.zig");
    _ = @import("help.zig");
}

/// A fixed `Ambient` for the in-process dispatch tests: a pinned epoch (no wall
/// clock) and no environment author. Verbs other than `commit` ignore it; the
/// commit dispatch tests that reach assembly pin their own values via the e2e
/// harness (the real binary), so this constant is only the argument shape.
const test_amb: cli.Ambient = .{ .now_epoch = 0, .user_env = null };

// --- status error-mapper unit tests (B-status-10/-11; pure switches) -------

test "status B-status-10: CheckoutError maps to the contract messages and exit 1" {
    const Case = struct { err: checkout.CheckoutError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.Corrupt, .want = "zit status: cannot read checkout state: .zit-checkout is corrupt\n" },
        .{ .err = error.Storage, .want = "zit status: cannot read checkout state: input/output error\n" },
    };
    for (cases) |c| {
        var buf: [256]u8 = undefined;
        var w = Io.Writer.fixed(&buf);
        var sink: [1]u8 = undefined;
        var wnull = Io.Writer.fixed(&sink);
        const s: cli.Streams = .{ .out = &wnull, .err = &w };
        try std.testing.expectEqual(cli.Exit.failure, diagnostics.checkoutFail(s, "status", c.err));
        try std.testing.expectEqualStrings(c.want, w.buffered());
    }
}

test "status B-status-11: ManagedError maps to the contract messages and exit 1" {
    const Case = struct { err: managed.ManagedError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.Corrupt, .want = "zit status: cannot read tracked files: .zit-checkout is corrupt\n" },
        .{ .err = error.Storage, .want = "zit status: cannot read tracked files: input/output error\n" },
        .{ .err = error.TooLong, .want = "zit status: cannot read tracked files: a tracked path is too long\n" },
        .{ .err = error.TooMany, .want = "zit status: cannot read tracked files: too many tracked files\n" },
        .{ .err = error.OutOfMemory, .want = "zit status: out of memory\n" },
    };
    for (cases) |c| {
        var buf: [256]u8 = undefined;
        var w = Io.Writer.fixed(&buf);
        var sink: [1]u8 = undefined;
        var wnull = Io.Writer.fixed(&sink);
        const s: cli.Streams = .{ .out = &wnull, .err = &w };
        try std.testing.expectEqual(cli.Exit.failure, diagnostics.managedFail(s, "status", c.err));
        try std.testing.expectEqualStrings(c.want, w.buffered());
    }
}

test "status B-status-9: stateOom renders the out-of-memory message and exit 1" {
    var buf: [64]u8 = undefined;
    var w = Io.Writer.fixed(&buf);
    var sink: [1]u8 = undefined;
    var wnull = Io.Writer.fixed(&sink);
    const s: cli.Streams = .{ .out = &wnull, .err = &w };
    try std.testing.expectEqual(cli.Exit.failure, diagnostics.stateOom(s, "status"));
    try std.testing.expectEqualStrings("zit status: out of memory\n", w.buffered());
}

// --- status dispatch: the io/alloc-free paths, driven in-process -----------
//
// `--help` and the two usage errors touch neither the filesystem nor the
// allocators, so they run through `run()` over fixed-buffer writers — the same
// technique the unknown-command dispatch tests use — with the exact argv.

/// Drives `run()` for `zit status <tail...>` over fixed-buffer writers,
/// returning the exit code and the captured stdout/stderr (valid until the next
/// call). Sized to hold the whole `status_help` block on stdout.
fn runStatusCapture(tail: []const []const u8) struct { code: cli.Exit, out: []const u8, err: []const u8 } {
    const S = struct {
        var out_buf: [4096]u8 = undefined;
        var err_buf: [512]u8 = undefined;
    };
    var out = Io.Writer.fixed(&S.out_buf);
    var err = Io.Writer.fixed(&S.err_buf);
    const streams: cli.Streams = .{ .out = &out, .err = &err };
    var argv_buf: [8][]const u8 = undefined;
    argv_buf[0] = "zit";
    argv_buf[1] = "status";
    for (tail, argv_buf[2..][0..tail.len]) |src, *dst| dst.* = src;
    const code = run(
        std.testing.allocator,
        std.testing.io,
        std.testing.allocator,
        argv_buf[0 .. 2 + tail.len],
        streams,
        test_amb,
    );
    return .{ .code = code, .out = out.buffered(), .err = err.buffered() };
}

test "status B-status-12: an unknown option is a usage error (exit 2, stderr, empty stdout)" {
    const r = runStatusCapture(&.{"-x"});
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit status: unknown option '-x'\ntry 'zit status --help'\n",
        r.err,
    );
}

test "status B-status-13: an unexpected argument is a usage error (exit 2, stderr, empty stdout)" {
    const r = runStatusCapture(&.{"foo"});
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit status: unexpected argument 'foo'\ntry 'zit status --help'\n",
        r.err,
    );
}

test "status B-status-14: --help prints the help to stdout (exit 0, empty stderr)" {
    const r = runStatusCapture(&.{"--help"});
    try std.testing.expectEqual(cli.Exit.ok, r.code);
    try std.testing.expectEqualStrings(help_pages.status_help, r.out);
    try std.testing.expectEqualStrings("", r.err);
}

test "status B-status-16 DX-D4: 'zit help status' routes to the verb's own help" {
    // `run()`'s help arm touches neither io nor the allocators, so the topic
    // routing is driven in-process; the stdout must be byte-identical to
    // `status --help` (the DX-D4 fix: `zit help status` no longer prints the
    // general command list that implied the verb was absent).
    var out_buf: [4096]u8 = undefined;
    var err_buf: [256]u8 = undefined;
    var out = Io.Writer.fixed(&out_buf);
    var err = Io.Writer.fixed(&err_buf);
    const streams: cli.Streams = .{ .out = &out, .err = &err };
    const code = run(
        std.testing.allocator,
        std.testing.io,
        std.testing.allocator,
        &.{ "zit", "help", "status" },
        streams,
        test_amb,
    );
    try std.testing.expectEqual(cli.Exit.ok, code);
    try std.testing.expectEqualStrings(help_pages.verb_help.get(.status).?, out.buffered());
    try std.testing.expectEqualStrings("", err.buffered());
}

test "init B-init-3: default hash_kind is SHA3-256 (= 2)" {
    // Guards the byte the header stores for a fresh repo (artifact §7.2-m2).
    try std.testing.expectEqual(@as(u8, 2), @backingInt(zit.artifact.defaultPolicy(false, false)));
}

// --- unknown-command dispatch (DX D2/D4), verified through `run()` ----------
//
// `run()` on an unknown verb touches neither io nor the allocators, so these
// drive it in-process over fixed-buffer writers — no subprocess needed — and
// assert the same exit-2 / stderr-only contract the e2e suite holds for init.

/// Runs `zit <verb>` through `run()`, returning the exit code plus the captured
/// stdout/stderr slices (valid until the next call — backed by static buffers,
/// so a test uses one invocation at a time).
const RunCapture = struct {
    code: cli.Exit,
    out: []const u8,
    err: []const u8,

    var out_buf: [256]u8 = undefined;
    var err_buf: [512]u8 = undefined;

    fn run_verb(verb: []const u8) RunCapture {
        return run_argv(&.{ "zit", verb });
    }

    /// Like `run_verb` but with the full argv (post-"zit" tokens included), for
    /// verbs whose diagnostic depends on an option. Only safe for control paths
    /// that return before `discoverRoot` (which allocates into the arena — here
    /// `testing.allocator` — and is freed en masse by a real arena in `main`).
    fn run_argv(argv: []const []const u8) RunCapture {
        var out = Io.Writer.fixed(&out_buf);
        var err = Io.Writer.fixed(&err_buf);
        const streams: cli.Streams = .{ .out = &out, .err = &err };
        const code = run(std.testing.allocator, std.testing.io, std.testing.allocator, argv, streams, test_amb);
        return .{ .code = code, .out = out.buffered(), .err = err.buffered() };
    }
};

/// Asserts a git-reflex `verb` renders its teaching line: exit 2, stdout empty,
/// stderr naming the verb, stating it is not a zit command, and containing the
/// lesson keyword `teaches`.
fn expectReflex(verb: []const u8, teaches: []const u8) !void {
    const r = RunCapture.run_verb(verb);
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, verb) != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "is not a zit command") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, teaches) != null);
}

test "cli D2 B-init-12: 'rebase' teaches immutable history, exit 2 stderr-only" {
    try expectReflex("rebase", "history is immutable");
}
test "cli amend B-amend-12: 'amend' dispatches to the real handler, not the git-reflex lesson" {
    // amend is a real verb now (removed from `reflex_table`): `zit amend` with no
    // NAME is amend's OWN usage error, never the immutable-history reflex lesson —
    // teaching against a fossil-semantics amend with that lesson would conflate it
    // with git's history-rewriting amend.
    const r = RunCapture.run_verb("amend");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "is not a zit command") == null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "no name given") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "try 'zit amend --help'") != null);
}
test "cli D2 B-init-12: 'reset' teaches immutable history, exit 2 stderr-only" {
    try expectReflex("reset", "history is immutable");
}
test "cli D2 B-init-12: 'filter-branch' teaches immutable history, exit 2 stderr-only" {
    try expectReflex("filter-branch", "history is immutable");
}
test "cli: 'checkout' is an alias of 'update' and dispatches to it" {
    // An unknown option draws update's own usage error — proof the alias
    // reached the real handler rather than a git-reflex lesson. (A bare
    // `update` is no longer a usage error: it means --latest.)
    const r = RunCapture.run_argv(&.{ "zit", "checkout", "--nope" });
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "is not a zit command") == null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "update") != null);
}
test "cli push: an unknown option is a usage error before any I/O (real verb, dispatched)" {
    // `push` is a real handler, not a git-reflex redirect. Under M4 an omitted URL
    // is no longer an immediate usage error (it falls back to the saved remote),
    // but a malformed option is still rejected by the arg parser before any I/O —
    // exit 2, the diagnostic on stderr, empty stdout — proving real dispatch.
    const r = RunCapture.run_argv(&.{ "zit", "push", "--nope" });
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit push: unknown option '--nope'\ntry 'zit push --help'\n",
        r.err,
    );
}
test "cli pull: an unknown option is a usage error before any I/O (real verb, dispatched)" {
    // `pull` is a real handler, not a git-reflex redirect. Under M4 an omitted URL
    // falls back to the saved remote rather than erroring immediately; a malformed
    // option is still rejected before any I/O — exit 2, stderr-only.
    const r = RunCapture.run_argv(&.{ "zit", "pull", "--nope" });
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit pull: unknown option '--nope'\ntry 'zit pull --help'\n",
        r.err,
    );
}

test "cli D2 B-init-12: 'fetch' teaches bidirectional sync, exit 2 stderr-only" {
    try expectReflex("fetch", "zit sync");
}
test "cli D2 B-init-12: 'stash' states it is not implemented, exit 2 stderr-only" {}
test "cli commit B-commit-5: 'zit commit' with no -m is a usage error (real verb, dispatched)" {
    // Regression: `commit` is now a real handler, not a planned stub. `run()`'s
    // commit arm raises the missing-message usage error before any I/O, so this
    // is driven in-process — exit 2, stderr the B-commit-5 message, empty stdout.
    const r = RunCapture.run_verb("commit");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit commit: a check-in message is required\n" ++
            "  give one with -m <message>,\n" ++
            "  run from a terminal to compose it in $EDITOR,\n" ++
            "  or set an editor: zit settings editor <command>\n" ++
            "try 'zit commit --help'\n",
        r.err,
    );
}
test "cli clone: 'zit clone' with no arguments is a usage error (real verb, dispatched)" {
    // `clone` is now a real handler, not a planned stub. `run()`'s clone arm
    // parses the empty argument list and raises the missing-URL usage error
    // before any I/O — exit 2, the diagnostic on stderr, empty stdout.
    const r = RunCapture.run_verb("clone");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expectEqualStrings(
        "zit clone: no repository URL given\ntry 'zit clone --help'\n",
        r.err,
    );
}

test "cli D4 B-init-12: a near-miss verb suggests the closest command, exit 2 stderr-only" {
    // `ini` would now resolve as a prefix of `init`; a transposition
    // is the near-miss that still needs a suggestion.
    const r = RunCapture.run_verb("inti");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "unknown command 'inti'") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "did you mean 'init'?") != null);
}

test "cli D4 B-init-12: a typo of a planned verb suggests the canonical command" {
    // `comit` is neither reflex nor exactly planned; the generic path should
    // suggest the planned canonical `commit` (planned verbs join the near-miss
    // set), so the typo does not dead-end.
    const r = RunCapture.run_verb("comit");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "unknown command 'comit'") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "did you mean 'commit'?") != null);
}

test "cli D4 B-init-12: a typo of 'update' suggests it (every dispatched verb is suggestable)" {
    // `update` is a real dispatched verb, so a near-miss must land on it. Guards
    // against the suggester's candidate list drifting from the dispatched set.
    const r = RunCapture.run_verb("updtae");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "unknown command 'updtae'") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "did you mean 'update'?") != null);
}

test "cli D4 B-init-12: a distant unknown lists commands with no misleading guess" {
    const r = RunCapture.run_verb("florble");
    try std.testing.expectEqual(cli.Exit.usage, r.code);
    try std.testing.expectEqualStrings("", r.out);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "unknown command 'florble'") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "did you mean") == null);
    // Two lines, not the command list.
    try std.testing.expect(std.mem.indexOf(u8, r.err, "try 'zit help'") != null);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "commands:") == null);
}

// --- commit error-mapper unit tests (B-commit-15; pure switches) -----------

test "update: ApplyError maps to the contract messages and exit 1, exhaustively over all 23 variants" {
    const target_id = repeat("1", 40);
    const Case = struct { err: update.ApplyError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.OutOfMemory, .want = "zit update: out of memory\n" },
        .{
            .err = error.InvalidCheckinId,
            .want = "zit update: invalid check-in ID '" ++ target_id ++ "' (expected 40 or 64 lowercase hexadecimal digits)\n",
        },
        .{ .err = error.CheckinNotFound, .want = "zit update: check-in '" ++ target_id ++ "' not found\n" },
        .{
            .err = error.CheckinContentMissing,
            .want = "zit update: cannot read repository: check-in '" ++ target_id ++ "' content is missing\n",
        },
        .{
            .err = error.CheckinNameMismatch,
            .want = "zit update: cannot read repository: check-in '" ++ target_id ++ "' content does not match its name\n",
        },
        .{ .err = error.TargetNotManifest, .want = "zit update: check-in '" ++ target_id ++ "' is not a valid manifest\n" },
        .{
            .err = error.BaselineNotFound,
            .want = "zit update: cannot read repository: check-in '" ++ target_id ++ "' baseline is not found\n",
        },
        .{
            .err = error.BaselineContentMissing,
            .want = "zit update: cannot read repository: check-in '" ++ target_id ++ "' baseline content is missing\n",
        },
        .{
            .err = error.BaselineNameMismatch,
            .want = "zit update: cannot read repository: check-in '" ++ target_id ++ "' baseline content does not match its name\n",
        },
        .{
            .err = error.BaselineNotManifest,
            .want = "zit update: check-in '" ++ target_id ++ "' baseline is not a valid manifest\n",
        },
        .{
            .err = error.StateRecordInvalid,
            .want = "zit update: cannot read repository: " ++ update.state_record_invalid_reason ++ "\n",
        },
        .{ .err = error.InvalidPath, .want = "zit update: check-in '" ++ target_id ++ "' names an invalid file path\n" },
        .{ .err = error.ReservedPath, .want = "zit update: check-in '" ++ target_id ++ "' names a reserved file path\n" },
        .{
            .err = error.SymlinkUnsupported,
            .want = "zit update: check-in '" ++ target_id ++ "' contains an unsupported symlink entry\n",
        },
        .{ .err = error.CurrentStateInvalid, .want = "zit update: current working-tree state is invalid\n" },
        .{ .err = error.WorktreeNotClean, .want = "zit update: working tree is not clean\n" },
        .{ .err = error.Corrupt, .want = "zit update: cannot read repository: repository is corrupt\n" },
        .{ .err = error.UnmanagedCollision, .want = "zit update: an untracked file or directory is in the way\n" },
        .{ .err = error.Storage, .want = "zit update: cannot update working tree: input/output error\n" },
        .{ .err = error.TransactionUnavailable, .want = "zit update: cannot create a transaction directory\n" },
        .{
            .err = error.RollbackFailed,
            .want = "zit update: update failed and could not be rolled back; the previous working-tree state is retained for recovery\n",
        },
        .{
            .err = error.CleanupFailed,
            .want = "zit update: update committed, but the transaction directory could not be removed\n",
        },
    };
    for (cases) |c| {
        var buf: [256]u8 = undefined;
        var w = Io.Writer.fixed(&buf);
        var sink: [1]u8 = undefined;
        var wnull = Io.Writer.fixed(&sink);
        const s: cli.Streams = .{ .out = &wnull, .err = &w };
        try std.testing.expectEqual(cli.Exit.failure, cmd_update.updateApplyFail(s, target_id, c.err));
        try std.testing.expectEqualStrings(c.want, w.buffered());
    }
}

/// Render one `ApplyError` through `updateApplyFail` and return the stderr text.
fn updateFailText(buf: []u8, err: update.ApplyError) []const u8 {
    var w = Io.Writer.fixed(buf);
    var sink: [1]u8 = undefined;
    var wnull = Io.Writer.fixed(&sink);
    const s: cli.Streams = .{ .out = &wnull, .err = &w };
    _ = cmd_update.updateApplyFail(s, repeat("1", 40), err);
    return w.buffered();
}

// `Corrupt` and `StateRecordInvalid` are two different claims and must never
// share a diagnostic again. `Corrupt` says stored bytes do not match the name
// they are stored under — real damage. `StateRecordInvalid` says nothing about
// the repository's integrity: a stored artifact was not usable as a state
// record. An intact fossil clone reaches it routinely, because fossil stores
// and syncs artifacts it itself declines to crosslink, so answering it with a
// corruption claim accuses an undamaged repository.
test "update: the two read-path failures do not share a diagnostic" {
    var a: [256]u8 = undefined;
    var b: [256]u8 = undefined;
    const corrupt = updateFailText(&a, error.Corrupt);
    const state = updateFailText(&b, error.StateRecordInvalid);

    try std.testing.expect(!std.mem.eql(u8, corrupt, state));

    // Only the integrity failure may allege corruption.
    try std.testing.expect(std.mem.indexOf(u8, corrupt, "corrupt") != null);
    try std.testing.expect(std.mem.indexOf(u8, state, "corrupt") == null);
}

test "tracked file size limit admits its boundary" {
    const limit: u64 = cmd_tracking.max_tracked_file_bytes;
    try std.testing.expect(cmd_tracking.trackedFileSizeAllowed(limit - 1));
    try std.testing.expect(cmd_tracking.trackedFileSizeAllowed(limit));
    try std.testing.expect(!cmd_tracking.trackedFileSizeAllowed(limit + 1));
}

test "the tracked-file ceiling is the storage frame ceiling, not a policy number" {
    // The comptime assert beside the declaration is the real enforcement; this
    // states the same tie as a readable claim, and says WHY it is not tunable:
    // `logstore.put`/`putArtifact` assert on `max_payload`, so admitting a file
    // above it would trip an assert during commit rather than refuse the file.
    try std.testing.expectEqual(logstore.max_payload, @as(u64, cmd_tracking.max_tracked_file_bytes));

    // The largest admissible file is exactly one storable frame — the boundary
    // the assert allows, not one byte inside or outside it.
    try std.testing.expect(cmd_tracking.trackedFileSizeAllowed(logstore.max_payload));
    try std.testing.expect(!cmd_tracking.trackedFileSizeAllowed(logstore.max_payload + 1));
}

// --- renderBranchList unit tests (repo-state §6.1/§6.3/§6.4/§9) -------------
// The derived §6.3 state (which rid represents a branch, its closed status, the
// grouping) is proven in repostate_test.zig; these tests fix only the CLI
// presentation over hand-built BranchEntry values transcribed from §6.3.

const BranchEntry = repostate.RepoState.BranchEntry;

/// Renders `entries`/`current` into a fixed buffer and returns the written
/// slice — the shared body of the presentation tests.
fn renderBranchesToBuf(buf: []u8, entries: []const BranchEntry, current: ?[]const u8) []const u8 {
    var w = Io.Writer.fixed(buf);
    cmd_branch.renderBranchList(&w, entries, current);
    return w.buffered();
}

test "renderBranchList §6.3: a representative-closed branch renders \"(closed)\"" {
    // §6.3 divergence: a forked branch whose greatest-mtime representative is
    // closed lists as closed even while an older leaf stays open. The closed
    // flag is the representative-row property; render appends the marker.
    const entries = [_]BranchEntry{
        .{ .name = "trunk", .tip = 1, .mtime = 3, .count = 2, .closed = true },
    };
    var buf: [64]u8 = undefined;
    try std.testing.expectEqualStrings("  trunk  (closed)\n", renderBranchesToBuf(&buf, &entries, null));
}

test "renderBranchList §6.3: multiple branches render name-ascending, current marked once" {
    // `branches` returns entries name-ascending; render preserves that order and
    // marks exactly the current branch, indenting the rest.
    const entries = [_]BranchEntry{
        .{ .name = "feature", .tip = 2, .mtime = 5, .count = 1, .closed = false },
        .{ .name = "trunk", .tip = 1, .mtime = 9, .count = 3, .closed = false },
    };
    var buf: [64]u8 = undefined;
    try std.testing.expectEqualStrings(
        "* feature\n  trunk\n",
        renderBranchesToBuf(&buf, &entries, "feature"),
    );
}

test "renderBranchList §9: a forked branch (two leaves) renders as one line" {
    // §9: a branch with more than one leaf is forked but is still a single §6.3
    // entry (count > 1), so it lists on exactly one line.
    const entries = [_]BranchEntry{
        .{ .name = "trunk", .tip = 7, .mtime = 4, .count = 2, .closed = false },
    };
    var buf: [64]u8 = undefined;
    const out = renderBranchesToBuf(&buf, &entries, "trunk");
    try std.testing.expectEqualStrings("* trunk\n", out);
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\n"));
}

test "renderBranchList §6.4: a null current-branch marks no row" {
    // Negative space: with no resolvable current branch, no line carries "*".
    const entries = [_]BranchEntry{
        .{ .name = "feature", .tip = 2, .mtime = 5, .count = 1, .closed = false },
        .{ .name = "trunk", .tip = 1, .mtime = 9, .count = 1, .closed = false },
    };
    var buf: [64]u8 = undefined;
    const out = renderBranchesToBuf(&buf, &entries, null);
    try std.testing.expectEqualStrings("  feature\n  trunk\n", out);
    try std.testing.expect(std.mem.indexOfScalar(u8, out, '*') == null);
}

test "renderBranchList §6.1: the configured main-branch name marks its row (not a literal)" {
    // The current-branch name is whatever branchOf returned through the config
    // main-branch — here "mainline", not "trunk". Render marks that row, so a
    // non-trunk default is honored end to end.
    const entries = [_]BranchEntry{
        .{ .name = "mainline", .tip = 1, .mtime = 9, .count = 1, .closed = false },
        .{ .name = "trunk", .tip = 2, .mtime = 3, .count = 1, .closed = false },
    };
    var buf: [64]u8 = undefined;
    try std.testing.expectEqualStrings(
        "* mainline\n  trunk\n",
        renderBranchesToBuf(&buf, &entries, "mainline"),
    );
}