Skip to content
zit Artifact [0c705f0df2]
Login

Artifact [0c705f0df2]

Artifact 0c705f0df20ba7e185bb478ef67c5580d1c3b833754c35daf0db95260691a4d3:


//! 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 Io = std.Io;
const File = Io.File;
const zit = @import("zit");
const cli = @import("cli.zig");
const merge3 = @import("merge3.zig");
const extras = @import("extras.zig");

// 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. `Repository` is the deep read-path facade; `zit.repoview` is its
// derived-view collaborator, reached directly only by the pack verify test.
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const bisect = @import("zit").bisect;
const Repository = @import("zit").Repository;
const serve_mod = @import("serve.zig");
// 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_tracking = @import("cmd/tracking.zig");
const cmd_history = @import("cmd/history.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;

pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;
    const arena = init.arena.allocator();
    const io = 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),
        .user_env = init.environ_map.get("USER") orelse init.environ_map.get("LOGNAME"),
        .push_password = init.environ_map.get("ZIT_PASSWORD"),
    };

    const code = run(gpa, io, arena, args, streams, amb);

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

/// Each verb's `--help` block, keyed by `cli.Verb` — the one place a verb is
/// paired with its help text. `zit help <verb>` and `zit <verb> --help` both
/// read this, so they teach identical text (DX D4). Verbs with no dedicated
/// help (`version`, `help`) and the `unknown` catch-all map to `null`; the
/// caller then falls back to `top_usage`. Keyed by the enum, so a new verb
/// forces a matching entry here at compile time — no help topic can silently
/// drop.
const verb_help = std.EnumArray(cli.Verb, ?[]const u8).init(.{
    .init = init_help,
    .add = add_help,
    .rm = rm_help,
    .mv = mv_help,
    .status = status_help,
    .stat = stat_help,
    .diff = diff_help,
    .extras = extras_help,
    .clean = clean_help,
    .addremove = addremove_help,
    .commit = commit_help,
    .log = log_help,
    .open = open_help,
    .update = update_help,
    .merge = merge_help,
    .revert = revert_help,
    .undo = undo_help,
    .redo = redo_help,
    .leaves = leaves_help,
    .timeline = timeline_help,
    .branch = branch_help,
    .tag = tag_help,
    .amend = amend_help,
    .info = info_help,
    .ls = ls_help,
    .cat = cat_help,
    .artifact = artifact_help,
    .annotate = annotate_help,
    .bisect = bisect_help,
    .serve = serve_help,
    .clone = clone_help,
    .pull = pull_help,
    .push = push_help,
    .sync = sync_help,
    .remote = remote_help,
    .pack = pack_help,
    .version = null,
    .help = null,
    .unknown = null,
});

/// The `--help` block for a verb named on the command line, or `null` when the
/// verb carries no dedicated help (or the name is unknown) — the caller then
/// falls back to `top_usage`. Resolves the name through `cli.verbOf` so help
/// topics track the dispatched verb set exactly.
fn helpFor(name: []const u8) ?[]const u8 {
    return verb_help.get(cli.verbOf(name));
}

/// 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`.
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 &.{};
    const global = cli.parseGlobalArgs(arena, raw_args) catch
        return stateOom(streams, verb);
    const verb_args = switch (global) {
        .ok => |g| blk: {
            if (g.repo != null and !cli.acceptsRepoOverride(cli.verbOf(verb)))
                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,
        .user_env = amb.user_env,
        .push_password = amb.push_password,
        .repo_override = switch (global) {
            .ok => |g| g.repo,
            else => unreachable, // every other arm returned above
        },
    };

    switch (cli.verbOf(verb)) {
        .init => return runInit(gpa, io, arena, verb_args, streams),
        .add => return cmd_tracking.runAdd(gpa, io, arena, verb_args, streams),
        .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),
        .stat => return cmd_history.runStat(gpa, io, arena, verb_args, streams),
        .diff => return cmd_tracking.runDiff(gpa, io, arena, verb_args, streams),
        .extras => return cmd_tracking.runExtras(gpa, io, arena, verb_args, streams),
        .clean => return cmd_tracking.runClean(gpa, io, arena, verb_args, streams),
        .addremove => return cmd_tracking.runAddremove(gpa, io, arena, verb_args, streams),
        .commit => return runCommit(gpa, io, arena, verb_args, streams, amb_r),
        .log => return cmd_history.runLog(gpa, io, arena, verb_args, streams, amb_r),
        .open => return cmd_sync.runOpen(gpa, io, arena, verb_args, streams),
        .update => return runUpdate(gpa, io, arena, verb_args, streams),
        .merge => return runMerge(gpa, io, arena, verb_args, streams),
        .revert => return runRevert(gpa, io, arena, verb_args, streams),
        .undo => return runUndo(gpa, io, arena, verb_args, streams),
        .redo => return runRedo(gpa, io, arena, verb_args, streams),
        .leaves => return cmd_history.runLeaves(gpa, io, arena, verb_args, streams, amb_r),
        .timeline => return cmd_history.runTimeline(gpa, io, arena, verb_args, streams, amb_r),
        .branch => return cmd_history.runBranch(gpa, io, arena, verb_args, streams, amb_r),
        .tag => return cmd_history.runTag(gpa, io, arena, verb_args, streams, amb_r),
        .amend => return runAmend(gpa, io, arena, verb_args, streams, amb_r),
        .info => return cmd_history.runInfo(gpa, io, arena, verb_args, streams, amb_r),
        .ls => return cmd_history.runLs(gpa, io, arena, verb_args, streams, amb_r),
        .cat => return cmd_history.runCat(gpa, io, arena, verb_args, streams, amb_r),
        .artifact => return cmd_history.runArtifact(gpa, io, arena, verb_args, streams, amb_r),
        .annotate => return cmd_history.runAnnotate(gpa, io, arena, verb_args, streams, amb_r),
        .bisect => return runBisect(gpa, io, arena, verb_args, streams),
        .serve => return cmd_sync.runServe(gpa, io, arena, verb_args, streams),
        .clone => return cmd_sync.runClone(gpa, io, arena, verb_args, streams),
        .pull => return cmd_sync.runPull(gpa, io, arena, verb_args, streams),
        .push => return cmd_sync.runPush(gpa, io, arena, verb_args, streams, amb_r),
        .sync => return cmd_sync.runSync(gpa, io, arena, verb_args, streams, amb_r),
        .remote => return cmd_sync.runRemote(gpa, io, arena, verb_args, streams),
        .pack => return cmd_sync.runPack(gpa, io, arena, verb_args, streams),
        .version => {
            streams.out.writeAll("zit 0.0.0 (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 (helpFor(args[2])) |topic_help| {
                    streams.out.writeAll(topic_help) catch {};
                    return .ok;
                }
            }
            streams.out.writeAll(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 {};
            }
            streams.err.writeAll("\n") catch {};
            streams.err.writeAll(top_usage) catch {};
            return .usage;
        },
    }
}

/// `zit init [-q|--quiet] [--] [directory]` — the thin wiring: parse, resolve
/// an absolute target, then drive the existing library sequence (create `.zit`,
/// `LogStore.open`/`commit`/`deinit`, `checkout.write`). Filesystem access is
/// confined to this function. All-or-nothing: any failure after `.zit` is
/// created rolls it back so a failed init never poisons the already-exists
/// guard (B-init-9). (contracts/init.md B-init-1..12.)
pub fn runInit(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    // 1. Parse (B-init-1). Usage errors → exit 2 (B-init-10).
    const parsed = switch (cli.parseInitArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "init", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "init", .extra_argument, tok),
    };
    // --help wins over every effect (B-init-11).
    if (parsed.help) {
        streams.out.writeAll(init_help) catch {};
        return .ok;
    }

    // 2. Resolve an absolute target directory and repo path (B-init-2/5/12).
    //    `resolve` normalizes `.`/`..` and, when `dir_arg` is already
    //    absolute, ignores the cwd — yielding a stable, parseable success token.
    const dir_arg = parsed.directory orelse ".";
    // Uses the grow-buffer helper (not std's `currentPathAlloc`, which aborts on
    // a cwd deeper than the platform PATH_MAX). A cwd we cannot name is reported
    // honestly, never a crash.
    const cwd = (cli.currentPathAlloc(arena, io) catch |e|
        return renderStorage(streams, dir_arg, reasonOf(e))) orelse
        return renderStorage(streams, dir_arg, "cannot determine the current directory");
    const abs_dir = std.fs.path.resolve(arena, &.{ cwd, dir_arg }) catch |e|
        return renderStorage(streams, dir_arg, reasonOf(e));
    const abs_zit = std.fs.path.join(arena, &.{ abs_dir, repo_filename }) catch |e|
        return renderStorage(streams, abs_dir, reasonOf(e));

    // 3. Ensure the target directory exists (B-init-5); a file in the way is
    //    "not a directory" (B-init-8).
    const cwd_dir = std.Io.Dir.cwd();
    cwd_dir.createDirPath(io, abs_dir) catch |e| switch (e) {
        error.NotDir => return renderNotDir(streams, abs_dir),
        else => return renderStorage(streams, abs_dir, reasonOf(e)),
    };

    // 4. Open a handle to the target dir; all subsequent file ops go through it
    //    so `.zit`/`.zit-checkout` land in the resolved directory.
    var target = cwd_dir.openDir(io, abs_dir, .{}) catch |e| switch (e) {
        error.NotDir => return renderNotDir(streams, abs_dir),
        else => return renderStorage(streams, abs_dir, reasonOf(e)),
    };
    defer target.close(io);

    // 5. Create `.zit` exclusively — this defines the "already exists" error
    //    out of existence (no separate stat probe, no TOCTOU). Detection is
    //    precisely the presence of `.zit`; an orphan `.zit-checkout` is
    //    irrelevant (B-init-7).
    var file = target.createFile(io, repo_filename, .{ .read = true, .exclusive = true }) catch |e| switch (e) {
        error.PathAlreadyExists => return renderAlreadyExists(streams, abs_zit),
        error.IsDir, error.NotDir => return renderNotDir(streams, abs_zit),
        else => return renderStorage(streams, abs_dir, reasonOf(e)),
    };

    // 6. Default hash policy (B-init-3): a fresh repo with no SHA-named
    //    artifacts is SHA3-256 (`.sha3` = 2). Threaded opaquely into the header.
    const hash_kind: u8 = @intFromEnum(zit.artifact.defaultPolicy(false, false));

    // 7. Log lifecycle (B-init-2): `open` on the empty file writes the 64-byte
    //    header (zero frames); `commit` fsyncs it (durability before success).
    //    On any failure, close and roll back `.zit` (B-init-9).
    var fs = storage.FileStorage.init(io, file, 0);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), hash_kind) catch |e| {
        file.close(io);
        target.deleteFile(io, repo_filename) catch {};
        return renderStorage(streams, abs_dir, reasonOf(e));
    };
    // §9.1 — give the repository a stable, unique project code (sync §9.1:
    // `projectcode = artifact-hash`). Derived deterministically from the
    // repo's absolute path — reproducible, distinct per repository, and with
    // no ambient RNG (the determinism seam). Persisted as repo config so
    // `serve` emits it in the clone reply's `push` card and a clone adopts it.
    const project_code = zit.sync.deriveProjectCode(&.{abs_zit});
    log.putConfig(.{
        .hash_policy = hash_kind,
        .default_branch = "trunk",
        .project_id = "",
        .project_code = &project_code,
    }) catch |e| {
        log.deinit(gpa);
        file.close(io);
        target.deleteFile(io, repo_filename) catch {};
        return renderStorage(streams, abs_dir, reasonOf(e));
    };
    log.commit() catch |e| {
        log.deinit(gpa);
        file.close(io);
        target.deleteFile(io, repo_filename) catch {};
        return renderStorage(streams, abs_dir, reasonOf(e));
    };
    log.deinit(gpa);
    file.close(io);

    // 8. Checkout record (B-init-2/4): trunk unborn (`version == ""`).
    //    `checkout.write` is itself atomic, so a partial record is impossible;
    //    on failure roll back `.zit` (B-init-9).
    checkout.write(io, target, .{ .version = "", .branch = "trunk", .merge_parent = "", .special_op = "", .manifest_flags = "" }) catch |e| {
        target.deleteFile(io, repo_filename) catch {};
        return renderStorage(streams, abs_dir, reasonOf(e));
    };

    // 9. Success feedback (B-init-2/6/12): a single plain-ASCII line whose
    //    trailing whitespace-delimited token is the absolute `.zit` path;
    //    `-q`/`--quiet` writes nothing.
    if (!parsed.quiet) {
        streams.out.print("Initialized empty zit repository in {s}\n", .{abs_zit}) catch {};
    }
    return .ok;
}

/// The one wording for "0.1.0 does not version symlinks", shared by explicit
/// `add`'s refusal and recursive `add`'s skip notice so the two can never drift
/// apart — the drift between the recursive and direct paths IS blocker B3
/// (docs/plans/CLI-VERB-BREAKDOWN.md §B3). A fifo/socket keeps the older,
/// separate "not a regular file" wording: those are not the same refusal and
/// must not read as one.
pub const symlink_unversioned = "symlink (not versioned in 0.1.0)";

/// The repository file's fixed name (logstore §E: a copied `.zit` is a
/// complete repository).
pub const repo_filename = zit.repo_filename;

// --- educating diagnostics (all to err, all exit 1) -----------------------

fn renderAlreadyExists(s: cli.Streams, abs_zit: []const u8) cli.Exit {
    s.err.print("zit: a zit repository already exists at {s}\n", .{abs_zit}) catch {};
    return .failure;
}

fn renderNotDir(s: cli.Streams, path: []const u8) cli.Exit {
    s.err.print("zit: cannot initialize: {s} is not a directory\n", .{path}) catch {};
    return .failure;
}

pub fn renderStorage(s: cli.Streams, abs_dir: []const u8, reason: []const u8) cli.Exit {
    s.err.print("zit: cannot initialize repository at {s}: {s}\n", .{ abs_dir, reason }) catch {};
    return .failure;
}

/// Maps a raw error to a short, honest, human phrase for the B-init-9 line.
/// Pure rendering, not logic — the switch is over the union of every error
/// the init path can surface (filesystem, `LogStore`, `checkout`).
pub fn reasonOf(err: anyerror) []const u8 {
    return switch (err) {
        error.OutOfMemory => "out of memory",
        error.AccessDenied, error.PermissionDenied => "permission denied",
        error.ReadOnlyFileSystem => "read-only file system",
        error.NoSpaceLeft, error.DiskQuota => "no space left on device",
        error.FileNotFound => "no such file or directory",
        error.Corrupt => "repository is corrupt",
        // `error.Storage` (LogStore/checkout device failure) and every other
        // device/OS error collapse to one honest phrase.
        else => "input/output error",
    };
}

// --- help / usage text ----------------------------------------------------

/// Renders a checkout-state read failure for any verb; the verb prefixes the
/// message so one mapper serves both the read-only working-tree verbs and commit.
pub fn checkoutFail(s: cli.Streams, verb: []const u8, err: checkout.CheckoutError) cli.Exit {
    switch (err) {
        error.Corrupt => s.err.print(
            "zit {s}: cannot read checkout state: .zit-checkout is corrupt\n",
            .{verb},
        ) catch {},
        error.Storage => s.err.print(
            "zit {s}: cannot read checkout state: input/output error\n",
            .{verb},
        ) catch {},
    }
    return .failure;
}

/// Renders a managed-set read failure for any verb; the verb prefixes the
/// message so one mapper serves both the read-only working-tree verbs and commit.
pub fn managedFail(s: cli.Streams, verb: []const u8, err: managed.ManagedError) cli.Exit {
    switch (err) {
        error.Corrupt => s.err.print(
            "zit {s}: cannot read tracked files: .zit-managed is corrupt\n",
            .{verb},
        ) catch {},
        error.Storage => s.err.print(
            "zit {s}: cannot read tracked files: input/output error\n",
            .{verb},
        ) catch {},
        error.TooLong => s.err.print(
            "zit {s}: cannot read tracked files: a tracked path is too long\n",
            .{verb},
        ) catch {},
        error.TooMany => s.err.print("zit {s}: cannot read tracked files: too many tracked files\n", .{verb}) catch {},
        error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
    }
    return .failure;
}

pub fn stateOom(s: cli.Streams, verb: []const u8) cli.Exit {
    s.err.print("zit {s}: out of memory\n", .{verb}) catch {};
    return .failure;
}

// ==========================================================================
// `zit diff` — read-only metadata comparison of managed paths against the
// checkout's fully resolved F-set. It buffers every record before writing so
// an I/O/corruption/OOM failure never leaves a partial report on stdout.
// ==========================================================================

/// Upper bound on one managed working-tree file read by `commit` or `diff`.
/// The boundary is inclusive, so a file exactly this size is valid; larger
/// files are refused before allocation.
pub const max_tracked_file_bytes: usize = 1 << 30;

pub fn trackedFileSizeAllowed(size: u64) bool {
    return size <= @as(u64, max_tracked_file_bytes);
}

pub fn executable(permissions: File.Permissions) bool {
    if (comptime File.Permissions.has_executable_bit) {
        return permissions.toMode() & 0o111 != 0;
    }
    return false;
}

/// The diagnostic every working-tree verb (add/rm/status) prints when discovery
/// finds no repository. Shared so all three fail identically (B-add-8 / B-rm-8 /
/// B-status-9 "identical shape") — a single, byte-identical line, exactly as each
/// contract quotes it.
pub const not_a_repo_msg =
    "zit: not a zit repository (no .zit found in this directory or any parent)\n";

// ==========================================================================
// `zit log CHECKIN` — one explicit check-in and its reachable parent graph.
// ==========================================================================

/// One honest phrase for a repository the read-only family cannot open or stat.
pub fn repoReadFail(s: cli.Streams, verb: []const u8) cli.Exit {
    s.err.print("zit {s}: cannot read repository: input/output error\n", .{verb}) catch {};
    return .failure;
}

/// Maps a `Repository.open` failure to the verb's diagnostic + exit 1. Closed
/// over `Repository.OpenError` so the CLI switch stays exhaustive; general over
/// the verb name so every read-only verb shares one map. The `not-a-repo` and
/// corrupt/IO phrasings are byte-identical to the pre-facade hand-wired opens.
pub fn repoOpenFail(s: cli.Streams, verb: []const u8, err: Repository.OpenError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
        error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
        error.CannotRead => s.err.print("zit {s}: cannot read repository: input/output error\n", .{verb}) catch {},
        error.Corrupt => s.err.print("zit {s}: cannot read repository: repository is corrupt\n", .{verb}) catch {},
    }
    return .failure;
}

/// Discover the checkout root and open the repository through the `Repository`
/// facade for the read-only verb family (leaves, branch, tag, info). One place
/// owns the discover + open + per-verb diagnostics so every read-only verb reads
/// identical text. On `.ok`, `repo` is filled (caller `deinit`s it) and
/// `root_dir` is set (caller closes it AFTER `repo.deinit`); on any non-`.ok`
/// the diagnostic is already on stderr, `repo` is untouched, and any opened root
/// dir has been closed here.
pub fn openRepo(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    verb: []const u8,
    repo_override: ?[]const u8,
    bypass_cache: bool,
    fast_read: bool,
    repo: *Repository,
    root_dir: *std.Io.Dir,
) cli.Exit {
    // `resolveRoot` is the one place the `-R` route and the walk-up-from-cwd
    // route converge, so no verb below has to know which one it got.
    const root = (cli.resolveRoot(arena, io, repo_override) catch
        return stateOom(streams, verb)) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    // Hot verbs take the zero-parse image path (`.fast_read`); the cold verbs
    // that read adjacency or the full tag tables stay on the full derive.
    repo.open(gpa, io, root.dir, .{
        .bypass_cache = bypass_cache,
        .mode = if (fast_read) .fast_read else .full,
    }) catch |e| {
        var d = root.dir;
        d.close(io);
        return repoOpenFail(streams, verb, e);
    };
    root_dir.* = root.dir;
    return .ok;
}

/// Displayed prefix of the full artifact hash on a timeline line. Display only:
/// the total order keys on the FULL hash inside `checkinsByMtime`, so a display
/// collision never perturbs ordering.
pub const timeline_hash_display = 12;

/// The first line of a check-in comment (up to, excluding, the first LF), so a
/// multi-line comment never injects a newline into the one-line-per-check-in
/// listing (B-timeline-6). A comment with no LF is returned whole.
pub fn firstCommentLine(comment: []const u8) []const u8 {
    const nl = std.mem.indexOfScalar(u8, comment, '\n') orelse return comment;
    return comment[0..nl];
}

/// Renders the §6.3 branch listing to stdout, one line per entry in `entries`
/// order (name-ascending, as `branches` returns them). `current` is the branch
/// name of the checked-out check-in (§6.1/§6.4) or null; the matching entry —
/// at most one, since §6.3 grouping yields distinct names — gets a leading
/// "* ", every other a two-space indent. A representative-closed branch (§6.3)
/// appends "  (closed)". Pure; bounded by `entries.len`.
pub fn renderBranchList(
    out: *std.Io.Writer,
    entries: []const repostate.RepoState.BranchEntry,
    current: ?[]const u8,
) void {
    var marked: usize = 0;
    for (entries) |entry| {
        const is_current = current != null and std.mem.eql(u8, entry.name, current.?);
        if (is_current) marked += 1;
        std.debug.assert(marked <= 1); // distinct names ⇒ at most one mark
        out.writeAll(if (is_current) "* " else "  ") catch {};
        out.writeAll(entry.name) catch {};
        if (entry.closed) out.writeAll("  (closed)") catch {};
        out.writeAll("\n") catch {};
    }
    std.debug.assert(marked <= 1);
}

/// The reserved 'sym-' prefix (repo-state §2): a symbolic name is stored with
/// it and surfaced with it stripped.
pub const sym_prefix = "sym-";

/// The parent's symbolic tags a branch-root check-in must cancel (repo-state
/// §6.2). §6.2: "Branch creation MUST also cancel every pre-existing active
/// sym-* tag on the branch-root check-in ... because symbolic tags are
/// otherwise INHERITED from a check-in's parent." Inheritance is propagation,
/// so the cancel set is exactly the parent's PROPAGATING (`*`) syms: a singleton
/// (`+`) sym never propagates, so the child does not inherit it and cancelling
/// it would emit a spurious non-canonical `-sym-X` for a tag the child never
/// held. `zit tag add` mints exactly such a singleton sym (REGRESSION B6), so
/// this exclusion is reachable locally now, not only via a synced
/// `T +sym-X *`. The branch's own re-established sym (`want_sym`) is excluded,
/// since `composeCommitTags` re-adds it as a propagating tag. Pure; each
/// surfaced name is duped onto `arena` so it outlives the read view. `entries`
/// come from `RepoState.tagsOf`, which surfaces active rows only (no cancels).
fn selectInheritedSyms(
    arena: std.mem.Allocator,
    entries: []const repostate.RepoState.TagEntry,
    want_sym: []const u8,
) error{OutOfMemory}![]const []const u8 {
    std.debug.assert(std.mem.startsWith(u8, want_sym, sym_prefix));
    var syms: std.ArrayList([]const u8) = .empty;
    errdefer syms.deinit(arena);
    for (entries) |e| {
        std.debug.assert(e.tagtype != .cancel); // tagsOf surfaces active rows only
        if (e.tagtype != .propagate) continue; // §6.2: only inherited (propagating) syms
        if (!std.mem.startsWith(u8, e.name, sym_prefix)) continue;
        if (std.mem.eql(u8, e.name, want_sym)) continue; // re-established as a propagating tag
        try syms.append(arena, try arena.dupe(u8, e.name));
    }
    return syms.toOwnedSlice(arena);
}

test "commit repo-state §6.2: only inherited (propagating) parent syms are cancelled" {
    const gpa = std.testing.allocator;
    const TagEntry = repostate.RepoState.TagEntry;
    // A parent (as `tagsOf` surfaces it: active rows only) carrying every case:
    // an inherited propagating sym (MUST cancel), the branch's own propagating
    // sym (excluded — re-established), a SINGLETON sym (MUST NOT cancel; §6.2
    // cancels only inherited syms, and a `+` sym never propagates), and a
    // non-sym propagating tag (`branch`, not a symbolic name).
    const entries = [_]TagEntry{
        .{ .name = "sym-trunk", .tagtype = .propagate, .value = null },
        .{ .name = "sym-feature", .tagtype = .propagate, .value = null },
        .{ .name = "sym-adhoc", .tagtype = .singleton, .value = null },
        .{ .name = "branch", .tagtype = .propagate, .value = "trunk" },
    };
    const got = try selectInheritedSyms(gpa, &entries, "sym-feature");
    defer {
        for (got) |s| gpa.free(s);
        gpa.free(got);
    }
    // Exactly the inherited propagating sym, minus the re-established one: the
    // singleton `sym-adhoc` and the non-sym `branch` are both excluded.
    try std.testing.expectEqual(@as(usize, 1), got.len);
    try std.testing.expectEqualStrings("sym-trunk", got[0]);
}

/// Ascending raw-byte order over two artifact IDs, so the merge-parent lines
/// print in a deterministic order (IDs are unique per check-in).
pub fn lessByHash(_: void, a: []const u8, b: []const u8) bool {
    return std.mem.order(u8, a, b) == .lt;
}

/// `zit update CHECKIN` — parse one canonical artifact ID, discover the
/// worktree, open the repository read-only, and delegate the transaction to
/// the private update module.
fn runUpdate(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    const parsed = switch (cli.parseUpdateArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "update", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "update", .extra_argument, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(update_help) catch {};
        return .ok;
    }
    const requested = parsed.checkin orelse
        return cli.usageError(streams, "update", .no_checkin, "");
    // SF1 (BLOCKER-FIX-PLAN.md §3): `update` used to accept ONLY a canonical
    // 40/64-hex ID, so `zit update trunk` — the single most obvious thing to
    // type — failed as an "invalid check-in ID". Its argument is a check-in
    // name like every other verb's, so it goes through the same §8.3 procedure.
    const target_id = switch (updateResolveTarget(gpa, io, arena, requested, streams)) {
        .ok => |h| h,
        .fail => |exit| return exit,
    };

    const root = (cli.discoverRoot(arena, io) catch {
        streams.err.writeAll("zit update: out of memory\n") catch {};
        return .failure;
    }) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var file = root_dir.openFile(io, repo_filename, .{}) catch {
        streams.err.writeAll("zit update: cannot read repository: input/output error\n") catch {};
        return .failure;
    };
    defer file.close(io);
    const log_st = file.stat(io) catch {
        streams.err.writeAll("zit update: cannot read repository: input/output error\n") catch {};
        return .failure;
    };
    var fs = storage.FileStorage.init(io, file, log_st.size);
    var log = logstore.LogStore.openReadOnly(gpa, fs.storageFile()) catch |err|
        return updateLogFail(streams, err);
    defer log.deinit(gpa);

    update.applyCheckin(gpa, io, root_dir, &log, target_id, .inherit) catch |err|
        return updateApplyFail(streams, target_id, err);
    return .ok;
}

/// Resolve `update`'s check-in argument to a canonical artifact ID (SF1).
///
/// A canonical 40/64-hex ID short-circuits: it needs no repository state, so
/// update's cold path (open the log read-only, hand the ID to the update
/// engine) is byte-for-byte what it was. Anything else — `trunk`, `tip`, a hash
/// prefix, a date form — opens the repository read-only and runs the shared
/// §8.3 procedure, then hands back the arena-owned canonical ID. The
/// repository view is closed again before the update transaction opens the log,
/// so the two never hold it at once.
fn updateResolveTarget(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    requested: []const u8,
    streams: cli.Streams,
) union(enum) { ok: []const u8, fail: cli.Exit } {
    if (artifact.validateName(requested)) return .{ .ok = requested };

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    // `.full` derive, not `.fast_read`: plain-name resolution reads the tag
    // tables, which the read-image does not materialize.
    const rc = openRepo(gpa, io, arena, streams, "update", null, false, false, &repo, &root_dir);
    if (rc != .ok) return .{ .fail = rc };
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    const rid = repo.resolve(requested, .checkin) catch |e| switch (e) {
        error.NotFound => {
            streams.err.print("zit update: check-in '{s}' not found\n", .{requested}) catch {};
            return .{ .fail = .failure };
        },
        error.Ambiguous => {
            streams.err.print("zit update: name '{s}' is ambiguous\n", .{requested}) catch {};
            return .{ .fail = .failure };
        },
        error.OutOfMemory => return .{ .fail = stateOom(streams, "update") },
    };
    // The hash borrows `repo`'s view, which dies with the `defer` above.
    const owned = arena.dupe(u8, repo.hashOf(rid)) catch
        return .{ .fail = stateOom(streams, "update") };
    std.debug.assert(artifact.validateName(owned));
    return .{ .ok = owned };
}

fn updateLogFail(s: cli.Streams, err: logstore.OpenError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit update: out of memory\n") catch {},
        else => s.err.print("zit update: cannot read repository: {s}\n", .{reasonOf(err)}) catch {},
    }
    return .failure;
}

pub fn updateApplyFail(s: cli.Streams, target_id: []const u8, err: update.ApplyError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit update: out of memory\n") catch {},
        error.InvalidCheckinId => s.err.print(
            "zit update: invalid check-in ID '{s}' (expected 40 or 64 lowercase hexadecimal digits)\n",
            .{target_id},
        ) catch {},
        error.CheckinNotFound => s.err.print("zit update: check-in '{s}' not found\n", .{target_id}) catch {},
        error.CheckinContentMissing => s.err.print(
            "zit update: cannot read repository: check-in '{s}' content is missing\n",
            .{target_id},
        ) catch {},
        error.CheckinNameMismatch => s.err.print(
            "zit update: cannot read repository: check-in '{s}' content does not match its name\n",
            .{target_id},
        ) catch {},
        error.TargetNotManifest => s.err.print("zit update: check-in '{s}' is not a valid manifest\n", .{target_id}) catch {},
        error.BaselineNotFound => s.err.print(
            "zit update: cannot read repository: check-in '{s}' baseline is not found\n",
            .{target_id},
        ) catch {},
        error.BaselineContentMissing => s.err.print(
            "zit update: cannot read repository: check-in '{s}' baseline content is missing\n",
            .{target_id},
        ) catch {},
        error.BaselineNameMismatch => s.err.print(
            "zit update: cannot read repository: check-in '{s}' baseline content does not match its name\n",
            .{target_id},
        ) catch {},
        error.BaselineNotManifest => s.err.print(
            "zit update: check-in '{s}' baseline is not a valid manifest\n",
            .{target_id},
        ) catch {},
        error.BaselineIsDelta => s.err.print(
            "zit update: check-in '{s}' baseline is not fully resolvable\n",
            .{target_id},
        ) catch {},
        error.StateRecordInvalid, error.Corrupt => s.err.writeAll("zit update: cannot read repository: repository is corrupt\n") catch {},
        error.InvalidPath => s.err.print("zit update: check-in '{s}' names an invalid file path\n", .{target_id}) catch {},
        error.ReservedPath => s.err.print("zit update: check-in '{s}' names a reserved file path\n", .{target_id}) catch {},
        error.SymlinkUnsupported => s.err.print(
            "zit update: check-in '{s}' contains an unsupported symlink entry\n",
            .{target_id},
        ) catch {},
        error.CurrentStateInvalid => s.err.writeAll("zit update: current working-tree state is invalid\n") catch {},
        error.WorktreeNotClean => s.err.writeAll("zit update: working tree is not clean\n") catch {},
        error.UnmanagedCollision => s.err.writeAll("zit update: an untracked file or directory is in the way\n") catch {},
        error.Storage => s.err.writeAll("zit update: cannot update working tree: input/output error\n") catch {},
        error.TransactionUnavailable => s.err.writeAll("zit update: cannot create a transaction directory\n") catch {},
        error.RollbackFailed => s.err.writeAll(
            "zit update: update failed and could not be rolled back; the previous working-tree state is retained for recovery\n",
        ) catch {},
        error.CleanupFailed => s.err.writeAll(
            "zit update: update committed, but the transaction directory could not be removed\n",
        ) catch {},
    }
    return .failure;
}

// ==========================================================================
// `zit bisect SUBCOMMAND [NAME]` — binary-search the check-in DAG for the
// defect-introducing check-in (contracts/bisect.md B-bisect-1..20). The span
// math is ONE general-purpose repostate query (`Repository.bisectSpan`,
// ambiguities.md bisect-midpoint); moves ride the shipped update engine
// (`update.applyCheckin`, journal-armed); the session lives in `.zit-bisect`
// (the `undo.zig` state-file tier). This layer only orchestrates: parse, resolve,
// refuse, persist-then-move, announce.
// ==========================================================================

/// The 12-character display prefix of an artifact hash (timeline parity).
fn bisectShort(hash: []const u8) []const u8 {
    return hash[0..@min(hash.len, timeline_hash_display)];
}

fn bisectDiag(s: cli.Streams, msg: []const u8) cli.Exit {
    s.err.print("zit bisect: {s}\n", .{msg}) catch {};
    return .failure;
}

fn bisectOom(s: cli.Streams) cli.Exit {
    return bisectDiag(s, "out of memory");
}

fn bisectNoSession(s: cli.Streams) cli.Exit {
    return bisectDiag(s, "no bisect in progress");
}

fn bisectInconsistent(s: cli.Streams) cli.Exit {
    return bisectDiag(s, "bisect state names a check-in not in this repository; run 'zit bisect reset'");
}

/// Map a `.zit-bisect` read/write fault to its diagnostic. A corrupt file names
/// `reset` as the recovery (B-bisect-6), matching the `.zit-managed` parity.
fn bisectStateFail(s: cli.Streams, err: bisect.StateError) cli.Exit {
    switch (err) {
        error.OutOfMemory => return bisectOom(s),
        error.Storage => return bisectDiag(s, "cannot read bisect state: input/output error"),
        error.Corrupt => return bisectDiag(s, "cannot read bisect state: .zit-bisect is corrupt; run 'zit bisect reset' to recover"),
    }
}

/// Map an update-engine move fault to its diagnostic. The path/baseline arms are
/// unreachable for a check-in this view already resolved, so they fold into the
/// generic corrupt-repository message.
fn bisectMoveFail(s: cli.Streams, err: update.ApplyError) cli.Exit {
    switch (err) {
        error.OutOfMemory => return bisectOom(s),
        error.WorktreeNotClean => return bisectDiag(s, "working tree is not clean"),
        error.UnmanagedCollision => return bisectDiag(s, "an untracked file or directory is in the way"),
        error.Storage => return bisectDiag(s, "cannot update working tree: input/output error"),
        error.TransactionUnavailable => return bisectDiag(s, "cannot create a transaction directory"),
        error.RollbackFailed => return bisectDiag(s, "move failed and could not be rolled back; the previous working-tree state is retained for recovery"),
        error.CleanupFailed => return bisectDiag(s, "move committed, but the transaction directory could not be removed"),
        else => return bisectDiag(s, "cannot read repository: repository is corrupt"),
    }
}

/// Resolve every stored mark hash to its rid. `Missing` == the session names a
/// hash this view never interned (an inconsistent state).
fn bisectRids(gpa: std.mem.Allocator, repo: *Repository, hashes: []const []const u8) error{ OutOfMemory, Missing }![]Repository.Rid {
    const out = gpa.alloc(Repository.Rid, hashes.len) catch return error.OutOfMemory;
    errdefer gpa.free(out);
    for (hashes, out) |h, *r| r.* = repo.lookup(h) orelse return error.Missing;
    return out;
}

/// Drop every occurrence of `hash` from `list` (content compare), so re-marking a
/// check-in moves it between the good/bad/skip sets rather than duplicating it.
fn bisectRemove(list: *std.ArrayList([]const u8), hash: []const u8) void {
    var i: usize = 0;
    while (i < list.items.len) {
        if (std.mem.eql(u8, list.items[i], hash)) {
            _ = list.orderedRemove(i);
        } else i += 1;
    }
}

// ===========================================================================
// `zit annotate PATH` (contracts/annotate.md B-annotate-1..16). Per-line
// provenance of one tracked file at the current check-out: which check-in
// introduced each line, and when. The version chain is the file's FULL ancestry
// materialized through `Repository.fileAt` (the §8 effective set) + `blob`, with
// adjacency from the repostate §3.3 parent query; adjacent versions are diffed
// by the ONE house line-diff core (`merge3.matchLines`); the pure `annotate`
// engine pushes origins backward per ambiguities.md `annotate-attribution`. This
// layer is only I/O + rendering — no second history walker, resolver, or diff.
// ===========================================================================

fn runBisect(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    const parsed = switch (cli.parseBisectArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "bisect", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "bisect", .extra_argument, tok),
        .bad_subcommand => |tok| return cli.usageError(streams, "bisect", .bad_subcommand, tok),
        .missing_name => return cli.usageError(streams, "bisect", .no_name, ""),
    };
    if (parsed.help) {
        streams.out.writeAll(bisect_help) catch {};
        return .ok;
    }

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "bisect", null, false, false, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    return switch (parsed.sub) {
        .bad => bisectMark(gpa, io, &repo, root_dir, streams, parsed.name.?, .bad),
        .good => bisectMark(gpa, io, &repo, root_dir, streams, parsed.name.?, .good),
        .next => bisectNext(gpa, io, &repo, root_dir, streams),
        .status => bisectStatus(gpa, io, &repo, root_dir, streams),
        .reset => bisectReset(gpa, io, &repo, root_dir, streams),
    };
}

/// `zit bisect bad|good NAME`: record the mark, then — once both a bad and a good
/// endpoint exist — narrow the span and move the checkout to the next probe
/// (B-bisect-1/3). A lone endpoint is recorded and confirmed without moving.
fn bisectMark(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    name: []const u8,
    kind: cli.BisectSub,
) cli.Exit {
    const rid = repo.resolve(name, .checkin) catch |e| switch (e) {
        error.NotFound => {
            streams.err.print("zit bisect: check-in '{s}' not found\n", .{name}) catch {};
            return .failure;
        },
        error.Ambiguous => {
            streams.err.print("zit bisect: name '{s}' is ambiguous\n", .{name}) catch {};
            return .failure;
        },
        error.OutOfMemory => return stateOom(streams, "bisect"),
    };
    const hash = repo.hashOf(rid);

    var sess_opt = bisect.read(gpa, io, root_dir) catch |e| return bisectStateFail(streams, e);
    defer if (sess_opt) |*s| s.deinit();

    var work = std.heap.ArenaAllocator.init(gpa);
    defer work.deinit();
    const a = work.allocator();

    var bad_list: std.ArrayList([]const u8) = .empty;
    var good_list: std.ArrayList([]const u8) = .empty;
    var skip_list: std.ArrayList([]const u8) = .empty;
    var start: []const u8 = "";
    if (sess_opt) |s| {
        start = s.start;
        for (s.bad) |x| bad_list.append(a, x) catch return bisectOom(streams);
        for (s.good) |x| good_list.append(a, x) catch return bisectOom(streams);
        for (s.skipped) |x| skip_list.append(a, x) catch return bisectOom(streams);
    } else {
        // Fresh session: the current checkout is the restore point for `reset`.
        var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
        if (checkout.read(io, root_dir, &ck_buf) catch null) |ck| {
            start = a.dupe(u8, ck.version) catch return bisectOom(streams);
        }
    }

    const dh = a.dupe(u8, hash) catch return bisectOom(streams);
    bisectRemove(&bad_list, dh);
    bisectRemove(&good_list, dh);
    bisectRemove(&skip_list, dh);
    switch (kind) {
        .bad => bad_list.append(a, dh) catch return bisectOom(streams),
        .good => good_list.append(a, dh) catch return bisectOom(streams),
        else => unreachable,
    }

    const has_both = bad_list.items.len != 0 and good_list.items.len != 0;
    if (!has_both) {
        // Record the lone endpoint; no move (B-bisect-1 first half).
        bisect.write(gpa, io, root_dir, start, bad_list.items, good_list.items, skip_list.items) catch |e|
            return bisectStateFail(streams, e);
        streams.out.print("bisect: marked {s} {s}\n", .{ bisectShort(hash), @tagName(kind) }) catch {};
        const other = if (kind == .bad) "good" else "bad";
        streams.out.print("bisect: mark a {s} check-in to begin bisecting\n", .{other}) catch {};
        return .ok;
    }
    return bisectAdvance(gpa, io, repo, root_dir, streams, start, bad_list.items, good_list.items, skip_list.items, true);
}

/// Derive the span, refuse over a dirty tree / inverted / unrelated marks
/// (mutating nothing), then — only on success — persist the state and move the
/// checkout to the probe (or the culprit when the span is exhausted). Shared by
/// marking (persist == true) and `next` (persist == true, idempotent rewrite).
fn bisectAdvance(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    start: []const u8,
    bad_hashes: []const []const u8,
    good_hashes: []const []const u8,
    skip_hashes: []const []const u8,
    persist: bool,
) cli.Exit {
    // Dirty-tree refusal first — the shipped update discipline (B-bisect-9),
    // mutating nothing.
    const log = repo.logStore(gpa) catch |e| return repoOpenFail(streams, "bisect", e);
    update.requireCleanTree(gpa, io, root_dir, log) catch |e| switch (e) {
        error.WorktreeNotClean => return bisectDiag(streams, "working tree is not clean"),
        else => return bisectMoveFail(streams, e),
    };

    const bad_rids = bisectRids(gpa, repo, bad_hashes) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(bad_rids);
    const good_rids = bisectRids(gpa, repo, good_hashes) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(good_rids);
    const skip_rids = bisectRids(gpa, repo, skip_hashes) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(skip_rids);

    const out = repo.bisectSpan(gpa, bad_rids, good_rids, skip_rids) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.InvertedMarks => return bisectDiag(streams, "the bad check-in is an ancestor of a good check-in; the marks are inverted"),
        error.UnrelatedHistories => return bisectDiag(streams, "the good and bad marks share no common history"),
    };

    // Persist the validated state durably BEFORE the move (B-bisect-6): a crash
    // leaves the marks recorded and the probe re-derivable.
    if (persist) {
        bisect.write(gpa, io, root_dir, start, bad_hashes, good_hashes, skip_hashes) catch |e|
            return bisectStateFail(streams, e);
    }

    if (out.probe) |probe| {
        const target = repo.hashOf(probe);
        update.applyCheckin(gpa, io, root_dir, log, target, .inherit) catch |e| return bisectMoveFail(streams, e);
        streams.out.print(
            "bisect: {d} untested candidate(s) remain; testing {s}\n",
            .{ out.untested, bisectShort(target) },
        ) catch {};
        return .ok;
    }
    return bisectAnnounceCulprit(gpa, io, repo, root_dir, log, streams, out.culprit);
}

/// Termination (B-bisect-4): move the checkout to the culprit and announce it
/// with its comment line. The session stays recorded until `reset`.
fn bisectAnnounceCulprit(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    log: *logstore.LogStore,
    streams: cli.Streams,
    culprit: Repository.Rid,
) cli.Exit {
    const target = repo.hashOf(culprit);
    update.applyCheckin(gpa, io, root_dir, log, target, .inherit) catch |e| return bisectMoveFail(streams, e);

    // The comment borrows the manifest bytes, so print before it is freed; the
    // override value borrows tagxref bytes valid for the repo's lifetime.
    var maybe = repo.manifest(gpa, culprit) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        else => return bisectDiag(streams, "cannot read repository: repository is corrupt"),
    };
    defer if (maybe) |*m| m.deinit(gpa);
    const manifest_comment: []const u8 = if (maybe) |m|
        (if (m.manifest.c) |c| firstCommentLine(c.comment) else "")
    else
        "";
    const comment = repo.override(culprit, "comment", manifest_comment);
    streams.out.print("bisect: {s} is the first bad check-in\n", .{bisectShort(target)}) catch {};
    streams.out.print("    {s}\n", .{comment}) catch {};
    return .ok;
}

/// `zit bisect next`: re-derive and re-announce the current probe, moving the
/// checkout to it. Refuses with no session or with only one endpoint (B-bisect-13).
fn bisectNext(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
) cli.Exit {
    var sess_opt = bisect.read(gpa, io, root_dir) catch |e| return bisectStateFail(streams, e);
    defer if (sess_opt) |*s| s.deinit();
    const s = sess_opt orelse return bisectNoSession(streams);
    if (s.bad.len == 0 or s.good.len == 0) {
        const missing = if (s.bad.len == 0) "bad" else "good";
        streams.err.print("zit bisect: mark a {s} check-in before running 'zit bisect next'\n", .{missing}) catch {};
        return .failure;
    }
    return bisectAdvance(gpa, io, repo, root_dir, streams, s.start, s.bad, s.good, s.skipped, false);
}

/// `zit bisect status`: report the marks, the current probe, and the remaining
/// count without moving (B-bisect-7). Never refuses on a dirty tree; with no
/// session it is exit 1, nothing mutated.
fn bisectStatus(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
) cli.Exit {
    var sess_opt = bisect.read(gpa, io, root_dir) catch |e| return bisectStateFail(streams, e);
    defer if (sess_opt) |*s| s.deinit();
    const s = sess_opt orelse return bisectNoSession(streams);

    for (s.bad) |h| streams.out.print("bisect: bad  {s}\n", .{bisectShort(h)}) catch {};
    for (s.good) |h| streams.out.print("bisect: good {s}\n", .{bisectShort(h)}) catch {};
    for (s.skipped) |h| streams.out.print("bisect: skip {s}\n", .{bisectShort(h)}) catch {};

    if (s.bad.len == 0 or s.good.len == 0) {
        const other = if (s.bad.len == 0) "bad" else "good";
        streams.out.print("bisect: mark a {s} check-in to begin bisecting\n", .{other}) catch {};
        return .ok;
    }

    const bad_rids = bisectRids(gpa, repo, s.bad) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(bad_rids);
    const good_rids = bisectRids(gpa, repo, s.good) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(good_rids);
    const skip_rids = bisectRids(gpa, repo, s.skipped) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.Missing => return bisectInconsistent(streams),
    };
    defer gpa.free(skip_rids);

    const out = repo.bisectSpan(gpa, bad_rids, good_rids, skip_rids) catch |e| switch (e) {
        error.OutOfMemory => return bisectOom(streams),
        error.InvertedMarks => return bisectDiag(streams, "the bad check-in is an ancestor of a good check-in; the marks are inverted"),
        error.UnrelatedHistories => return bisectDiag(streams, "the good and bad marks share no common history"),
    };
    if (out.probe) |probe| {
        streams.out.print(
            "bisect: testing {s} ({d} untested candidate(s) remain)\n",
            .{ bisectShort(repo.hashOf(probe)), out.untested },
        ) catch {};
    } else {
        streams.out.print("bisect: {s} is the first bad check-in\n", .{bisectShort(repo.hashOf(out.culprit))}) catch {};
    }
    return .ok;
}

/// `zit bisect reset`: restore the starting check-in, remove `.zit-bisect`, exit 0
/// (B-bisect-8). No session is exit 1; a corrupt file is cleared (reset is the
/// advertised recovery, B-bisect-6). The restore move rides the update engine and
/// is refused over a dirty tree (B-bisect-9).
fn bisectReset(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
) cli.Exit {
    var sess_opt = bisect.read(gpa, io, root_dir) catch |e| switch (e) {
        error.Corrupt => {
            // reset IS the recovery: clear the damaged file rather than deadlock.
            bisect.clear(io, root_dir);
            streams.out.writeAll("bisect: cleared corrupt bisect state (working tree not restored)\n") catch {};
            return .ok;
        },
        else => return bisectStateFail(streams, e),
    };
    defer if (sess_opt) |*s| s.deinit();
    const s = sess_opt orelse return bisectNoSession(streams);

    const log = repo.logStore(gpa) catch |e| return repoOpenFail(streams, "bisect", e);
    update.requireCleanTree(gpa, io, root_dir, log) catch |e| switch (e) {
        error.WorktreeNotClean => return bisectDiag(streams, "working tree is not clean"),
        else => return bisectMoveFail(streams, e),
    };
    if (s.start.len != 0) {
        update.applyCheckin(gpa, io, root_dir, log, s.start, .inherit) catch |e| return bisectMoveFail(streams, e);
        bisect.clear(io, root_dir);
        streams.out.print("bisect: reset; working tree restored to {s}\n", .{bisectShort(s.start)}) catch {};
    } else {
        bisect.clear(io, root_dir);
        streams.out.writeAll("bisect: reset\n") catch {};
    }
    return .ok;
}

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

fn runMerge(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    // 1. Parse the one-positional NAME plus `-h`/`--help` and the two mutually-
    //    exclusive baseline flags `--cherrypick`/`--backout` (B-merge-25/26/40).
    //    Help wins; an unknown option, a second positional, or both flags is a
    //    usage error (exit 2). A missing NAME is a usage error — NAME is
    //    mandatory (unlike `update`, which defaults to tip). The flagless grammar
    //    stays byte-identical to the shipped surface (B-merge-31).
    const parsed = switch (cli.parseMergeArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "merge", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "merge", .extra_argument, tok),
        .conflicting_flags => {
            streams.err.writeAll(
                "zit merge: --cherrypick and --backout cannot be combined\n",
            ) catch {};
            streams.err.writeAll("try 'zit merge --help'\n") catch {};
            return .usage;
        },
    };
    if (parsed.help) {
        streams.out.writeAll(merge_help) catch {};
        return .ok;
    }
    const name = parsed.checkin orelse return cli.usageError(streams, "merge", .no_name, "");

    // 2. Open the repository through the read-only facade (B-merge-27): a missing
    //    repo / read fault is exit 1, distinct from the exit-2 usage class, and
    //    the repository check precedes any resolution or working-tree read.
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "merge", null, false, false, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

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

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

    // 5. Refusal gate — nothing mutated on any refusal (all checked BEFORE
    //    `applyMerge`). Read the checkout for a pending-merge marker FIRST: an
    //    unresolved prior merge leaves conflict markers in the tree, so a bare
    //    dirty-tree check would misreport it — the pending check must precede it
    //    (B-merge-15).
    var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
    const ck = (checkout.read(io, root_dir, &ck_buf) catch |e|
        return checkoutFail(streams, "merge", e)) orelse {
        streams.err.writeAll("zit merge: no current check-in to merge into\n") catch {};
        return .failure;
    };
    if (ck.merge_parent.len != 0 or ck.special_op.len != 0) {
        streams.err.writeAll(
            "zit merge: a merge is already pending; resolve and commit it, or run 'zit undo'\n",
        ) catch {};
        return .failure;
    }

    // 6. Dirty-tree refusal (B-merge-14): the merge computes over the checkout's
    //    effective content (never a disk re-read), so a divergent working tree is
    //    rejected up front — the same `requireClean` gate `update` runs. Checked
    //    before the ancestry gates so a dirty tree reads as "not clean" rather
    //    than being masked by an up-to-date/unrelated verdict (plan §3 order).
    const log = repo.logStore(gpa) catch |e| return repoOpenFail(streams, "merge", e);
    update.requireCleanTree(gpa, io, root_dir, log) catch |e| switch (e) {
        error.WorktreeNotClean => {
            streams.err.writeAll("zit merge: working tree is not clean\n") catch {};
            return .failure;
        },
        else => return mergeApplyFail(streams, e),
    };

    // 6b. Special merges (merge-flags.md) choose an ALTERNATE baseline inside
    //     this same machinery — cherrypick applies REV's own change, backout
    //     reverses it — so they skip the plain-merge ancestry gates (up-to-date /
    //     unrelated-histories / merge-base) entirely and route straight through
    //     `classifyFile`/`applyMerge` with base/other picked per the flag. A root
    //     REV (no primary parent) uses the EMPTY file set for its parent side, so
    //     no refusal is needed (error defined out of existence).
    if (parsed.special) |sp| {
        const rev = other;
        const pp = repo.state().primaryParentOf(rev);
        const sel = specialBaseline(sp, rev, pp);
        const rev_hash = repo.hashOf(rev);
        const sign: u8 = if (sp == .cherrypick) '+' else '-';
        // The pending op recorded in checkout state: the q-sign byte glued onto
        // REV's hash (checkout §E `special_op`). Arena-owned; outlives applyMerge.
        const special_op = std.fmt.allocPrint(arena, "{c}{s}", .{ sign, rev_hash }) catch
            return mergeOom(streams);
        return computeAndApplyMerge(gpa, io, arena, &repo, root_dir, sel.base, current, sel.other, ck, .{
            .merge_parent = "",
            .special_op = special_op,
            .report_verb = if (sp == .cherrypick) "cherry-picked" else "backed out",
            .report_hash = rev_hash,
            .refuse_empty = true,
        }, streams);
    }

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

    // 8. Merge base over FULL ancestry (repo-state `mergeBaseOf`; ambiguities.md
    //    merge-base). No common ancestor → unrelated histories, refuse
    //    (B-merge-17). The up-to-date case (NAME an ancestor of the checkout) was
    //    already refused in step 7 by the mtime-independent ancestry test, so
    //    `base` here is strictly the three-way merge base.
    const base = (repo.mergeBaseOf(gpa, current, other) catch return mergeOom(streams)) orelse {
        streams.err.print(
            "zit merge: '{s}' shares no history with the current check-in\n",
            .{name},
        ) catch {};
        return .failure;
    };

    // 9. Compute the outcome set purely and materialize it, recording other's
    //    hash as the pending merge parent. Reports last.
    return computeAndApplyMerge(gpa, io, arena, &repo, root_dir, base, current, other, ck, .{
        .merge_parent = repo.hashOf(other),
        .special_op = "",
        .report_verb = "merged",
        .report_hash = repo.hashOf(other),
        .refuse_empty = false,
    }, streams);
}

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

/// What `computeAndApplyMerge` records and reports: the pending checkout fields
/// (exactly one of `merge_parent`/`special_op` is non-empty), the success-line
/// verb/hash, and whether a no-op application refuses (special merges) versus
/// falls through as a zero-change merge (plain merges, unchanged behavior).
const MergeApply = struct {
    merge_parent: []const u8,
    special_op: []const u8,
    report_verb: []const u8,
    report_hash: []const u8,
    refuse_empty: bool,
};

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

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

/// The current-side attribute wins (B-merge-23); when the path is added only on
/// the other side, its attribute is the only one there.
fn mergeSlotPerm(slot: MergeSlot) ?[]const u8 {
    if (slot.current) |f| return f.perm;
    if (slot.other) |f| return f.perm;
    return null;
}

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

    // The union of paths across the three sides; each slot names the side's card.
    // Iteration order is unspecified — the conflict list is sorted before it is
    // reported and `applyMerge` is order-independent, so nothing depends on it.
    var slots = std.StringHashMap(MergeSlot).init(arena);
    if (base_list) |*bl| {
        var bit = bl.iterator();
        while (bit.next()) |f| {
            const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
            if (!gop.found_existing) gop.value_ptr.* = .{};
            gop.value_ptr.base = f;
        }
    }
    var cit = cur_list.iterator();
    while (cit.next()) |f| {
        const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
        if (!gop.found_existing) gop.value_ptr.* = .{};
        gop.value_ptr.current = f;
    }
    if (oth_list) |*ol| {
        var oit = ol.iterator();
        while (oit.next()) |f| {
            const gop = slots.getOrPut(f.filename) catch return mergeOom(streams);
            if (!gop.found_existing) gop.value_ptr.* = .{};
            gop.value_ptr.other = f;
        }
    }

    // Classify every path (pure), building the outcome entries and the conflict
    // list. Bytes/results are arena-owned and outlive `applyMerge`.
    var entries: std.ArrayList(update.MergeEntry) = .empty;
    var conflicts: std.ArrayList([]const u8) = .empty;
    var it = slots.iterator();
    while (it.next()) |kv| {
        const path = kv.key_ptr.*;
        const slot = kv.value_ptr.*;
        // The bytes of each side (null = path absent there). The §8.2 walk
        // suppresses hash-less delete markers, so a present card always names a
        // stored blob; a missing blob is a corruption. A read fault returns an
        // already-rendered `cli.Exit` from this function verbatim.
        const base_side: merge3.Side = if (slot.base) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;
        const cur_side: merge3.Side = if (slot.current) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;
        const oth_side: merge3.Side = if (slot.other) |f|
            (repo.blob(arena, f.hash.?) catch |e| return repoOpenFail(streams, "merge", e)) orelse return mergeCorrupt(streams)
        else
            null;

        const outcome = merge3.classifyFile(arena, base_side, cur_side, oth_side) catch return mergeOom(streams);
        const perm = mergeSlotPerm(slot);
        switch (outcome) {
            .unchanged => {},
            .delete => entries.append(arena, .{ .path = path, .action = .delete }) catch return mergeOom(streams),
            .take_other => entries.append(arena, .{
                .path = path,
                .action = .{ .write = .{ .bytes = oth_side.?, .perm = perm } },
            }) catch return mergeOom(streams),
            .clean_merge => |r| entries.append(arena, .{
                .path = path,
                .action = .{ .write = .{ .bytes = r.bytes, .perm = perm } },
            }) catch return mergeOom(streams),
            .text_conflict => |r| {
                entries.append(arena, .{
                    .path = path,
                    .action = .{ .write = .{ .bytes = r.bytes, .perm = perm } },
                }) catch return mergeOom(streams);
                conflicts.append(arena, path) catch return mergeOom(streams);
            },
            .whole_file_conflict => {
                const bytes = merge3.writeEnvelope(arena, cur_side, base_side, oth_side) catch return mergeOom(streams);
                entries.append(arena, .{
                    .path = path,
                    .action = .{ .write = .{ .bytes = bytes, .perm = perm } },
                }) catch return mergeOom(streams);
                conflicts.append(arena, path) catch return mergeOom(streams);
            },
        }
    }

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

    // Materialize (journal-armed) and record the pending operation: a plain
    // merge's `merge_parent` (other's hash) or a special merge's `special_op`
    // (sign + REV). `applyMerge` writes the checkout FIRST, so a conflict still
    // records the pending state for `zit commit`/`zit undo` (B-merge-3/7/35).
    update.applyMerge(gpa, io, root_dir, entries.items, .{
        .version = ck.version,
        .branch = ck.branch,
        .merge_parent = spec.merge_parent,
        .special_op = spec.special_op,
        // A merge changes the check-in, never the checkout's manifest opt-in.
        .manifest_flags = ck.manifest_flags,
    }) catch |e| return mergeApplyFail(streams, e);

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

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

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

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

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

// ==========================================================================
// `zit revert` — restore managed files to their content at the current
// check-in (artifact §8.4 effective file + §7.2 verified blob). A thin consumer
// of the Repository read path (`fileAt`/`blob`) plus `update.restoreFile`: no
// format work, no managed-set mutation. Content-restore only.
// ==========================================================================

/// `zit revert [PATH...]` — restore managed files to their checked-in content.
/// With no paths, every managed file; with paths, only the named managed files.
fn runRevert(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    const parsed = switch (cli.parseRevertArgs(gpa, verb_args) catch return revertOom(streams)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "revert", .unknown_option, tok),
    };
    defer gpa.free(parsed.paths);
    if (parsed.help) {
        streams.out.writeAll(revert_help) catch {};
        return .ok;
    }

    // Discover the root (its absolute path drives path-scoped `repoRelative`),
    // then open the read-only derived view.
    const root = (cli.discoverRoot(arena, io) catch return revertOom(streams)) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    var repo: Repository = undefined;
    repo.open(gpa, io, root_dir, .{}) catch |e| return repoOpenFail(streams, "revert", e);
    defer repo.deinit(gpa);

    // §7.5: the current checkout names the check-in whose content is restored;
    // an unborn/absent checkout has nothing to revert to.
    const rid = repo.currentCheckoutRid() orelse return revertNoCheckout(streams);

    // The managed set — read, never written: revert restores content only.
    var set = managed.ManagedSet.read(gpa, io, root_dir) catch |e|
        return managedFail(streams, "revert", e);
    defer set.deinit();

    // Gather the resolved restore targets first, so the undo journal captures
    // every path's pre-revert bytes in ONE seam before the first file is
    // rewritten (B-undo-2/14). Untracked or unresolvable args are reported here
    // and excluded from both the journal image and the restore.
    var targets: std.ArrayList([]const u8) = .empty;
    defer targets.deinit(gpa);
    var had_error = false;
    if (parsed.paths.len == 0) {
        for (set.iterate()) |path| targets.append(gpa, path) catch return revertOom(streams);
    } else {
        const cwd_abs = (cli.currentPathAlloc(arena, io) catch return revertOom(streams)) orelse {
            streams.err.writeAll("zit revert: cannot determine the current directory\n") catch {};
            return .failure;
        };
        for (parsed.paths) |arg| {
            const key = switch (cli.repoRelative(arena, root.abs, cwd_abs, arg) catch return revertOom(streams)) {
                .key => |k| k,
                .root, .outside => {
                    revertNotTracked(streams, arg);
                    had_error = true;
                    continue;
                },
            };
            if (!set.contains(key)) {
                revertNotTracked(streams, key);
                had_error = true;
                continue;
            }
            targets.append(gpa, key) catch return revertOom(streams);
        }
    }

    // Journal-before-mutate (B-undo-3): the undo image is written and fsynced
    // before the first restore. A journal fault aborts with nothing mutated —
    // the durability rule forbids restoring without a recoverable pre-image.
    if (targets.items.len != 0) {
        update.journal.record(gpa, io, root_dir, targets.items) catch |e|
            return revertJournalFail(streams, e);
    }

    for (targets.items) |name| {
        if (revertOne(gpa, io, &repo, root_dir, rid, name, streams) == .failed) had_error = true;
    }
    return if (had_error) .failure else .ok;
}

/// A journal-write failure before revert touches any file — exit 1, nothing
/// mutated. `record` only surfaces `OutOfMemory`/`Storage`; the `else` folds the
/// device faults into the honest I/O message.
fn revertJournalFail(s: cli.Streams, e: update.journal.JournalError) cli.Exit {
    switch (e) {
        error.OutOfMemory => s.err.writeAll("zit revert: out of memory\n") catch {},
        else => s.err.writeAll("zit revert: cannot write the undo journal: input/output error\n") catch {},
    }
    return .failure;
}

/// The per-file revert verdict: content restored, nothing to restore (absent
/// from the effective set — informational, not an error), or a genuine fault.
const RevertOutcome = enum { reverted, skipped, failed };

/// Restore one managed file `name` to its content at `rid`. §8.4 effective
/// lookup: a file absent from the effective set (never present, or a §4.7.6
/// delete marker) has no content to restore — reported and left unchanged,
/// never fabricated (`.skipped`). A read/write fault is `.failed`.
fn revertOne(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    rid: Repository.Rid,
    name: []const u8,
    streams: cli.Streams,
) RevertOutcome {
    const found = repo.fileAt(gpa, rid, name) catch |e| {
        revertFileFail(streams, name, e);
        return .failed;
    };
    const card = found orelse {
        streams.err.print("zit revert: '{s}' is not in the current check-in; left unchanged\n", .{name}) catch {};
        return .skipped;
    };
    defer Repository.freeFileCard(gpa, card);
    std.debug.assert(card.hash != null); // fileAt yields only hash-bearing cards (§4.7.6)

    // §7.2: the blob is verified to hash to its F-card id before it lands.
    const bytes = (repo.blob(gpa, card.hash.?) catch |e| {
        revertFileFail(streams, name, e);
        return .failed;
    }) orelse {
        streams.err.print("zit revert: content for '{s}' is missing; left unchanged\n", .{name}) catch {};
        return .failed;
    };
    defer gpa.free(bytes);

    update.restoreFile(io, root_dir, name, bytes, card.mode) catch |e| {
        switch (e) {
            error.SymlinkUnsupported => streams.err.print(
                "zit revert: '{s}' is a symlink, which zit does not support; left unchanged\n",
                .{name},
            ) catch {},
            error.Storage => streams.err.print(
                "zit revert: cannot restore '{s}': input/output error\n",
                .{name},
            ) catch {},
        }
        return .failed;
    };
    streams.out.print("reverted {s}\n", .{name}) catch {};
    return .reverted;
}

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

fn revertNoCheckout(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit revert: nothing to revert to (the working checkout is unborn)\n") catch {};
    return .failure;
}

fn revertNotTracked(s: cli.Streams, path: []const u8) void {
    s.err.print("zit revert: '{s}' is not tracked (use 'zit add' to track it)\n", .{path}) catch {};
}

/// Maps a `Repository.fileAt`/`blob` failure to a per-file diagnostic (no exit
/// code — the caller aggregates). Switches the full `FilesError` set
/// exhaustively; `blob`'s narrower `OpenError` coerces in. Phrasings match
/// `ls`/`cat`.
fn revertFileFail(s: cli.Streams, name: []const u8, e: Repository.FilesError) void {
    switch (e) {
        error.OutOfMemory => s.err.writeAll("zit revert: out of memory\n") catch {},
        error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
        error.CannotRead => s.err.print("zit revert: cannot read '{s}': input/output error\n", .{name}) catch {},
        error.Corrupt => s.err.print("zit revert: cannot read '{s}': repository is corrupt\n", .{name}) catch {},
        error.NotManifest => s.err.writeAll("zit revert: not a check-in\n") catch {},
        error.BaselineUnresolvable => s.err.writeAll("zit revert: cannot resolve the baseline of a delta check-in\n") catch {},
        error.BaselineIsDelta => s.err.writeAll("zit revert: the baseline of a delta check-in is itself a delta\n") catch {},
    }
}

// ==========================================================================
// `zit undo` / `zit redo` — single-level undo/redo of the working-file mutators
// (contracts/undo.md B-undo-1..21). Thin wiring: parse (help-only, no
// positionals), discover the root BEFORE any journal read (B-undo-19), then
// drive the `update.journal` swap. All format/slot work lives in `undo.zig`;
// restoration reuses the update layer. No log append, no network.
// ==========================================================================

const UndoKind = enum { undo, redo };

/// `zit undo` — reverse the last sheltered working-file mutation.
fn runUndo(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    return runUndoRedo(gpa, io, arena, verb_args, streams, .undo);
}

/// `zit redo` — reapply the change a preceding `zit undo` reversed.
fn runRedo(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    return runUndoRedo(gpa, io, arena, verb_args, streams, .redo);
}

/// The shared body: the two verbs differ only in name, help text, which journal
/// slot they consume, and the "nothing to …" phrasing (Ousterhout: one
/// mechanism, not two near-identical copies).
fn runUndoRedo(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    kind: UndoKind,
) cli.Exit {
    const verb = switch (kind) {
        .undo => "undo",
        .redo => "redo",
    };
    const help_text = switch (kind) {
        .undo => undo_help,
        .redo => redo_help,
    };
    // Usage errors are exit 2, stderr-only, and read no journal (B-undo-17/18);
    // `-h`/`--help` win over any trailing token and print to stdout (B-undo-16).
    const parsed = switch (cli.parseNoPositionalArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, verb, .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, verb, .extra_argument, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(help_text) catch {};
        return .ok;
    }

    // B-undo-19: the repository check precedes any journal read; absent → the
    // standard not-a-zit-repository diagnostic, exit 1 (distinct from exit 2).
    const root = (cli.discoverRoot(arena, io) catch {
        streams.err.print("zit {s}: out of memory\n", .{verb}) catch {};
        return .failure;
    }) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    (switch (kind) {
        .undo => update.journal.undo(gpa, io, root_dir),
        .redo => update.journal.redo(gpa, io, root_dir),
    }) catch |err| return undoFail(streams, verb, err);

    // The single confirmation row goes to stdout (B-undo-20); diagnostics never
    // share the stream.
    streams.out.print("{s}: working tree restored\n", .{verb}) catch {};
    return .ok;
}

/// Renders a `JournalError` to stderr and returns `.failure` (exit 1). `Empty`
/// is the nothing-to-undo/redo case (B-undo-9/10); `Corrupt` the damaged
/// journal (B-undo-11); the rest are honest device/allocation faults.
fn undoFail(s: cli.Streams, verb: []const u8, err: update.journal.JournalError) cli.Exit {
    switch (err) {
        error.Empty => s.err.print("zit {s}: nothing to {s}\n", .{ verb, verb }) catch {},
        error.Corrupt => s.err.print("zit {s}: the undo journal is damaged\n", .{verb}) catch {},
        error.Storage => s.err.print("zit {s}: cannot restore working tree: input/output error\n", .{verb}) catch {},
        error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) 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.
// ==========================================================================

/// SHA3-256 digest length: the on-disk log frame is keyed by these 32 raw bytes
/// (logstore.max_hash_len), while the artifact NAME is their 64-hex form. `init`
/// wrote the SHA3-256 policy (B-commit-16), so the algorithm is this constant.
pub const digest_len = 32;

/// Decodes a 64-hex artifact name into its 32-byte binary digest — the log-frame
/// key. Returns null for a non-64-hex string (a corrupt checkout `version`), so
/// the caller maps it to the parent-corrupt diagnostic rather than trapping.
pub fn hexToDigest(hex: []const u8) ?[digest_len]u8 {
    if (hex.len != digest_len * 2) return null;
    var d: [digest_len]u8 = undefined;
    _ = std.fmt.hexToBytes(&d, hex) catch return null;
    return d;
}

/// Lowercase-hex-encodes a raw binary `digest` into `out`, returning the used
/// prefix — the log-frame key's wire NAME (sync §3.3). The inverse of
/// `decodeWireName`; both live at the log↔store boundary so no other module
/// sees a raw digest cross into wire space.
pub fn digestToWireName(digest: []const u8, out: *[2 * digest_len]u8) []const u8 {
    std.debug.assert(digest.len <= digest_len);
    const hexdigits = "0123456789abcdef";
    for (digest, 0..) |b, i| {
        out[2 * i] = hexdigits[b >> 4];
        out[2 * i + 1] = hexdigits[b & 0x0f];
    }
    return out[0 .. 2 * digest.len];
}

/// Decodes a wire artifact NAME (40- or 64-hex, sync §3.3) into its raw binary
/// digest — the log-frame key. Returns null for anything that is not an
/// even-length hex string of at most `digest_len` bytes, so a malformed peer
/// name is rejected cleanly rather than trapping. The inverse of
/// `digestToWireName`.
pub fn decodeWireName(name: []const u8, out: *[digest_len]u8) ?[]const u8 {
    if (name.len == 0 or name.len % 2 != 0) return null;
    const nbytes = name.len / 2;
    if (nbytes > digest_len) return null;
    _ = std.fmt.hexToBytes(out[0..nbytes], name) catch return null;
    return out[0..nbytes];
}

/// 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();
}

/// One managed file captured for the check-in, or the reason it cannot be
/// (rendered by the caller so the stderr/exit discipline stays in `runCommit`).
const Capture = union(enum) {
    /// The file's F card (hash duped onto the manifest arena).
    card: artifact.FCard,
    missing, // absent from the working tree (B-commit-10)
    /// Present but not a regular file (B-commit-10). The payload is `true` for
    /// a symlink, which gets the F-B3 recovery hint instead of the bare
    /// refusal — carried here rather than re-stat'd by the renderer.
    not_regular: bool,
    io_error, // a read/store device failure (B-commit-15)
    oom,
};

/// Stats, reads, hashes, and stores one managed file `key`, returning its F card
/// or the reason it could not be captured. All of `commit`'s working-tree read
/// I/O lives here (design-seams rule). Symlinks are not followed, so a symlink
/// is `not_regular`, never silently resolved. The blob is stored uncompressed
/// (the name is over uncompressed bytes; storage compression is deferred —
/// Scope). Idempotent re-intern: `logstore.put` appends nothing for a blob
/// already present.
fn captureFile(
    gpa: std.mem.Allocator,
    io: std.Io,
    ma: std.mem.Allocator,
    root_dir: std.Io.Dir,
    log: *logstore.LogStore,
    key: []const u8,
    base: ?logstore.Rid,
) Capture {
    const st = root_dir.statFile(io, key, .{ .follow_symlinks = false }) catch return .missing;
    if (st.kind != .file) return .{ .not_regular = st.kind == .sym_link };
    if (!trackedFileSizeAllowed(st.size)) return .io_error;
    const content = root_dir.readFileAlloc(io, key, gpa, .limited(max_tracked_file_bytes)) catch |e|
        return switch (e) {
            error.OutOfMemory => .oom,
            else => .io_error,
        };
    defer gpa.free(content);
    // The on-disk log keys frames by the binary digest (logstore.max_hash_len ==
    // 32); the F card carries the 64-hex artifact name (§4.7.1 wire form). Both
    // derive from the same content, so naming is unaffected by storage.
    var digest: [digest_len]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(content, &digest, .{});
    var name_buf: [64]u8 = undefined;
    const name = artifact.artifactName(.sha3_256, content, &name_buf);
    // §4.1/§7.2 — store the blob, delta-encoded against the same path's blob in
    // the parent check-in when that is materially smaller (else a full §4.1
    // container). `base` is a hint only; naming is always over the uncompressed
    // bytes, so storage compression/delta never changes HASH.
    _ = log.putArtifact(&digest, content, base) catch |e| return switch (e) {
        error.OutOfMemory => .oom,
        error.Storage => .io_error,
    };
    const hash = ma.dupe(u8, name) catch return .oom;
    const filename = ma.dupe(u8, key) catch return .oom;
    // Capture the working-tree executable bit so a chmod +x round-trips into the
    // check-in instead of silently reverting to regular (a permission drift that
    // otherwise shows as `M` on every diff and never commits). §4.7.6: a perm
    // token containing `x` marks the entry executable, and a producer SHOULD emit
    // only w/x/l — so an executable file carries the explicit `x` token (needed
    // for the mode to survive re-parse via `fileMode`), and a regular file omits
    // the token. Non-regular kinds already returned `.not_regular` above, so the
    // mode is only ever regular or executable here.
    const is_exec = executable(st.permissions);
    return .{ .card = .{
        .filename = filename,
        .hash = hash,
        .perm = if (is_exec) "x" else null,
        .old_name = null,
        .mode = if (is_exec) .executable else .regular,
    } };
}

/// True when `bytes` still carries an unresolved three-way conflict marker: the
/// `merge3.conflict_sentinel` at the start of a line (file start or right after
/// a LF), exactly as `merge3.writeEnvelope` emits it. The sole consumer of the
/// sentinel outside `merge3` — `zit commit` scans every captured file of a
/// recorded merge and refuses on any hit (B-merge-10).
fn hasConflictMarker(bytes: []const u8) bool {
    if (std.mem.startsWith(u8, bytes, merge3.conflict_sentinel)) return true;
    return std.mem.indexOf(u8, bytes, "\n" ++ merge3.conflict_sentinel) != null;
}

/// `zit commit -m <message> [--user <login>] [-q] [--] [<path>...]` — the thin
/// wiring: parse → discover → load checkout+managed set → capture working-tree
/// files → compose the F-set (`cli.composeFCards`) → assemble+serialize the
/// manifest (`artifact.create`) → append blobs+manifest and fsync the log →
/// advance `.zit-checkout` → render. Durability order (B-commit-15): the log is
/// committed before the checkout advances; a failure between is stated honestly.
fn runCommit(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    // 1. Parse (B-commit-1). --help wins over everything (B-commit-18a); an
    //    unknown/dangling option is a usage error (B-commit-18b).
    const parsed = switch (cli.parseCommitArgs(gpa, verb_args) catch
        return commitOom(streams)) {
        .ok => |p| p,
        .unknown_option => |tok| {
            // A git user reaches for `--amend`/`--force` to rewrite the last
            // check-in, but zit history is immutable (B-commit-20): check-ins are
            // never rewritten. Teach the model at the point of error rather than
            // deferring the lesson to --help; a bare "unknown option" would read
            // as a typo and hide the immutable-history rule. Still a usage error:
            // exit 2, stderr only, and the try-help line is kept.
            if (std.mem.eql(u8, tok, "--amend") or
                std.mem.eql(u8, tok, "--force") or std.mem.eql(u8, tok, "-f"))
            {
                streams.err.print(
                    "zit commit: '{s}' is not supported. zit history is immutable — " ++
                        "check-ins are never rewritten; record a new check-in that " ++
                        "supersedes the old one.\n",
                    .{tok},
                ) catch {};
                streams.err.writeAll("try 'zit commit --help'\n") catch {};
                return .usage;
            }
            return cli.usageError(streams, "commit", .unknown_option, tok);
        },
    };
    defer gpa.free(parsed.paths);
    if (parsed.help) {
        streams.out.writeAll(commit_help) catch {};
        return .ok;
    }

    // 2. A message is required (B-commit-5, a usage error) and must be
    //    meaningful (B-commit-4, an expected failure) — both before any I/O.
    const message = parsed.message orelse {
        streams.err.writeAll(
            "zit commit: a check-in message is required: -m <message>\ntry 'zit commit --help'\n",
        ) catch {};
        return .usage;
    };
    if (std.mem.trim(u8, message, " \t\r\n").len == 0) {
        streams.err.writeAll(
            "zit commit: aborting — empty check-in message\n",
        ) catch {};
        return .failure;
    }

    // 3. Resolve the author (B-commit-6): --user, else the environment default.
    const author = parsed.user orelse amb.user_env orelse {
        streams.err.writeAll(
            "zit commit: cannot determine the check-in author; pass --user <login>\n",
        ) catch {};
        return .failure;
    };

    // 4. Discover the checkout root (B-commit-14) and load the working state.
    const root = (cli.discoverRoot(arena, io) catch
        return commitOom(streams)) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
    const ck = (checkout.read(io, root_dir, &ck_buf) catch |e|
        return checkoutFail(streams, "commit", e)) orelse
        return commitCheckoutMissing(streams);
    const branch = if (ck.branch.len == 0) "trunk" else ck.branch;
    const is_root = ck.version.len == 0;
    // A recorded merge parent (from `zit merge`) turns this into a merge commit:
    // it emits the two-token P card and clears the record on advance (B-merge-8/
    // 9). Empty == no pending merge → the ordinary single-parent path, untouched
    // (B-merge-9 negative space). A merge is never a root (it requires a prior
    // version), so `is_merge` implies `!is_root`.
    const is_merge = ck.merge_parent.len != 0;
    // A recorded special-merge op (cherrypick/backout, from `zit merge
    // --cherrypick/--backout`) is NOT a merge: the check-in stays SINGLE-parent
    // (REV is never a merge parent, B-merge-33) and carries one Q card recording
    // the provenance (§4.7.14). `special_op` is the q-sign byte glued onto REV's
    // hash; empty means no pending special op → today's path, untouched. A
    // special op requires a prior version, so it too implies `!is_root`. At most
    // one of `is_merge`/`has_special` is ever set (the merge verb refuses to
    // start a second pending operation).
    const has_special = ck.special_op.len != 0;
    const q_sign: ?artifact.QSign = if (!has_special) null else switch (ck.special_op[0]) {
        '+' => .cherrypick,
        '-' => .backout,
        else => unreachable, // `merge` only ever writes '+' or '-'
    };

    // repostate §6.2: a branch-root manifest is a CHILD of the branch point, so
    // `--branch` needs a parent to fork from. The root check-in's default-branch
    // start is `init`/§6.1's job, not a fork — reject `--branch` on an unborn
    // checkout before any capture.
    if (is_root and parsed.branch != null) {
        streams.err.writeAll(
            "zit commit: --branch needs a parent check-in; the first commit starts branch 'trunk'\n",
        ) catch {};
        return .failure;
    }
    // An empty `--branch` value names no branch (§6.2). Reject it here, with the
    // other early arg checks, before any store is opened.
    if (parsed.branch) |bname| {
        if (bname.len == 0) {
            streams.err.writeAll("zit commit: --branch name must not be empty\n") catch {};
            return .failure;
        }
    }
    // The branch the new check-in lands on: `--branch` overrides, else the
    // parent's branch (trunk when unset). `compose_branch` is the name whose
    // §6.2 branch/sym tags this commit emits — always trunk for the root
    // (establishing it), the explicit `--branch` for a child that switches, and
    // null for a child that stays on its parent's branch (no tag, inherited).
    const target_branch = parsed.branch orelse branch;
    const compose_branch: ?[]const u8 = if (is_root) target_branch else parsed.branch;

    var set = managed.ManagedSet.read(gpa, io, root_dir) catch |e|
        return managedFail(streams, "commit", e);
    defer set.deinit();

    // 5. Open the log read-write (append blobs + manifest, then fsync).
    var file = root_dir.openFile(io, repo_filename, .{ .mode = .read_write }) catch
        return commitLogFail(streams, error.Storage);
    defer file.close(io);
    const log_st = file.stat(io) catch return commitLogFail(streams, error.Storage);
    var fs = storage.FileStorage.init(io, file, log_st.size);
    // `hash_kind` 0 is a don't-care on a non-empty file: `open` reads the stored
    // kind from the header. The repo was named SHA3-256 by `init` (B-commit-16).
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch |e|
        return commitLogFail(streams, e);
    defer log.deinit(gpa);

    // 6. One arena owns every card's storage (F slice, arena copies of each
    //    captured hash + filename); `create` reads card fields only, so the CLI
    //    supplies the arena. Content buffers are read on `gpa` and freed per file.
    var m_arena = std.heap.ArenaAllocator.init(gpa);
    defer m_arena.deinit();
    const ma = m_arena.allocator();

    // 6b. Branch prep (repostate §6.2), only when `--branch` starts/switches a
    //     branch. The derived read-only view answers two questions the append
    //     transaction cannot: does NAME already name an open branch (§6.2 forbids
    //     re-creating one), and which of the parent's active sym-* tags must this
    //     commit cancel so the check-in leaves the parent's branch(es). The view
    //     is opened read-only and freed before any append; the sym names are
    //     duped onto `ma` so they outlive it. `--tag`/`--close` need no view.
    var parent_syms: []const []const u8 = &.{};
    if (parsed.branch) |bname| {
        var repo: Repository = undefined;
        repo.open(gpa, io, root_dir, .{}) catch |e| return repoOpenFail(streams, "commit", e);
        defer repo.deinit(gpa);
        const open_leaves = repo.state().openLeavesOf(gpa, bname) catch return commitOom(streams);
        defer gpa.free(open_leaves);
        if (open_leaves.len != 0) {
            streams.err.print(
                "zit commit: branch '{s}' already exists with an open leaf; commit onto it or choose a new name\n",
                .{bname},
            ) catch {};
            return .failure;
        }
        // The parent's inherited sym-* tags to cancel, minus the one we
        // re-establish, duped onto `ma` (the view's interned names die at
        // `repo.deinit`).
        if (repo.currentCheckoutRid()) |prid| {
            const want_sym = std.mem.concat(ma, u8, &.{ sym_prefix, bname }) catch return commitOom(streams);
            const entries = repo.state().tagsOf(gpa, prid) catch return commitOom(streams);
            defer gpa.free(entries);
            parent_syms = selectInheritedSyms(ma, entries, want_sym) catch return commitOom(streams);
        }
    }

    // 7. Parent manifest (child only): read + parse it for carry-forward, the
    //    no-op verdict (B-commit-9/11), AND the per-path delta bases. Loaded
    //    BEFORE capture — it has no dependency on capture — so each captured
    //    blob can be delta-encoded against the same path's parent blob (§7.2
    //    storage compaction). Slice-1 parents are always full manifests, so no
    //    delta resolution is reached here.
    var pm: ?artifact.Manifest = null;
    defer if (pm) |*m| m.deinit();
    // Read path: the parent is prior (possibly fossil-origin) history, so it is
    // parsed with the legacy F-card trailing-separator tolerance.
    var pm_normalized: ?[]u8 = null;
    defer if (pm_normalized) |b| gpa.free(b);
    var parent_bytes: ?[]u8 = null;
    defer if (parent_bytes) |b| gpa.free(b);
    var parent_f: []const artifact.FCard = &.{};
    var parent_manifest_rid: ?logstore.Rid = null;
    // path → parent blob rid: the delta base for the same path this commit.
    var parent_blob = std.StringHashMap(logstore.Rid).init(gpa);
    defer parent_blob.deinit();
    if (!is_root) {
        const pdigest = hexToDigest(ck.version) orelse return commitParentCorrupt(streams);
        const prid = log.lookup(&pdigest) orelse return commitParentCorrupt(streams);
        parent_manifest_rid = prid;
        parent_bytes = (log.content(gpa, prid) catch |e| return commitContentFail(streams, e)) orelse
            return commitParentCorrupt(streams);
        const parent_im = artifact.parseForImport(gpa, parent_bytes.?) catch return commitParentCorrupt(streams);
        pm = parent_im.manifest;
        pm_normalized = parent_im.normalized;
        parent_f = pm.?.f;
        // A parent F card whose blob resolves in the log maps its path to that
        // blob's rid; a card without a resolvable blob is simply absent (its
        // child blob then stores full — the base hint is optional).
        for (parent_f) |fc| {
            const h = fc.hash orelse continue;
            const bd = hexToDigest(h) orelse continue;
            const brid = log.lookup(&bd) orelse continue;
            parent_blob.put(fc.filename, brid) catch return commitOom(streams);
        }
    }

    // 8. Capture the working-tree files and pick the merge policy (B-commit-8/
    //    10/11/12). This is the only place the all-files/partial split is
    //    decided; all merge/sort/no-op arithmetic is deferred to composeFCards.
    var captured: std.ArrayList(artifact.FCard) = .empty;
    const policy: cli.ComposePolicy = if (parsed.paths.len == 0) .snapshot else .carry_forward;
    if (parsed.paths.len == 0) {
        // All-files: capture every managed path (a deletion is simply absent
        // from the set → not captured → dropped by composeFCards, B-commit-12).
        for (set.iterate()) |path| {
            switch (captureFile(gpa, io, ma, root_dir, &log, path, parent_blob.get(path))) {
                .card => |c| captured.append(ma, c) catch return commitOom(streams),
                .missing => return commitMissing(streams, path),
                .not_regular => |is_symlink| return commitNotRegular(streams, path, is_symlink),
                .io_error => return commitCaptureIo(streams, path),
                .oom => return commitOom(streams),
            }
        }
    } else {
        // Partial: capture only the named managed files (B-commit-11). The
        // unnamed parent files are carried forward by composeFCards, not here.
        const cwd_abs = (cli.currentPathAlloc(arena, io) catch
            return commitOom(streams)) orelse
            return commitLogFail(streams, error.Storage);
        for (parsed.paths) |arg| {
            const key = switch (cli.repoRelative(arena, root.abs, cwd_abs, arg) catch
                return commitOom(streams)) {
                .key => |k| k,
                .root, .outside => return commitNotTracked(streams, arg),
            };
            if (!set.contains(key)) return commitNotTracked(streams, key);
            switch (captureFile(gpa, io, ma, root_dir, &log, key, parent_blob.get(key))) {
                .card => |c| captured.append(ma, c) catch return commitOom(streams),
                .missing => return commitMissing(streams, key),
                .not_regular => |is_symlink| return commitNotRegular(streams, key, is_symlink),
                .io_error => return commitCaptureIo(streams, key),
                .oom => return commitOom(streams),
            }
        }
    }

    // 8b. Stamp the pending rename (§4.7.6): if `zit mv` recorded a rename and
    //     NEW was captured this commit, mark that card with OLD as the fourth
    //     (old-name) token plus an explicit permission token — the grammar keeps
    //     old-name in the fourth field only when a perm token precedes it, and
    //     §4.7.6 SHOULD-w for a regular file (an executable keeps its `x`). The
    //     card is captured under NEW, so composeFCards sorts it under NEW (§4.6)
    //     and the perm/old_name fields ride through the sort/no-op logic
    //     untouched. `carried` gates the one-shot clear (step 12b): a partial
    //     commit that does not name NEW leaves the record pending (B-mv-8). OLD
    //     is duped onto `ma` so the card never aliases the record freed at clear.
    var carried = false;
    if (set.pendingRename()) |rn| {
        for (captured.items) |*c| {
            if (std.mem.eql(u8, c.filename, rn.new)) {
                c.old_name = ma.dupe(u8, rn.old) catch return commitOom(streams);
                c.perm = c.perm orelse "w";
                carried = true;
                break;
            }
        }
    }

    // 9. Compose the F-set and map the no-op verdict (B-commit-9). Guarded
    //    before any durable write — nothing is committed on a no-op. A rename
    //    always makes NEW differ from the parent's names, so it is never a no-op.
    const composed = cli.composeFCards(ma, .{
        .parent = parent_f,
        .captured = captured.items,
        .policy = policy,
    }) catch return commitOom(streams);
    // A pending merge / cherrypick / backout is itself the change: a convergent
    // merge (both sides made the same edit) composes to F cards identical to the
    // parent's, so `unchanged` goes true even though a second parent (P card) or
    // a provenance record (Q card) is queued. Refusing there wedges the tree with
    // `undo` as the only escape and silently drops the merge parent (blocker B5),
    // so the no-op verdict applies only to ordinary commits.
    if (composed.unchanged and !is_merge and !has_special) {
        if (is_root)
            streams.err.writeAll(
                "zit commit: nothing to commit (no tracked files) — use 'zit add <file>'\n",
            ) catch {}
        else
            streams.err.writeAll("zit commit: nothing to commit (no changes)\n") catch {};
        return .failure;
    }

    // 9b. A recorded merge must not be committed while any file it captures still
    //     carries an unresolved conflict marker (B-merge-10). Re-read each
    //     captured working-tree file and scan for `merge3.conflict_sentinel` at a
    //     line start; any hit refuses (exit 1, offending path(s) to stderr) with
    //     no check-in minted and the merge parent still recorded — there is no
    //     override flag; in-tree resolution or `zit undo` is the only way forward.
    //     Gated on `is_merge`/`has_special`, so an ordinary commit reads nothing
    //     extra and its bytes/I/O are unperturbed. Placed before any durable log
    //     write, so a refusal commits nothing. A cherrypick/backout conflict is
    //     surfaced identically (B-merge-35, the conflict model verbatim).
    if (is_merge or has_special) {
        var unresolved: usize = 0;
        for (captured.items) |c| {
            const cbytes = root_dir.readFileAlloc(io, c.filename, gpa, .limited(max_tracked_file_bytes)) catch |e|
                return switch (e) {
                    error.OutOfMemory => commitOom(streams),
                    else => commitCaptureIo(streams, c.filename),
                };
            defer gpa.free(cbytes);
            if (hasConflictMarker(cbytes)) {
                streams.err.print("zit commit: unresolved conflict in {s}\n", .{c.filename}) catch {};
                unresolved += 1;
            }
        }
        if (unresolved != 0) {
            streams.err.print(
                "zit commit: {d} unresolved conflict(s); resolve and commit, or run 'zit undo'\n",
                .{unresolved},
            ) catch {};
            return .failure;
        }
    }

    // 10. Assemble the manifest and serialize it (B-commit-17). The library owns
    //     the Z self-check, card order, escaping, and framing. Root establishes
    //     `trunk` via two propagating T cards (B-commit-13); a child carries one
    //     P card and no T card (inherits trunk by propagation).
    var ts_buf: [19]u8 = undefined;
    const ts = cli.formatWriterTimestamp(amb.now_epoch, &ts_buf);
    // Control tags (repostate §6.2 branch creation + artifact §4.7 close).
    // The root establishes trunk (two propagating tags — `--branch` is rejected
    // on the root); a child emits branch/sym/cancel tags only when `--branch`
    // switches it, plus `+closed` on `--close`. In the common no-flag child case
    // this is an empty slice, preserving today's bytes exactly. (`--tag` is
    // deferred behind the propagating-vs-singleton ambiguity, so it is absent.)
    const tags = cli.composeCommitTags(ma, .{
        .branch = compose_branch,
        .close = parsed.close,
        .parent_syms = parent_syms,
    }) catch return commitOom(streams);
    // A recorded merge extends the single primary parent to a two-token P card
    // (B-merge-8): `P <primary> <merge-parent>`, primary ancestor first (§4.7.13
    // / repostate §3.2 first-listed-is-primary), SP-joined so `appendPCard`
    // renders both tokens verbatim. The non-merge case keeps `count == 1` and
    // `parents == ck.version`, so today's manifest bytes are byte-identical.
    const parents_field: []const u8 = if (is_merge)
        std.mem.concat(ma, u8, &.{ ck.version, " ", ck.merge_parent }) catch return commitOom(streams)
    else
        ck.version;
    const child_parents = [_]artifact.PCard{.{
        .parents = parents_field,
        .count = if (is_merge) 2 else 1,
    }};
    // A recorded special-merge op mints exactly one Q card (§4.7.14, B-merge-33):
    // `Q +<rev>` (cherrypick) or `Q -<rev>` (backout), the sign glued onto the
    // target hash, baseline token OMITTED — the omitted-baseline default IS the
    // primary parent the merge used, so emitting it would be redundant. The
    // target borrows `ck.special_op` (which outlives `create`, exactly as the P
    // card borrows `ck.version`). The non-special case keeps an empty `q` slice,
    // so today's manifest bytes are byte-identical (B-merge-31).
    var q_cards: [1]artifact.QCard = undefined;
    const q_slice: []const artifact.QCard = if (q_sign) |s| blk: {
        q_cards[0] = .{ .sign = s, .target = ck.special_op[1..], .baseline = null };
        break :blk &q_cards;
    } else &.{};
    var m: artifact.Manifest = .{
        .arena_state = std.heap.ArenaAllocator.init(gpa),
        .kind = .manifest,
        .a = null,
        .b = null,
        .c = .{ .comment = message },
        .d = .{ .timestamp = ts },
        .e = null,
        .g = null,
        .h = null,
        .i = null,
        .k = null,
        .l = null,
        .n = null,
        .r = null,
        .u = .{ .login = author },
        .z = null,
        .w = null,
        .f = composed.f,
        .j = &.{},
        .m = &.{},
        .p = if (is_root) &.{} else &child_parents,
        .q = q_slice,
        .t = tags,
    };
    defer m.deinit(); // frees the empty arena_state; card storage is m_arena's
    const bytes = artifact.create(&m, gpa) catch return commitOom(streams);
    defer gpa.free(bytes);
    // Correctness self-check (safety builds only): the emitted bytes round-trip
    // to a manifest. A failure means the CLI mis-populated a card — a bug caught
    // here, never shipped.
    if (std.debug.runtime_safety) {
        var check = artifact.parse(gpa, bytes) catch |e|
            std.debug.panic("commit produced an unparseable manifest: {s}", .{@errorName(e)});
        defer check.deinit();
        std.debug.assert(check.kind == .manifest);
    }

    // 11. Store the manifest and durably commit the log (B-commit-15 order). The
    //     frame is keyed by the binary digest; the reported name is the 64-hex.
    var mdigest: [digest_len]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(bytes, &mdigest, .{});
    var mname_buf: [64]u8 = undefined;
    const manifest_name = artifact.artifactName(.sha3_256, bytes, &mname_buf);
    // §4.1/§7.2 — store the manifest, delta-encoded against the primary parent
    // manifest when materially smaller (else a full §4.1 container). The
    // reported name is the 64-hex of the UNCOMPRESSED manifest, so
    // delta/compression is address-transparent.
    _ = log.putArtifact(&mdigest, bytes, parent_manifest_rid) catch |e| return commitLogFail(streams, e);
    log.commit() catch |e| return commitLogFail(streams, e);

    // 12a. Clear the pending rename now that the check-in carrying it is durable
    //      (B-mv-8, one-shot: consumed only by the commit that named NEW). Order
    //      is log-durable → managed-clear (fsync) → checkout-advance, so a crash
    //      between stages leaves a recoverable tree (B-commit-15 discipline). The
    //      no-rename common case skips this entirely, so today's bytes and I/O
    //      are unperturbed (B-mv-9).
    if (carried) {
        set.clearRename();
        set.write(io, root_dir) catch |e| return managedFail(streams, "commit", e);
    }

    // 12. Advance the working state — only after the log is durable. The single
    //     non-atomic seam (B-commit-15): a failure here leaves the check-in in
    //     history but the working version un-advanced; a re-run re-parents from
    //     the old version (the durable log is never corrupted).
    // The pending merge OR special-merge op (if any) is consumed by this
    // check-in, so the advanced checkout clears BOTH (`merge_parent = ""`,
    // `special_op = ""`, B-merge-9/34 one-shot clear).
    checkout.write(io, root_dir, .{ .version = manifest_name, .branch = target_branch, .merge_parent = "", .special_op = "", .manifest_flags = "" }) catch
        return commitCheckoutWriteFail(streams);

    // 13. Success (B-commit-2/3/19): the one check-in line to stdout, the full
    //     artifact hash as a fixed-position token, on the branch it landed on.
    //     `-q` suppresses it.
    if (!parsed.quiet) {
        streams.out.print("check-in {s} on {s}\n", .{ manifest_name, target_branch }) catch {};
    }
    return .ok;
}

/// Renders `zit commit: out of memory` and returns `.failure` (B-commit-15).
fn commitOom(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit commit: out of memory\n") catch {};
    return .failure;
}

/// The checkout record vanished between discovery and read (B-commit-15).
fn commitCheckoutMissing(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit commit: cannot read checkout state: .zit-checkout is missing\n") catch {};
    return .failure;
}

/// Renders a B-commit-15 log open/put/commit failure. Exhaustive over the widest
/// closed set (`logstore.OpenError`); the narrower `PutError`/`CommitError`
/// coerce into it, so one mapper serves all three.
fn commitLogFail(s: cli.Streams, err: logstore.OpenError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit commit: out of memory\n") catch {},
        error.Storage => s.err.writeAll(
            "zit commit: cannot write the check-in: input/output error\n",
        ) catch {},
        error.Corrupt => s.err.writeAll("zit commit: the repository is corrupt\n") catch {},
    }
    return .failure;
}

/// Renders a B-commit-15 parent-manifest content failure. A `Corrupt` frame is
/// the parent-corrupt case; exhaustive over `logstore.ContentError`.
fn commitContentFail(s: cli.Streams, err: logstore.ContentError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit commit: out of memory\n") catch {},
        error.Storage => s.err.writeAll(
            "zit commit: cannot write the check-in: input/output error\n",
        ) catch {},
        error.Corrupt => s.err.writeAll("zit commit: the parent check-in is corrupt\n") catch {},
    }
    return .failure;
}

/// The parent check-in named by the checkout could not be found or parsed
/// (B-commit-15). A missing parent frame or a malformed manifest is corruption.
fn commitParentCorrupt(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit commit: the parent check-in is corrupt\n") catch {};
    return .failure;
}

/// The log committed but the working state could not advance (B-commit-15) — the
/// single non-atomic seam, stated honestly.
fn commitCheckoutWriteFail(s: cli.Streams) cli.Exit {
    s.err.writeAll(
        "zit commit: the check-in was recorded but the working state could not be updated: input/output error\n",
    ) catch {};
    return .failure;
}

/// A managed/selected file is absent from the working tree (B-commit-10). Nothing
/// is written — the failure is raised before `logstore.commit`.
fn commitMissing(s: cli.Streams, path: []const u8) cli.Exit {
    s.err.print(
        "zit commit: cannot commit '{s}': missing from the working tree (use 'zit rm' to stop tracking it)\n",
        .{path},
    ) catch {};
    return .failure;
}

/// A managed/selected file is present but not a regular file (B-commit-10).
/// A tracked SYMLINK is the wedge blocker B3 left in the field (a pre-fix `add
/// .` registered it, and every later commit refuses): 0.1.0 does not version
/// symlinks, so the only way forward is to stop tracking it — the message names
/// that recovery instead of leaving it to be guessed. A fifo/socket keeps the
/// bare refusal: no recovery is being recommended for content zit never claimed.
fn commitNotRegular(s: cli.Streams, path: []const u8, is_symlink: bool) cli.Exit {
    if (is_symlink) {
        s.err.print(
            "zit commit: cannot commit '{s}': " ++ symlink_unversioned ++
                "; run 'zit rm {s}' to stop tracking it\n",
            .{ path, path },
        ) catch {};
        return .failure;
    }
    s.err.print("zit commit: cannot commit '{s}': not a regular file\n", .{path}) catch {};
    return .failure;
}

/// A managed/selected file could not be read or stored (B-commit-15). Raised
/// before `logstore.commit`, so nothing durable is written.
fn commitCaptureIo(s: cli.Streams, path: []const u8) cli.Exit {
    s.err.print("zit commit: cannot commit '{s}': input/output error\n", .{path}) catch {};
    return .failure;
}

/// A named path in a partial commit is not tracked (B-commit-11). Educating: a
/// file must be `zit add`ed before it can be committed.
fn commitNotTracked(s: cli.Streams, path: []const u8) cli.Exit {
    s.err.print("zit commit: '{s}' is not tracked (use 'zit add' first)\n", .{path}) catch {};
    return .failure;
}

/// `zit amend NAME [--comment TEXT] [--user NAME] [--date ISO] [--branch NAME]`
/// (contracts/amend.md B-amend-1..17). amend NEVER rewrites a check-in: it mints
/// ONE control artifact whose T cards change how the target check-in DISPLAYS
/// (comment/user/date/branch), which the crosslinker applies on the next read
/// (repo-state §4/§5). History stays append-only — the original manifest is
/// untouched (B-amend-5). The one durable write is the control artifact + log
/// fsync; every validation (parse, NAME resolution, `--date` predicate,
/// target-is-a-check-in) precedes it, so a refusal mints nothing.
/// Assemble the ONE control artifact carrying `tags`, serialize it (artifact
/// §5.2: exactly D, T…, U, Z), and store it durably in the log — the single
/// fsync. Returns its 64-hex artifact name, written into `name_buf`.
///
/// This is the mint step shared by `amend` and `tag add`: both compose a T run
/// over a resolved check-in and then need exactly this. Everything a caller does
/// before calling is read-only or in-memory, so a crash before the call mints
/// nothing; after it returns, the control is durable and crosslinks on the next
/// read (B-amend-5/7). The library owns card order, escaping, the Z self-check,
/// and framing. D is the mint time — the §5.3 supersede clock (B-amend-6); U is
/// the author's env login (empty → `anonymous` on read, §4.7.17).
///
/// The error set is `logstore.OpenError`, the widest of the three the body can
/// produce, so one caller-side mapper renders all of them under its own verb.
pub fn mintControlArtifact(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    amb: cli.Ambient,
    tags: []const artifact.TCard,
    name_buf: *[64]u8,
) logstore.OpenError![]const u8 {
    std.debug.assert(tags.len >= 1); // a control artifact with no T run says nothing
    var ts_buf: [19]u8 = undefined;
    const ts = cli.formatWriterTimestamp(amb.now_epoch, &ts_buf);
    var m: artifact.Manifest = .{
        .arena_state = std.heap.ArenaAllocator.init(gpa),
        .kind = .control,
        .a = null,
        .b = null,
        .c = null,
        .d = .{ .timestamp = ts },
        .e = null,
        .g = null,
        .h = null,
        .i = null,
        .k = null,
        .l = null,
        .n = null,
        .r = null,
        .u = .{ .login = amb.user_env orelse "" },
        .z = null,
        .w = null,
        .f = &.{},
        .j = &.{},
        .m = &.{},
        .p = &.{},
        .q = &.{},
        .t = tags,
    };
    defer m.deinit(); // frees the empty arena_state; card storage is the caller's
    const bytes = try artifact.create(&m, gpa);
    defer gpa.free(bytes);
    // Correctness self-check (safety builds only): the emitted bytes round-trip
    // to a control artifact. A failure means the CLI mis-populated a card — a bug
    // caught here, never shipped (mirrors commit's self-check).
    if (std.debug.runtime_safety) {
        var check = artifact.parse(gpa, bytes) catch |e|
            std.debug.panic("the control mint produced an unparseable artifact: {s}", .{@errorName(e)});
        defer check.deinit();
        std.debug.assert(check.kind == .control);
    }

    var file = root_dir.openFile(io, repo_filename, .{ .mode = .read_write }) catch
        return error.Storage;
    defer file.close(io);
    const log_st = file.stat(io) catch return error.Storage;
    var fs = storage.FileStorage.init(io, file, log_st.size);
    var log = try logstore.LogStore.open(gpa, fs.storageFile(), 0);
    defer log.deinit(gpa);

    var cdigest: [digest_len]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(bytes, &cdigest, .{});
    const control_name = artifact.artifactName(.sha3_256, bytes, name_buf);
    _ = try log.putArtifact(&cdigest, bytes, null);
    try log.commit();
    return control_name;
}

fn runAmend(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    // 1. Parse (B-amend-1). Usage errors → exit 2; `--help` wins (B-amend-13).
    const parsed = switch (cli.parseAmendArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "amend", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "amend", .extra_argument, tok),
        .repeated_option => |tok| return cli.usageError(streams, "amend", .repeated_option, tok),
        .empty_value => |tok| return cli.usageError(streams, "amend", .empty_value, tok),
        .bad_date => |tok| return cli.usageError(streams, "amend", .bad_date, tok),
        .no_override => return cli.usageError(streams, "amend", .no_override, ""),
    };
    if (parsed.help) {
        streams.out.writeAll(amend_help) catch {};
        return .ok;
    }
    // NAME is required (B-amend-14): a missing positional is a usage error, before
    // any repository access.
    const name = parsed.name orelse return cli.usageError(streams, "amend", .no_name, "");

    // 2. Open the repository read-only for resolution (B-amend-15: the repository
    //    check precedes resolution — `openRepo` renders not-a-zit-repository and
    //    exits 1). Full derive: `resolve`/`tagsOf` read the tag tables.
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "amend", amb.repo_override, false, false, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);

    // 3. Resolve NAME to a check-in and capture everything the mint needs — the
    //    target's 64-hex hash and, for `--branch`, the parent syms to cancel
    //    (repo-state §6.2) — all duped onto `arena` so they outlive the read view,
    //    which is closed before the rw append (commit's durability pattern).
    var target_hash: []const u8 = undefined;
    var parent_syms: []const []const u8 = &.{};
    {
        defer repo.deinit(gpa);
        const rid = repo.resolve(name, .checkin) catch |e| switch (e) {
            // B-amend-9: an ambiguous hash prefix (repo-state §8.3).
            error.Ambiguous => {
                streams.err.print("zit amend: name '{s}' is ambiguous\n", .{name}) catch {};
                return .failure;
            },
            error.OutOfMemory => return stateOom(streams, "amend"),
            error.NotFound => {
                // B-amend-10: a NAME that names a stored non-check-in artifact (a
                // control artifact, say) is refused BY its actual type — T cards
                // target check-ins. Anything else is the B-amend-9 not-found.
                if (amendArtifactType(gpa, &repo, name)) |type_name| {
                    streams.err.print("zit amend: '{s}' is a {s}, not a check-in\n", .{ name, type_name }) catch {};
                } else {
                    streams.err.print("zit amend: check-in '{s}' not found\n", .{name}) catch {};
                }
                return .failure;
            },
        };
        target_hash = arena.dupe(u8, repo.hashOf(rid)) catch return amendOom(streams);

        // repo-state §6.2: a `--branch` move cancels the target's inherited
        // (propagating) sym-* tags, minus the branch's own re-established sym. The
        // surfaced names are duped onto `arena` (the view's interned names die at
        // `repo.deinit`).
        if (parsed.branch) |bname| {
            const want_sym = std.mem.concat(arena, u8, &.{ sym_prefix, bname }) catch return amendOom(streams);
            const entries = repo.state().tagsOf(gpa, rid) catch return amendOom(streams);
            defer gpa.free(entries);
            parent_syms = selectInheritedSyms(arena, entries, want_sym) catch return amendOom(streams);
        }
    }

    // 4. Compose the one control artifact's T run (B-amend-1/4), each card
    //    retargeted at the check-in (artifact §5.4). At least one override is
    //    present (the parser's `no_override` guard), so the run is non-empty.
    const tags = cli.composeAmendTags(arena, target_hash, .{
        .comment = parsed.comment,
        .user = parsed.user,
        .date = parsed.date,
        .branch = parsed.branch,
        .parent_syms = parent_syms,
    }) catch return amendOom(streams);

    // 5-6. Assemble, serialize, and durably store the one control artifact.
    var cname_buf: [64]u8 = undefined;
    const control_name = mintControlArtifact(gpa, io, root_dir, amb, tags, &cname_buf) catch |e|
        return amendLogFail(streams, e);

    // 7. Success (B-amend-1/16): the one confirmation line to stdout, the full
    //    control-artifact hash as a fixed-position token (mirrors commit's
    //    verb-prefixed line). Every diagnostic already went to stderr.
    streams.out.print("amend {s}\n", .{control_name}) catch {};
    return .ok;
}

/// Renders `zit amend: out of memory` and returns `.failure`.
fn amendOom(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit amend: out of memory\n") catch {};
    return .failure;
}

/// Renders a B-amend log open/put/commit failure. Exhaustive over the widest
/// closed set (`logstore.OpenError`); the narrower `PutError`/`CommitError`
/// coerce into it, so one mapper serves all three.
fn amendLogFail(s: cli.Streams, err: logstore.OpenError) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit amend: out of memory\n") catch {},
        error.Storage => s.err.writeAll("zit amend: cannot write the amendment: input/output error\n") catch {},
        error.Corrupt => s.err.writeAll("zit amend: the repository is corrupt\n") catch {},
    }
    return .failure;
}

/// The external type name of the stored artifact named `name` when it is NOT a
/// check-in (B-amend-10), or null when `name` names no stored artifact, is
/// unparseable, or IS a check-in manifest (in which case the not-found diagnostic
/// stands — `resolve` already ruled it out as a crosslinked check-in). Reads the
/// raw artifact through the repo's content channel and classifies it; the
/// returned name is a static string, valid after the parse is freed.
fn amendArtifactType(gpa: std.mem.Allocator, repo: *Repository, name: []const u8) ?[]const u8 {
    const bytes = (repo.blob(gpa, name) catch return null) orelse return null;
    defer gpa.free(bytes);
    var m = artifact.parse(gpa, bytes) catch return null;
    defer m.deinit();
    if (m.kind == .manifest) return null; // a manifest IS a check-in; let not-found stand
    return m.kind.externalName();
}

const top_usage =
    \\zit — a Fossil version-control system in Zig
    \\
    \\usage: zit <command> [args]
    \\
    \\commands:
    \\  init       create an empty zit repository
    \\  add        mark files to include in your next check-in
    \\  rm         stop tracking files (undo add)
    \\  mv         rename a tracked file
    \\  status     show the working checkout state
    \\  stat       report the repository store's size and artifact census
    \\  diff       compare managed files with the current check-in
    \\  extras     list files in the checkout that zit isn't tracking
    \\  clean      delete files in the checkout that zit isn't tracking
    \\  addremove  track new files and forget deleted ones in one pass
    \\  commit     record a check-in from your tracked files
    \\  log        show a check-in and its reachable parents
    \\  open       fill a freshly cloned directory with its files
    \\  update     materialize a check-in in the working tree
    \\  merge      merge another check-in into the working tree
    \\  revert     restore managed files to their checked-in contents
    \\  undo       undo the last update or revert
    \\  redo       reapply an undone change
    \\  leaves     list the open leaves of the check-in DAG
    \\  timeline   list every check-in, most recent first
    \\  branch     list the repository's branches
    \\  tag        list the tags in use, or give a check-in a name
    \\  amend      attach display overrides to a check-in
    \\  info       resolve a name to a check-in and describe it
    \\  ls         list the files of a check-in
    \\  cat        emit a file's contents at a check-in
    \\  artifact   print or describe a raw artifact by its hash
    \\  annotate   show which check-in introduced each line of a file
    \\  bisect     binary-search the check-in DAG for a good/bad boundary
    \\  serve      serve this repository over HTTP for sync
    \\  clone      copy a repository from a URL into a new directory
    \\  pull       fetch new artifacts from a URL into this repository
    \\  push       send this repository's artifacts to a URL
    \\  sync       reconcile with a peer in both directions
    \\  remote     show, set, or clear the default sync remote
    \\  pack       repack the repository store into a compact new generation
    \\  version    print the version
    \\  help       show this help
    \\
;

pub const log_help =
    \\usage: zit log [-n N] [-R <path>] CHECKIN [PATH]
    \\
    \\Show CHECKIN followed by every reachable parent check-in in depth-first
    \\P-card order. CHECKIN must be an exact 40- or 64-character lowercase
    \\hexadecimal artifact ID. Each check-in is shown once; a referenced parent
    \\missing from this repository is shown once as a phantom.
    \\
    \\With PATH, show only the reachable check-ins that change PATH — where
    \\PATH's effective content differs from its primary parent's, including
    \\where PATH is added or deleted. PATH is an exact repo-relative path, not
    \\a pattern; a path that never changed yields no output.
    \\
    \\options:
    \\  -n, --limit N show only the N most recent entries; 0 means all
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help    show this help and exit
    \\
;
pub const open_help =
    \\usage: zit open [--manifest[=r,u,t]] [-h|--help]
    \\
    \\Materialize the tip of this repository's main branch in the working tree.
    \\This is the second half of 'zit clone URL DIR': clone builds DIR and its
    \\'.zit', open fills DIR with the files of the newest check-in. Run it from
    \\inside the checkout directory.
    \\
    \\A working tree that is already open at a check-in is left untouched; use
    \\'zit update' to move an open tree to a different check-in. A repository
    \\with no check-in yet is already in its correct (empty) state, which open
    \\reports and leaves alone.
    \\
    \\--manifest asks this checkout for the files some build systems read to
    \\stamp a version into their output: 'manifest' (the check-in artifact, r),
    \\'manifest.uuid' (its hash, u) and 'manifest.tags' (its symbolic tags, t).
    \\The bare flag means 'ru'. The choice is remembered, so every later
    \\'zit update' rewrites the files for the check-in it moves to. Without the
    \\flag none are written, and a file of one of those names that the check-in
    \\itself tracks is never replaced.
    \\
    \\options:
    \\  --manifest[=r,u,t]  write manifest, manifest.uuid, manifest.tags
    \\  -h, --help          show this help and exit
    \\
;

const update_help =
    \\usage: zit update CHECKIN
    \\
    \\Materialize CHECKIN in the working tree. CHECKIN resolves like 'zit info'
    \\— a full or abbreviated artifact ID, a branch, or a tag.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;

const merge_help =
    \\usage: zit merge NAME
    \\       zit merge --cherrypick NAME
    \\       zit merge --backout NAME
    \\
    \\Merge the check-in NAME into the working tree with a three-way merge and
    \\record it as a pending merge parent. NAME resolves like 'zit info' — a full
    \\or abbreviated artifact ID, a branch, or a tag. This does not create a
    \\check-in; run 'zit commit' to record the merge. Conflicts are written into
    \\the working files with conflict markers and listed on stderr — resolve them
    \\and commit, or run 'zit undo' to abandon the merge.
    \\
    \\--cherrypick and --backout are special merges that pick an alternate
    \\baseline instead of the common ancestor: --cherrypick applies only NAME's
    \\own change onto the working tree, --backout reverses it. 'zit commit' then
    \\records the operation as a cherry-pick/backout, not as a merge parent.
    \\
    \\options:
    \\  -h, --help          show this help and exit
    \\  --cherrypick NAME   apply only NAME's own change onto the working tree
    \\  --backout NAME      reverse NAME's change on the working tree
    \\
;

const bisect_help =
    \\usage: zit bisect bad NAME | good NAME | next | status | reset
    \\
    \\Binary-search the check-in DAG for the check-in that introduced a defect.
    \\Mark a known-bad and a known-good check-in; zit narrows the candidate span
    \\to the ancestors of the bad check-in that are not ancestors of any good one
    \\and moves the working tree to the midpoint for you to test. Repeat until one
    \\check-in remains — the first bad check-in.
    \\
    \\subcommands:
    \\  bad NAME    mark NAME as containing the defect
    \\  good NAME   mark NAME as free of the defect
    \\  next        move to (or re-announce) the current probe check-in
    \\  status      show the marks, the current probe, and the remaining count
    \\  reset       end the bisection and restore the starting check-in
    \\
    \\NAME resolves like 'zit info' — a full or abbreviated artifact ID, a branch,
    \\or a tag. Marking moves the working tree through the update engine, so a move
    \\is refused over a dirty working tree and is recoverable with 'zit undo'. The
    \\bisection state lives in .zit-bisect and never enters the repository.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;

pub const annotate_help =
    \\usage: zit annotate PATH
    \\
    \\Show, for each line of PATH at the current check-out, the check-in that
    \\introduced that line and when. PATH is an exact repo-relative path to a
    \\tracked file; each output line is the introducing check-in's 10-character
    \\artifact-ID prefix, the ISO date it was recorded (UTC), then the file line.
    \\
    \\Provenance is computed over the file's whole version history: a line is
    \\attributed to the oldest check-in that carries it. A line that arrived from
    \\a merged branch is credited to its origin on that branch, never to the merge
    \\check-in itself. Only committed content is annotated — uncommitted edits in
    \\the working file are not shown.
    \\
    \\options:
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the annotation was written
    \\  1  PATH is not tracked at the current check-out, its content is binary,
    \\     or this is not a zit repository
    \\  2  usage error (a missing PATH, an unknown option, or a second positional)
    \\
;

const revert_help =
    \\usage: zit revert [PATH...]
    \\
    \\Restore managed files to their contents at the current check-in, discarding
    \\working-tree edits. With no PATH, every managed file is reverted; name one
    \\or more paths to revert just those.
    \\
    \\revert changes file contents only — it never changes which files are
    \\tracked. A managed file that the current check-in does not contain (added
    \\but never committed, or deleted at this check-in) is reported and left
    \\alone, never recreated.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the named files were reverted (or had nothing to restore)
    \\  1  a path is not tracked, a file could not be written, the checkout is
    \\     unborn, or this is not a zit repository
    \\  2  usage error (an unknown option)
    \\
;

const undo_help =
    \\usage: zit undo [-h|--help]
    \\
    \\Undo the last working-file change made by 'zit update' or 'zit revert',
    \\restoring every affected file and the checkout record to their state before
    \\that change. Single level: only the most recent change can be undone; a second
    \\'zit undo' in a row has nothing left to undo.
    \\
    \\Use 'zit redo' to reapply a change you just undid. A new update or revert
    \\clears the redo slot.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the change was undone
    \\  1  nothing to undo, the journal is damaged, or this is not a zit repository
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

const redo_help =
    \\usage: zit redo [-h|--help]
    \\
    \\Reapply the change you just undid with 'zit undo', restoring every affected
    \\file and the checkout record to their state after that change. Single level:
    \\redo is available only immediately after an undo; a new update or revert
    \\clears it.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the change was reapplied
    \\  1  nothing to redo, the journal is damaged, or this is not a zit repository
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

pub const pack_help =
    \\usage: zit pack [-h|--help]
    \\
    \\Repack this repository's store into a compact new generation, re-encoding
    \\full-form artifacts as deltas against their lineage (a check-in against its
    \\parent, a file against the same path in the parent check-in) and dropping
    \\superseded config records. Every artifact's content and name are preserved
    \\exactly; the on-disk layout is the only thing that changes.
    \\
    \\pack streams the whole store, verifying every frame's checksum and that each
    \\reconstructed artifact still hashes to its name — so it doubles as a
    \\whole-store integrity check. The packed log is written to a temporary file
    \\and swapped into place atomically: a crash before the swap leaves the
    \\original untouched. It transiently needs room for both the old and new store.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;

pub const leaves_help =
    \\usage: zit leaves [--all] [--no-cache] [-h|--help]
    \\
    \\List the open leaves of the check-in DAG — check-ins with no child on the
    \\same branch that carry no active closed tag. Each line shows the check-in's
    \\full artifact ID and its branch. Leaves are ordered most-recent first; the
    \\leaf matching the current checkout is marked with a leading "*".
    \\
    \\options:
    \\      --all       also list closed leaves, each marked "(closed)"
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

pub const timeline_help =
    \\usage: zit timeline [-n N] [-R <path>] [-h|--help]
    \\
    \\List every check-in in the repository, most recent first. Each line shows
    \\the check-in's short hash, its ISO timestamp, its branch, and the first
    \\line of its comment. A check-in that joins two or more lines of development
    \\is marked "M". Order is by event time descending, ties broken by artifact
    \\hash, so the listing is byte-identical across runs.
    \\
    \\options:
    \\  -n, --limit N show only the N most recent entries; 0 means all
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help    show this help and exit
    \\
;

pub const branch_help =
    \\usage: zit branch [--no-cache] [-h|--help]
    \\
    \\List the repository's branches, one per line, ordered by name. Branches are
    \\derived from the active branch tags of the check-ins; the branch of the current
    \\checkout is marked with a leading "*". A branch whose most recent check-in is
    \\closed is marked "(closed)".
    \\
    \\options:
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

pub const tag_help =
    \\usage: zit tag list [CHECKIN] [--no-cache]
    \\       zit tag add NAME CHECKIN
    \\
    \\List tags, or give a check-in a name. With no CHECKIN, list prints the tag
    \\names in use across the repository, one per line, sorted. With a CHECKIN,
    \\it prints the tags visible on that check-in and their values.
    \\
    \\add names one check-in: NAME then resolves to it everywhere a check-in
    \\name is accepted. The name stays on that check-in — unlike a branch name,
    \\it is not inherited by the check-ins committed after it.
    \\
    \\  ls          alias for list
    \\
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help  show this help
    \\
;

pub const serve_help =
    \\usage: zit serve [--port N] [-h|--help]
    \\
    \\Serve this repository over HTTP so a peer can sync against it. Answers a
    \\POST to /xfer carrying an application/x-fossil body per the sync protocol,
    \\one request per connection, single-threaded. Binds 127.0.0.1 on port N
    \\(default 8080). Stop it with Ctrl-C.
    \\
    \\options:
    \\      --port N  listen on port N (default 8080)
    \\  -h, --help    show this help and exit
    \\
;

pub const clone_help =
    \\usage: zit clone URL DIR [-h|--help]
    \\
    \\Copy a repository served at URL into a new directory DIR. Creates DIR (and
    \\its `.zit`), opens an HTTP connection to URL, syncs the repository's
    \\artifacts down to convergence, and stores them so DIR is a usable repo.
    \\
    \\URL is the peer's sync endpoint — an http:// or https:// address, used
    \\verbatim (the path is not rewritten). The clone is anonymous: no login.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;
pub const pull_help =
    \\usage: zit pull [URL] [-h|--help]
    \\
    \\Fetch artifacts from the repository served at URL into the current repository.
    \\Opens an HTTP connection to URL, announces what this repository already holds,
    \\requests everything it lacks, and stores the newly received artifacts so this
    \\repository converges toward the peer's content.
    \\
    \\URL is the peer's sync endpoint — an http:// or https:// address, used
    \\verbatim (the path is not rewritten). The pull is anonymous: no login. With
    \\URL omitted the saved remote is used ('zit remote URL' saves one); a repo
    \\with no saved remote and no URL is an error.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;
pub const push_help =
    \\usage: zit push [URL] [--user U [--password P]] [-h|--help]
    \\
    \\Send this repository's artifacts to the repository served at URL. Opens an
    \\HTTP connection to URL, announces what this repository holds, and uploads
    \\every artifact the peer lacks until both sides converge. The peer stores the
    \\uploaded artifacts; nothing on this side changes.
    \\
    \\URL is the peer's sync endpoint — an http:// or https:// address, used
    \\verbatim (the path is not rewritten). With URL omitted the saved remote is
    \\used ('zit remote URL' saves one); a repo with neither is an error.
    \\
    \\Without --user the push is anonymous (no login card). With --user the push
    \\authenticates: the shared secret is derived from the password and the login
    \\card is signed with it. The password comes from --password, else the
    \\ZIT_PASSWORD environment variable, else a no-echo prompt. After a successful
    \\authenticated push the derived secret (never the password) is saved in the
    \\repository at 0600, so a later push with just --user needs no password.
    \\
    \\options:
    \\  --user U        authenticate as login U (sync §6)
    \\  --password P    U's password (prompted without echo if omitted)
    \\  -h, --help      show this help and exit
    \\
;
pub const sync_help =
    \\usage: zit sync [URL] [--user U [--password P]] [-h|--help]
    \\
    \\Reconcile this repository with the one served at URL in BOTH directions in a
    \\single exchange: this side uploads every artifact the peer lacks and receives
    \\every artifact it lacks, until both converge. This is one session, not a pull
    \\followed by a push — sync history transfers both ways and never discards
    \\artifacts (so there is no force-push).
    \\
    \\URL is the peer's sync endpoint — an http:// or https:// address, used
    \\verbatim (the path is not rewritten). With URL omitted the saved remote is
    \\used ('zit remote URL' saves one); a repo with neither is an error.
    \\
    \\Without --user the sync is anonymous. With --user it authenticates for the
    \\upload exactly as 'zit push' does: the shared secret is derived from the
    \\password (from --password, else ZIT_PASSWORD, else a no-echo prompt) and, on
    \\success, saved in the repository at 0600 so a later --user needs no password.
    \\
    \\options:
    \\  --user U        authenticate as login U (sync §6)
    \\  --password P    U's password (prompted without echo if omitted)
    \\  -h, --help      show this help and exit
    \\
;
pub const remote_help =
    \\usage: zit remote [URL | --unset] [-h|--help]
    \\
    \\Show, set, or clear the default sync remote — the peer URL that 'zit sync',
    \\'zit pull', and 'zit push' use when you do not name one. With no argument,
    \\print the saved remote (or 'no remote set'). With URL, save it. With --unset,
    \\clear it.
    \\
    \\There is a single default remote, not a named-remote registry. URL is stored
    \\verbatim and used anonymously — never put a credential in it; authenticate a
    \\push or sync with --user instead.
    \\
    \\options:
    \\      --unset     clear the saved remote
    \\  -h, --help      show this help and exit
    \\
;
pub const info_help =
    \\usage: zit info NAME [--no-cache]
    \\
    \\Resolve NAME to a single check-in and describe it. NAME may be a full
    \\40- or 64-character artifact ID, a unique ID prefix, a branch or tag name,
    \\or one of the reserved forms (tip, rid:, tag:, root:, start:, merge-in:).
    \\Resolution follows recency, not open-leaf status: a name can resolve to a
    \\closed or non-leaf check-in that 'zit leaves' would not list.
    \\
    \\options:
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

const amend_help =
    \\zit amend NAME [--comment TEXT] [--user NAME] [--date ISO] [--branch NAME]
    \\
    \\Attach display overrides to a check-in by minting one control artifact.
    \\History is never rewritten; the original check-in is untouched.
    \\
    \\  --comment TEXT   override the displayed comment
    \\  --user NAME      override the displayed author
    \\  --date ISO       override the displayed date (YYYY-MM-DDTHH:MM:SS)
    \\  --branch NAME    move the check-in (and its descendants) to branch NAME
    \\  -h, --help       show this help
    \\
    \\At least one override flag is required.
    \\
;

pub const ls_help =
    \\usage: zit ls [VERSION] [--no-cache]
    \\
    \\List the files of a check-in, one per line as `<blob-id> <filename>`, in
    \\canonical filename order. VERSION selects the check-in the same way 'zit
    \\info' does — a full 40- or 64-character artifact ID, a unique ID prefix, a
    \\branch or tag name, or a reserved form (tip, rid:, tag:, root:, start:,
    \\merge-in:). With VERSION omitted, the current checkout is listed; an unborn
    \\checkout has nothing to list and is an error.
    \\
    \\The listing is the effective file set: a delta check-in is merged with its
    \\baseline and deleted files are omitted.
    \\
    \\options:
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

pub const cat_help =
    \\usage: zit cat FILE [VERSION] [--no-cache]
    \\
    \\Write the contents of FILE at a check-in to standard output, verbatim — no
    \\trailing newline is added and binary content passes through unchanged. FILE
    \\is a pathname within the check-in; VERSION selects the check-in the same way
    \\'zit info' does — a full 40- or 64-character artifact ID, a unique ID prefix,
    \\a branch or tag name, or a reserved form (tip, rid:, tag:, root:, start:,
    \\merge-in:). With VERSION omitted, the current checkout is used; an unborn
    \\checkout has nothing to read and is an error.
    \\
    \\FILE is resolved against the effective file set: in a delta check-in the
    \\file's own entry wins over the baseline, and a file deleted at this check-in
    \\is reported as not found. The emitted bytes are verified to match the file's
    \\recorded hash.
    \\
    \\options:
    \\      --no-cache  bypass the cache and re-derive from the full log,
    \\                  re-verifying whole-log integrity (the cache is refreshed)
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

pub const artifact_help =
    \\usage: zit artifact HASH [--raw]
    \\
    \\Describe or dump a single stored artifact addressed by its hash. HASH is a full
    \\or abbreviated (>=4 character) lowercase hexadecimal artifact ID, resolved
    \\against every stored artifact — file blobs included. Branch and tag names are
    \\not accepted; use 'zit info' for those.
    \\
    \\Without --raw, print a summary: the full hash, the artifact's size, its type,
    \\and — for a structural artifact — one line per card and whether its Z
    \\self-checksum verifies. A blob reports its size and whether it is binary.
    \\
    \\With --raw, write the artifact's exact stored bytes to standard output,
    \\verbatim — no trailing newline is added and binary content passes through
    \\unchanged. Hashing those bytes reproduces HASH.
    \\
    \\options:
    \\      --raw       write the exact stored bytes instead of a summary
    \\  -R, --repo <path>
    \\                read this repository instead of the one found from the
    \\                current directory; <path> is the directory holding '.zit'
    \\                (or the '.zit' file itself). No working tree is required.
    \\  -h, --help      show this help and exit
    \\
;

pub const diff_help =
    \\usage: zit diff [-h|--help]
    \\
    \\Compare the managed working-tree files with the current check-in. Output is
    \\metadata only, sorted by pathname: A for additions, M for content or
    \\executable-mode changes, and D for files removed from management or the
    \\working tree.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;

/// Verbatim B-init-11 help text. Model-honest wording ("check-in", "trunk",
/// "unborn", "root check-in", "SHA3-256 by default"). Ends in exactly one
/// newline. The e2e suite verifies stdout equals an independent transcription
/// of the contract, so drift here is caught.
const init_help =
    \\usage: zit init [-q|--quiet] [--] [directory]
    \\
    \\Create an empty zit repository in <directory> (default: the current
    \\directory). Writes two files there:
    \\
    \\  .zit            the repository — a single, self-contained content log
    \\  .zit-checkout   the working-state record (branch trunk, no check-in yet)
    \\
    \\The new repository has no check-ins: the default branch 'trunk' is unborn
    \\until your first `zit commit`, which records the root check-in. Artifacts
    \\are named with SHA3-256 by default.
    \\
    \\If <directory> does not exist it is created.
    \\
    \\options:
    \\  -q, --quiet   do not print the confirmation line
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  repository created
    \\  1  a repository already exists, or the path could not be initialized
    \\  2  usage error (unknown option or extra argument)
    \\
;

/// Verbatim B-add-13 help text (contracts/add.md §Help). Model-honest wording
/// ("managed", "no staging area", "check-in", "trunk", "unborn", "zit rm").
/// Ends in exactly one newline. The e2e suite compares stdout against an
/// independent transcription of this block, so drift is caught.
pub const add_help =
    \\usage: zit add [-n|--dry-run] [-q|--quiet] [--] <path>...
    \\
    \\Mark one or more working-tree files as managed, so they are included in
    \\your next check-in. zit has no staging area: `add` records only *which*
    \\files to track — their contents are read from the working tree when you
    \\run `zit commit`, not now. Re-adding an already-tracked file does nothing.
    \\
    \\Files stay tracked until `zit rm` forgets them. You can add files before
    \\the first check-in (the default branch 'trunk' is unborn until then).
    \\
    \\Naming a directory adds every untracked file beneath it, recursively;
    \\`zit add .` adds the whole tree. zit's control files are never added.
    \\
    \\options:
    \\  -n, --dry-run   show what would be added; change nothing
    \\  -q, --quiet     do not print the added files
    \\  -h, --help      show this help and exit
    \\
    \\exit status:
    \\  0  all named files are now tracked (or already were)
    \\  1  a file could not be added (missing, not a regular file, outside the
    \\     repo), or this is not a zit repository
    \\  2  usage error (no files given, or an unknown option)
    \\
;

/// Verbatim B-rm-13 help text (contracts/rm.md §Help). Model-honest wording
/// ("tracking", "managed set", "no staging area", "check-in", and the explicit
/// contrast with git's delete-by-default). Ends in exactly one newline. The e2e
/// suite compares stdout against an independent transcription of this block.
pub const rm_help =
    \\usage: zit rm [-n|--dry-run] [--hard] [-q|--quiet] [--] <path>...
    \\
    \\Stop tracking one or more files: remove their paths from the managed set,
    \\so your next check-in records their deletion. zit has no staging area, so
    \\this takes effect when you run `zit commit`, not now.
    \\
    \\By default your working copy is left on disk untouched -- `rm` only forgets
    \\the file. Pass --hard to also delete the file from disk. (git deletes by
    \\default; zit keeps your file unless you ask for --hard.)
    \\
    \\Removing a path that is not tracked is an error. Naming a directory forgets
    \\every tracked file beneath it, whether or not the directory still exists.
    \\
    \\options:
    \\  -n, --dry-run   show what would be removed; change nothing
    \\      --hard      also delete the working-tree file from disk
    \\  -q, --quiet     do not print the removed files
    \\  -h, --help      show this help and exit
    \\
    \\exit status:
    \\  0  all named files are no longer tracked (and, with --hard, deleted)
    \\  1  a file could not be removed (not tracked, outside the repo, or --hard
    \\     could not delete it), or this is not a zit repository
    \\  2  usage error (no files given, or an unknown option)
    \\
;

/// Verbatim help text (contracts/mv.md §Help). Model-honest wording ("tracked",
/// "check-in", "recorded", the explicit no-clobber / no-force / no-undo posture).
/// Ends in exactly one newline. The e2e suite compares stdout against an
/// independent transcription of this block, so drift is caught.
pub const mv_help =
    \\usage: zit mv OLD NEW
    \\
    \\Rename a tracked file: move the working file from OLD to NEW on disk, swap
    \\the tracked-name entry, and record the rename so your next `zit commit`
    \\records NEW with OLD as its former name.
    \\
    \\OLD must be tracked and present in the working tree; NEW must not already be
    \\tracked or exist on disk. Renaming never overwrites -- a collision is
    \\refused, and there is no --force. mv takes exactly two operands; it is never
    \\a glob or multi-file move, and it does not rename directories.
    \\
    \\mv is not undone by `zit undo`; to reverse a rename, run `zit mv NEW OLD`.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the file was renamed
    \\  1  OLD is not tracked or missing, NEW is already tracked or on disk, or
    \\     this is not a zit repository
    \\  2  usage error (wrong operand count, or an unknown option)
    \\
;

/// Verbatim `zit stat` help text. It states the one thing a reader of these
/// numbers has to know — that `content-bytes` and `store-bytes` are different
/// measurements and neither substitutes for the other — because the field list
/// alone would let someone read the smaller number as "the file, minus some
/// slack". Ends in exactly one newline. The e2e suite compares stdout against
/// an independent transcription of this block, so drift is caught.
pub const stat_help =
    \\usage: zit stat [--artifacts] [--type=full|delta] [-h|--help]
    \\
    \\Report what the repository store actually holds. Every number is read
    \\from the frames in `.zit` — nothing is estimated, and nothing is derived
    \\from the file's size.
    \\
    \\Output is one 'field value' line per fact, so it reads by machine:
    \\
    \\  store-bytes           the `.zit` file itself, in bytes
    \\  header-bytes          the store header
    \\  content-bytes         artifact payload bytes, summed frame by frame
    \\  frame-overhead-bytes  frame headers and 8-byte padding for those frames
    \\  config-bytes          the repository's config record
    \\  artifacts             stored artifacts (the config record is not one)
    \\  full-form             artifacts stored whole
    \\  deltas                artifacts stored against a base
    \\
    \\content-bytes and store-bytes are different measurements and must not be
    \\substituted for one another: the store also carries the header, a header
    \\per frame, and padding, so it is always the larger number. The four byte
    \\fields plus header-bytes account for the file exactly.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\  --artifacts   list the stored artifact hashes instead, one per line,
    \\                in ascending hash order
    \\  --type=KIND   with --artifacts, list only 'full' or 'delta' artifacts
    \\
    \\exit status:
    \\  0  the report was written
    \\  1  this is not a zit repository, or `.zit` could not be read
    \\  2  usage error (an unknown option, a repeated --type, a --type without
    \\     --artifacts, or an unexpected argument)
    \\
;

/// Verbatim B-status-16 help text (contracts/status.md §Help). Model-honest
/// wording ("check-in", "trunk", "unborn", "tracked", "artifact hash" — never
/// git's "index"/"staged"/"HEAD"), and it teaches the slice-1 scope boundary
/// (DX D2) rather than hiding it. Ends in exactly one newline. The e2e suite
/// compares stdout against an independent transcription of this block, so drift
/// is caught.
pub const status_help =
    \\usage: zit status [-h|--help]
    \\
    \\Show the state of the working copy: the current branch, the current
    \\check-in (if any), and the state of your tracked files.
    \\
    \\zit has no staging area. `status` reports the files you marked with
    \\`zit add` and how each one stands in the working tree:
    \\
    \\  added <path>     tracked and new — it will enter your next check-in
    \\  edited <path>    tracked, and its bytes or mode differ from the check-in
    \\  missing <path>   tracked, but not present in the working tree
    \\
    \\A tracked file whose contents match the current check-in is not listed.
    \\
    \\Until your first `zit commit` the branch 'trunk' is unborn: there is no
    \\check-in yet, so every tracked file is reported as 'added' (it will form
    \\the root check-in). The current check-in, once one exists, is shown as its
    \\full artifact hash.
    \\
    \\Two things `status` does not report, because it walks only your tracked
    \\files: a file deleted from the check-in but no longer tracked (`zit diff`
    \\lists it) and untracked "extra" files (`zit extras` lists them).
    \\
    \\options:
    \\  -h, --help   show this help and exit
    \\
    \\exit status:
    \\  0  the working-copy state was reported (with or without changes)
    \\  1  this is not a zit repository, or its state could not be read
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

/// Verbatim `zit extras` help (contracts/extras.md §Help). The house
/// `parseNoPositionalArgs`-verb help shape (status/diff/timeline). Ends in
/// exactly one newline; the e2e suite compares stdout against an independent
/// transcription, so any drift is caught.
pub const extras_help =
    \\usage: zit extras [-h|--help]
    \\
    \\List every file in the checkout that zit is not tracking — each on-disk file
    \\under the checkout root that is neither a tracked file nor a zit control file.
    \\Paths are shown relative to the checkout root, one per line, sorted. Files in
    \\subdirectories are included; directories themselves are not. Symlinks are
    \\listed but never followed. With nothing untracked, the output is empty.
    \\
    \\options:
    \\  -h, --help    show this help and exit
    \\
;

/// Verbatim `zit clean` help (contracts/clean.md §Help). Names the destructive,
/// non-undoable, non-interactive posture up front and the `--dry-run`-wins
/// precedence. Ends in exactly one newline; the e2e suite compares stdout
/// against an independent transcription, so any drift is caught.
pub const clean_help =
    \\usage: zit clean [--dry-run] [--force]
    \\
    \\Delete every file in the checkout that zit is not tracking — the same set
    \\`zit extras` lists. This is destructive and cannot be undone: `zit undo` does
    \\not recover a clean.
    \\
    \\By default clean refuses and deletes nothing: it reports how many untracked
    \\files would be deleted and stops. Pass --force to delete them, or --dry-run to
    \\preview the exact list first. clean never prompts.
    \\
    \\Tracked files and zit's control files are never touched. Only files are
    \\deleted; directories left empty are not pruned.
    \\
    \\options:
    \\  --dry-run     list what would be deleted, one path per line; delete nothing
    \\  --force       delete the untracked files
    \\  -h, --help    show this help and exit
    \\
    \\If both --dry-run and --force are given, --dry-run wins and nothing is deleted.
    \\
    \\exit status:
    \\  0  nothing to delete, a --dry-run preview, or every file deleted
    \\  1  refused (no --force), a file could not be deleted, or not a zit repository
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

/// Verbatim `zit addremove` help (contracts/addremove.md §Help). Names the
/// track-new + forget-deleted model, the tracked-only (never file contents)
/// posture, and the ADDED/REMOVED report shape. Ends in exactly one newline;
/// the e2e suite compares stdout against an independent transcription, so any
/// drift is caught.
pub const addremove_help =
    \\usage: zit addremove [--dry-run]
    \\
    \\Reconcile the tracked set with the working tree in one pass: mark every
    \\untracked file to include in your next check-in, and stop tracking every
    \\file you deleted from disk. This is the set `zit extras` lists, added, plus
    \\the tracked files now missing, removed — fossil and hg spell it `addremove`;
    \\git spells it `add -A`.
    \\
    \\addremove changes only what zit tracks; it never edits, creates, or deletes
    \\a working file, and the next `zit commit` records the result. Each action is
    \\reported, sorted and relative to the checkout root:
    \\
    \\  ADDED <path>     a newly tracked file
    \\  REMOVED <path>   a tracked file no longer on disk
    \\
    \\A tracked file that is merely modified is left alone (content does not affect
    \\membership), and zit's control files are never tracked. With nothing to do,
    \\the output is empty.
    \\
    \\options:
    \\  --dry-run     report what would change, one action per line; change nothing
    \\  -h, --help    show this help and exit
    \\
    \\exit status:
    \\  0  the tracked set was reconciled (with or without changes), or a --dry-run preview
    \\  1  a path could not be tracked, or this is not a zit repository
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

/// Verbatim B-commit-20 help text (contracts/commit.md §Help). Model-honest
/// wording ("check-in", "root check-in", "trunk", "artifact hash", "tracked",
/// "no staging area", "immutable", "no amend/--force" — never git's
/// "commit"/"index"/"staged"/"HEAD"), and it teaches the slice-1 scope boundary
/// (DX D2). Ends in exactly one newline. The e2e suite compares stdout against
/// an independent transcription of this block, so drift is caught.
const commit_help =
    \\usage: zit commit -m <message> [--user <login>] [--branch <name>] [--close]
    \\                  [-q|--quiet] [--] [<path>...]
    \\
    \\Record a check-in: save the current contents of your tracked files as a
    \\new, permanent point in history on the current branch.
    \\
    \\zit has no staging area. `commit` reads each tracked file straight from
    \\the working tree right now — there is nothing to stage first. With no
    \\paths, every tracked file is captured; name one or more paths to commit
    \\just those (the rest of the tree is carried forward unchanged).
    \\
    \\The first commit in a new repository creates the root check-in and starts
    \\the default branch 'trunk'. Each check-in is named by its full artifact
    \\hash (SHA3-256).
    \\
    \\--branch <name> starts a new branch at this check-in: the check-in moves
    \\onto <name> and later commits inherit it. <name> must not already name an
    \\open branch, and there must be a parent to fork from. --close marks this
    \\check-in a closed leaf, so it no longer shows as an open head of its branch.
    \\
    \\History is immutable: a check-in is never rewritten. There is no amend and
    \\no --force; to undo a file, change it and commit again. To stop tracking a
    \\file (and record its deletion), use `zit rm` then commit.
    \\
    \\A check-in message is required (-m). Only regular files are captured.
    \\
    \\options:
    \\  -m, --message <message>   the check-in comment (required)
    \\      --user <login>        author to record (default: $USER)
    \\      --branch <name>       start a new branch at this check-in
    \\      --close               mark this check-in a closed leaf
    \\  -q, --quiet               do not print the check-in line
    \\  -h, --help                show this help and exit
    \\
    \\exit status:
    \\  0  the check-in was created
    \\  1  nothing to commit, a tracked file is missing, an empty message, an
    \\     existing branch name, or this is not a zit repository
    \\  2  usage error (no message, or an unknown option)
    \\
;

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("cli.zig");
    _ = @import("transport.zig");
    _ = @import("serve.zig");
    _ = @import("sync_driver.zig");
    _ = @import("sync_driver_test.zig");
    // The pure three-way merge engine behind `zit merge` (contracts/merge.md).
    // It imports only std, so its inline tests ride the CLI test binary here
    // (no build.zig change) exactly as `extras`/`undo` ride their importers.
    _ = @import("merge3.zig");
    // The pure per-line provenance engine behind `zit annotate`
    // (contracts/annotate.md). Imports only std + merge3, so its inline tests
    // ride the CLI test binary here the same way.
    _ = @import("annotate.zig");
    _ = @import("cmd/sync.zig");
    _ = @import("cmd/tracking.zig");
    _ = @import("cmd/history.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, 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-managed 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, 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, 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: [2048]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(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: [2048]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(status_help, 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), @intFromEnum(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 D2 B-init-12: 'checkout' points at 'zit update', exit 2 stderr-only" {
    try expectReflex("checkout", "zit update");
}
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" {
    try expectReflex("stash", "not implemented");
}
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: -m <message>\ntry '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" {
    const r = RunCapture.run_verb("ini");
    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 'ini'") != 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("updat");
    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 'updat'") != 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);
    try std.testing.expect(std.mem.indexOf(u8, r.err, "commands:") != null);
}

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

/// Captures a mapper's stderr into a fixed buffer and returns (exit, bytes).
fn commitMapCapture(comptime run_map: anytype, args: anytype) struct { code: cli.Exit, err: []const u8 } {
    const S = struct {
        var err_buf: [256]u8 = undefined;
    };
    var w = Io.Writer.fixed(&S.err_buf);
    var sink: [1]u8 = undefined;
    var wnull = Io.Writer.fixed(&sink);
    const s: cli.Streams = .{ .out = &wnull, .err = &w };
    const code = @call(.auto, run_map, .{s} ++ args);
    return .{ .code = code, .err = w.buffered() };
}

test "commit B-commit-15: checkout-read errors map to the contract messages, exit 1" {
    const Case = struct { err: checkout.CheckoutError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.Corrupt, .want = "zit commit: cannot read checkout state: .zit-checkout is corrupt\n" },
        .{ .err = error.Storage, .want = "zit commit: cannot read checkout state: input/output error\n" },
    };
    for (cases) |c| {
        const r = commitMapCapture(checkoutFail, .{ "commit", c.err });
        try std.testing.expectEqual(cli.Exit.failure, r.code);
        try std.testing.expectEqualStrings(c.want, r.err);
    }
}

test "commit B-commit-15: managed-read errors map to the contract messages, exit 1" {
    const Case = struct { err: managed.ManagedError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.Corrupt, .want = "zit commit: cannot read tracked files: .zit-managed is corrupt\n" },
        .{ .err = error.Storage, .want = "zit commit: cannot read tracked files: input/output error\n" },
        .{ .err = error.TooLong, .want = "zit commit: cannot read tracked files: a tracked path is too long\n" },
        .{ .err = error.TooMany, .want = "zit commit: cannot read tracked files: too many tracked files\n" },
        .{ .err = error.OutOfMemory, .want = "zit commit: out of memory\n" },
    };
    for (cases) |c| {
        const r = commitMapCapture(managedFail, .{ "commit", c.err });
        try std.testing.expectEqual(cli.Exit.failure, r.code);
        try std.testing.expectEqualStrings(c.want, r.err);
    }
}

test "commit B-commit-15: log open/put/commit errors map to the contract messages, exit 1" {
    const Case = struct { err: logstore.OpenError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.OutOfMemory, .want = "zit commit: out of memory\n" },
        .{ .err = error.Storage, .want = "zit commit: cannot write the check-in: input/output error\n" },
        .{ .err = error.Corrupt, .want = "zit commit: the repository is corrupt\n" },
    };
    for (cases) |c| {
        const r = commitMapCapture(commitLogFail, .{c.err});
        try std.testing.expectEqual(cli.Exit.failure, r.code);
        try std.testing.expectEqualStrings(c.want, r.err);
    }
}

test "commit B-commit-15: parent-content errors map to the contract messages, exit 1" {
    const Case = struct { err: logstore.ContentError, want: []const u8 };
    const cases = [_]Case{
        .{ .err = error.OutOfMemory, .want = "zit commit: out of memory\n" },
        .{ .err = error.Storage, .want = "zit commit: cannot write the check-in: input/output error\n" },
        .{ .err = error.Corrupt, .want = "zit commit: the parent check-in is corrupt\n" },
    };
    for (cases) |c| {
        const r = commitMapCapture(commitContentFail, .{c.err});
        try std.testing.expectEqual(cli.Exit.failure, r.code);
        try std.testing.expectEqualStrings(c.want, r.err);
    }
}

test "commit B-commit-10/-11/-15: the single-message diagnostics render exactly, exit 1" {
    try std.testing.expectEqualStrings(
        "zit commit: cannot read checkout state: .zit-checkout is missing\n",
        commitMapCapture(commitCheckoutMissing, .{}).err,
    );
    try std.testing.expectEqualStrings(
        "zit commit: the parent check-in is corrupt\n",
        commitMapCapture(commitParentCorrupt, .{}).err,
    );
    try std.testing.expectEqualStrings(
        "zit commit: the check-in was recorded but the working state could not be updated: input/output error\n",
        commitMapCapture(commitCheckoutWriteFail, .{}).err,
    );
    try std.testing.expectEqualStrings("zit commit: out of memory\n", commitMapCapture(commitOom, .{}).err);
    try std.testing.expectEqualStrings(
        "zit commit: cannot commit 'a.txt': missing from the working tree (use 'zit rm' to stop tracking it)\n",
        commitMapCapture(commitMissing, .{"a.txt"}).err,
    );
    try std.testing.expectEqualStrings(
        "zit commit: cannot commit 'link': not a regular file\n",
        commitMapCapture(commitNotRegular, .{ "link", false }).err,
    );
    // F-B3: a tracked symlink is the one non-regular kind with a stated
    // recovery, because a pre-fix `add .` is how it got tracked at all.
    try std.testing.expectEqualStrings(
        "zit commit: cannot commit 'link': symlink (not versioned in 0.1.0); run 'zit rm link' to stop tracking it\n",
        commitMapCapture(commitNotRegular, .{ "link", true }).err,
    );
    try std.testing.expectEqualStrings(
        "zit commit: cannot commit 'x': input/output error\n",
        commitMapCapture(commitCaptureIo, .{"x"}).err,
    );
    try std.testing.expectEqualStrings(
        "zit commit: 'new.txt' is not tracked (use 'zit add' first)\n",
        commitMapCapture(commitNotTracked, .{"new.txt"}).err,
    );
}

test "update: ApplyError maps to the contract messages and exit 1, exhaustively over all 23 variants" {
    const target_id = "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.BaselineIsDelta,
            .want = "zit update: check-in '" ++ target_id ++ "' baseline is not fully resolvable\n",
        },
        .{ .err = error.StateRecordInvalid, .want = "zit update: cannot read repository: repository is corrupt\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, updateApplyFail(s, target_id, c.err));
        try std.testing.expectEqualStrings(c.want, w.buffered());
    }
}

test "tracked file size limit admits its boundary" {
    const limit: u64 = max_tracked_file_bytes;
    try std.testing.expect(trackedFileSizeAllowed(limit - 1));
    try std.testing.expect(trackedFileSizeAllowed(limit));
    try std.testing.expect(!trackedFileSizeAllowed(limit + 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);
    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"),
    );
}

// ===========================================================================
// `zit pack` — repack/GC tests. Storage on-disk layout is unspecified by the
// RFCs, so the oracle is the store's OWN semantics: every artifact's content
// and name survive a repack byte-for-byte, the set is preserved (no drop), the
// §7.7 name↔content invariant is re-checked before every write, the packed
// bytes are a deterministic function of the source content (idempotent), and a
// crash before the atomic rename leaves the original store untouched. Stores
// are built as FULL frames (the migration shape pack exists to compact),
// through the real `LogStore`/`artifact` — never seeded from fossil.
// ===========================================================================

/// Store `content` as a FULL raw frame and return its 64-hex artifact name.
pub fn packSeedBlob(log: *logstore.LogStore, content: []const u8) ![64]u8 {
    var digest: [digest_len]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(content, &digest, .{});
    _ = try log.put(&digest, content);
    var name: [64]u8 = undefined;
    _ = zit.artifact.artifactName(.sha3_256, content, &name);
    return name;
}

/// Serialize and store (as a FULL frame) a one-file check-in manifest snapshotting
/// `file_name` → `blob_name`, optionally descended from `parent_name`. Writes the
/// manifest's own 64-hex name into `name_out`. Root check-ins carry a propagating
/// `branch=trunk` T card; children carry the parent P card and inherit trunk.
pub fn packSeedCheckin(
    gpa: std.mem.Allocator,
    log: *logstore.LogStore,
    ts: []const u8,
    parent_name: ?[]const u8,
    file_name: []const u8,
    blob_name: []const u8,
    name_out: *[64]u8,
) !void {
    var pbuf: [1]zit.artifact.PCard = undefined;
    var p_slice: []const zit.artifact.PCard = &.{};
    if (parent_name) |pn| {
        pbuf[0] = .{ .parents = pn, .count = 1 };
        p_slice = pbuf[0..1];
    }
    const fcards = [_]zit.artifact.FCard{
        .{ .filename = file_name, .hash = blob_name, .perm = null, .old_name = null, .mode = .regular },
    };
    const root_tags = [_]zit.artifact.TCard{
        .{ .sign = .propagate, .name = "branch", .target = null, .value = "trunk" },
    };
    var m: zit.artifact.Manifest = .{
        .arena_state = std.heap.ArenaAllocator.init(gpa),
        .kind = .manifest,
        .a = null,
        .b = null,
        .c = .{ .comment = "c" },
        .d = .{ .timestamp = ts },
        .e = null,
        .g = null,
        .h = null,
        .i = null,
        .k = null,
        .l = null,
        .n = null,
        .r = null,
        .u = .{ .login = "u" },
        .z = null,
        .w = null,
        .f = &fcards,
        .j = &.{},
        .m = &.{},
        .p = p_slice,
        .q = &.{},
        .t = if (parent_name == null) &root_tags else &.{},
    };
    defer m.deinit();
    const bytes = try zit.artifact.create(&m, gpa);
    defer gpa.free(bytes);
    var digest: [digest_len]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(bytes, &digest, .{});
    _ = try log.put(&digest, bytes);
    _ = zit.artifact.artifactName(.sha3_256, bytes, name_out);
}

/// A large, near-identical evolving file: 128 identical lines plus a per-version
/// trailer, so successive versions delta to a fraction of the full blob (the
/// change is materially < 90%). Caller frees.
pub fn packEvolvingBlob(gpa: std.mem.Allocator, version: u8) ![]u8 {
    var buf: std.ArrayList(u8) = .empty;
    errdefer buf.deinit(gpa);
    var i: usize = 0;
    while (i < 128) : (i += 1) try buf.print(gpa, "line {d} of the tracked file\n", .{i});
    try buf.print(gpa, "trailer version {d}\n", .{version});
    return buf.toOwnedSlice(gpa);
}

/// Open a fresh, empty (header + config-less) writable `.zit` in `dir`.
pub fn packOpenWritable(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fs_out: *storage.FileStorage) !logstore.LogStore {
    const hash_kind: u8 = @intFromEnum(zit.artifact.defaultPolicy(false, false));
    const f = try dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
    fs_out.* = storage.FileStorage.init(io, f, 0);
    return logstore.LogStore.open(gpa, fs_out.storageFile(), hash_kind);
}

/// Reopen an existing `.zit` in `dir` read-only.
pub fn packOpenReadOnly(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fs_out: *storage.FileStorage) !logstore.LogStore {
    const f = try dir.openFile(io, repo_filename, .{});
    const st = try f.stat(io);
    fs_out.* = storage.FileStorage.init(io, f, st.size);
    return logstore.LogStore.openReadOnly(gpa, fs_out.storageFile());
}