Skip to content
zit Artifact [363f898c35]
Login

Artifact [363f898c35]

Artifact 363f898c357da9a9ab2c6dc23e1f4e9f13b4078d7a1a3969b0ec35cddf9d9f4d:


//! `zit commit`: record the working tree's changes as a new check-in, with
//! the before-commit check, signing and the direct-commit policy.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const merge3 = @import("zit").merge3;
const cmd_sync = @import("sync.zig");
const cmd_precedent = @import("precedent.zig");
const cmd_tracking = @import("tracking.zig");
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const Repository = @import("zit").Repository;
const Io = std.Io;
const managed = zit.managed;
const artifact = zit.artifact;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const checkoutFail = diagnostics.checkoutFail;
const managedFail = diagnostics.managedFail;
const repoOpenFail = diagnostics.repoOpenFail;
const hexToDigest = zit.digest_name.hexToDigest;
const trackedFileSizeAllowed = cmd_tracking.trackedFileSizeAllowed;
const executable = cmd_tracking.executable;
const digest_len = zit.digest_name.digest_len;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const max_tracked_file_bytes = cmd_tracking.max_tracked_file_bytes;
const symlink_unversioned = cmd_tracking.symlink_unversioned;
const commit_help = help_pages.commit_help;

// The direct-commit core owns the commit pieces both commit paths need, so the
// working-tree commit below and `commit --stdin` cannot drift apart.
const ContentFault = zit.checkin.ContentFault;
const ContentPolicy = zit.checkin.ContentPolicy;
const PendingBlobs = zit.checkin.PendingBlobs;
const seenDeltaManifest = zit.checkin.seenDeltaManifest;
const setSeenDelta = zit.checkin.setSeenDelta;
const setSeenSubmanifest = zit.checkin.setSeenSubmanifest;

const control_artifact = @import("control_artifact.zig");
const cmd_merge = @import("merge.zig");
const cmd_submanifest = @import("submanifest.zig");
const cmd_update = @import("update.zig");
const mintControlArtifact = control_artifact.mintControlArtifact;
const NamedCheckout = cmd_merge.NamedCheckout;
const replaceSettledCostShape = cmd_submanifest.replaceSettledCostShape;
const submanifestWrite = cmd_submanifest.submanifestWrite;
const projectSetting = cmd_update.projectSetting;
const updateResolveRemote = cmd_update.updateResolveRemote;

/// Whether two lists of tag names are the same, in order.
fn sameNames(a: []const []const u8, b: []const []const u8) bool {
    if (a.len != b.len) return false;
    for (a, b) |x, y| if (!std.mem.eql(u8, x, y)) return false;
    return true;
}

/// 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)
    /// Larger than one artifact frame can hold (`managed.max_tracked_file_bytes`).
    /// Distinct from `io_error` because it is neither a device fault nor
    /// anything the operator can retry: it is a stated limit, and reporting it
    /// as "input/output error" named nothing they had done and suggested a
    /// failure that might not recur.
    too_large: u64,
    /// The file's CONTENT is a class this repository has not said it
    /// accepts: NUL bytes, or CR/LF line endings. Refused rather than warned,
    /// because a warning is a prompt and `commit` has to be answerable
    /// non-interactively; fossil reaches the same place, since its warning
    /// blocks a non-tty commit until `--no-warnings` is passed.
    content_class: ContentFault,
    oom,
};

const ContentNote = struct { path: []const u8, fault: ContentFault, size: u64 };

test "commit: a SHA-1 name a parent carries is never a pending capture" {
    // Captures are SHA3; the R-card pass asks for every parent F card, and
    // a repository with SHA-1 history hands it 20-byte digests.
    var pending: PendingBlobs = .{};
    defer pending.deinit(std.testing.allocator);
    const sha3_digest: [digest_len]u8 = @splat(7);
    const sha1_digest: [20]u8 = @splat(7);
    try pending.add(std.testing.allocator, sha3_digest, try std.testing.allocator.dupe(u8, "x"), null);
    try std.testing.expect(pending.get(&sha1_digest) == null);
    try std.testing.expect(pending.get(&sha3_digest) != null);
}

/// 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,
    pending: *PendingBlobs,
    key: []const u8,
    base: ?logstore.Rid,
    policy: ContentPolicy,
    notes: *std.ArrayList(ContentNote),
    treestat: ?*cmd_tracking.TreeStat,
) 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 .{ .too_large = st.size };
    const is_exec = executable(st.permissions);
    // The stat cache `status` trusts: a file whose size and mtime match what
    // the cache recorded hashes to the recorded name, and when that is the
    // parent's blob the file is unchanged and is not read. An all-files commit
    // read and hashed every managed file to learn that (68588 files, 11 s of
    // CPU on pkgsrc) while `zit changes` answered the same question in 0.3 s.
    if (treestat) |ts| if (base) |b| {
        if (ts.lookup(key, st)) |cached| {
            var hex_buf: [64]u8 = undefined;
            const hex = hexLower(log.hashOf(b), &hex_buf);
            if (std.mem.eql(u8, cached, hex)) {
                const hash = ma.dupe(u8, hex) catch return .oom;
                const filename = ma.dupe(u8, key) catch return .oom;
                return .{ .card = .{
                    .filename = filename,
                    .hash = hash,
                    .perm = if (is_exec) "x" else null,
                    .old_name = null,
                    .mode = if (is_exec) .executable else .regular,
                } };
            }
        }
    };
    const content = root_dir.readFileAlloc(io, key, gpa, .limited(max_tracked_file_bytes)) catch |e|
        return switch (e) {
            error.OutOfMemory => .oom,
            else => .io_error,
        };
    var content_owned = true;
    defer if (content_owned) 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;
    var name: []const u8 = artifact.artifactName(.sha3_256, content, &name_buf);
    // Policy gates what this commit INTRODUCES, not the tree it inherits.
    // An all-files commit re-captures every managed path, so classifying
    // unchanged content would make declaring a glob block every later commit
    // until the whole tree already conformed — adoption would be all-or-
    // nothing in exactly the repositories that most need it. Comparing against
    // the parent's blob for this path makes it incremental: existing files are
    // grandfathered, a new or edited one is not. Checked before the blob is
    // stored, so a refused commit mints nothing.
    //
    // "Unchanged" is decided by the ALGORITHM OF THE PARENT'S NAME, as Fossil
    // decides it. A tree whose F cards carry 40-hex SHA1 names (a repository
    // imported from Fossil's SHA1 era, pkgsrc for one) compared by SHA3 digest
    // can never match, so every file read as edited and one commit re-minted
    // the whole tree under new names -- 68588 blobs the origin had never
    // seen, pushed on the next sync. An unchanged file keeps its SHA1 name;
    // only new content takes the SHA3 name the hash policy prescribes.
    var unchanged = false;
    if (base) |b| {
        const base_hash = log.hashOf(b);
        if (base_hash.len == 20) {
            var sha1: [20]u8 = undefined;
            std.crypto.hash.Sha1.hash(content, &sha1, .{});
            unchanged = std.mem.eql(u8, &sha1, base_hash);
            if (unchanged) name = artifact.artifactName(.sha1, content, &name_buf);
        } else {
            unchanged = std.mem.eql(u8, &digest, base_hash);
        }
    }
    if (!unchanged) {
        if (policy.fault(key, content)) |f| return .{ .content_class = f };
    }
    const hash = ma.dupe(u8, name) catch return .oom;
    const filename = ma.dupe(u8, key) catch return .oom;
    if (treestat) |ts| ts.note(key, st, name);
    if (!unchanged) if (policy.undeclared(content)) |f| {
        notes.append(ma, .{ .path = filename, .fault = f, .size = st.size }) catch return .oom;
    };
    // Content the store lacks waits for the publish step, which stores it
    // delta-encoded against `base` when that is materially smaller (§4.1/
    // §7.2). Naming is over the uncompressed bytes, so storage never changes
    // HASH. Last, because `add` takes the bytes.
    if (!unchanged and log.lookup(&digest) == null) {
        content_owned = false;
        pending.add(gpa, digest, content, base) 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.
    return .{ .card = .{
        .filename = filename,
        .hash = hash,
        .perm = if (is_exec) "x" else null,
        .old_name = null,
        .mode = if (is_exec) .executable else .regular,
    } };
}

/// Lower-case hex of a binary digest, the artifact-name form. `n` is typed:
/// `@min(len, 32)` alone is a u6, and doubling a 32-byte digest's length in
/// it wraps to zero in a release build, returning an empty name that matches
/// nothing -- every SHA3-named file was then read and hashed on each commit.
fn hexLower(bytes: []const u8, out: *[64]u8) []const u8 {
    const digits = "0123456789abcdef";
    const n: usize = @min(bytes.len, 32);
    for (bytes[0..n], 0..) |b, i| {
        out[2 * i] = digits[b >> 4];
        out[2 * i + 1] = digits[b & 15];
    }
    return out[0 .. 2 * n];
}

/// `submanifestEmission`'s full result: the §8.1/§6.3 emission decision this
/// commit builds against, plus `submanifest-auto-retune` read from the exact
/// same config frame — one `readConfig`, two decisions, so §6.4's
/// auto-dispatch gate (`commitSubmanifestAdvice`, below) costs no second read.
const EmissionDecision = struct {
    emission: zit.submanifest.Emission,
    /// The last effective-set shape whose k-cost was settled. Equal shapes need
    /// no advisory scan; missing/different shapes must be analyzed again.
    settled_cost_shape: ?[32]u8,
    /// draft-fossil-submanifests-00 §6.4's `submanifest-auto-retune`: the
    /// durable project-operator act authorizing subsequent automatic re-tunes.
    /// Default false, matching the config field's own default — a repository
    /// that never opted in reads `false` here exactly as it always has.
    auto_retune: bool,
};

/// draft-fossil-submanifests-00 §8.1/§6.3 — the emission decision for THIS
/// commit, read from the repository's own config frame.
///
/// §8.1: "A writer MUST NOT emit an S card unless the repository's
/// enable-submanifests setting -- a project-scope boolean, default false -- is
/// true". §6.3: "A writer MUST take k from the pinned setting, MUST NOT derive a
/// value per commit ... on receiving a value outside 1..12 it MUST fall back to
/// emitting flat manifests rather than substitute a parameter of its own, and
/// SHOULD report the fallback to the operator."
///
/// The decision is folded here rather than inlined at the call site so a config
/// that cannot be read is one decision, not two: a repository with no config
/// frame, or one whose frame will not decode, arrives as a null `config` and is
/// `.off` — the default, the state of every repository predating this draft,
/// and the only safe direction (guessing "enabled" would mint artifacts §8
/// calls unreadable). `submanifestEmission` makes no output;
/// `reportSubmanifestOutOfRange` preserves the §6.3 diagnostic ordering after
/// pre-capture pinned-k validation.
fn submanifestEmission(config: ?*const logstore.Config) EmissionDecision {
    const c = config orelse return .{
        .emission = .off,
        .settled_cost_shape = null,
        .auto_retune = false,
    };
    return .{
        .emission = zit.submanifest.emission(.of(c.*)),
        .settled_cost_shape = c.submanifest_settled_cost_shape,
        .auto_retune = c.submanifest_auto_retune,
    };
}

/// The two LOCAL signing settings, read from the same config frame
/// everything else in the commit path reads. `clearsign` makes every commit
/// signed without `--sign`, matching fossil; `pgp_command` is the stored
/// command line, which `$ZIT_PGP_COMMAND` still overrides. Neither ever
/// crosses the wire: fossil classifies `pgp-command` SENSITIVE (a propagated
/// value would let an origin choose what a cloner executes) and puts
/// `clearsign` in no config group at all.
///
/// An unreadable config yields the defaults — off, and the built-in command —
/// which is the same direction `submanifestEmission` takes for the same
/// reason: guessing "sign" on a frame we could not read would fail the commit,
/// not protect it.
const SigningSettings = struct {
    clearsign: bool = false,
    /// Borrows the caller's arena; empty means the built-in default.
    pgp_command: []const u8 = "",
};

/// The two signing settings, resolved through the SAME precedence
/// `zit settings` reports: environment, then this repository, then the
/// operator's global file, then the built-in default. (Neither is versionable,
/// so no tracked file can reach them — that boundary is enforced inside
/// `settings.resolve`, not here.)
///
/// Routed through the shared resolver rather than reading the frame's fields
/// directly, because the two must never disagree: a `zit settings` that reports
/// `clearsign on` from the global tier while the commit quietly does not sign is
/// a worse failure than having no global tier at all. That bug existed for
/// exactly one commit. `cfg` supplies only the REPOSITORY tier of that chain --
/// the frame the commit already holds, so no second store open is paid here.
///
/// An unresolvable setting yields the default — off, and the built-in command —
/// the same direction `submanifestEmission` takes for the same reason: guessing
/// "sign" on state we could not read would fail the commit, not protect it.
fn signingSettings(
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    amb: cli.Ambient,
    cfg: ?*const logstore.Config,
) SigningSettings {
    const clear = cmd_sync.localSetting(io, arena, root_dir, .{ .environ = amb.environ }, cfg, .clearsign) catch
        return .{};
    const cmd = cmd_sync.localSetting(io, arena, root_dir, .{ .environ = amb.environ }, cfg, .pgp_command) catch
        return .{ .clearsign = zit.settings.parseBool(clear.value) orelse false };
    return .{
        .clearsign = zit.settings.parseBool(clear.value) orelse false,
        // The resolver always answers with the default when no tier spoke, and
        // `clearsignBytes` treats an EMPTY stored command as "use the built-in".
        // Passing the resolved default through is the same thing, one fewer
        // special case.
        .pgp_command = cmd.value,
    };
}

/// draft-fossil-submanifests-00 §6.3's SHOULD-report occurs at the historic
/// post-no-op commit phase, even though its pinned-k decision was read earlier.
fn reportSubmanifestOutOfRange(streams: cli.Streams, decision: zit.submanifest.Emission) void {
    if (decision != .out_of_range) return;
    streams.err.print(
        "zit commit: {s} ({d}; must be {d}..{d}) — emitting a flat manifest. " ++
            "Re-pin with 'zit submanifest retune --k N'.\n",
        .{
            zit.submanifest.out_of_range_report_prefix,
            decision.out_of_range,
            artifact.min_k,
            artifact.max_k,
        },
    ) catch {};
}

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

fn flattenCommitParent(
    gpa: std.mem.Allocator,
    log: *logstore.LogStore,
    manifest: *artifact.Manifest,
) (artifact.TreeError || error{ OutOfMemory, CannotRead, Corrupt, MissingNode })!void {
    var missing = false;
    Repository.flattenTreeFromLogDiagnose(gpa, log, manifest, &missing) catch |err| {
        if (missing) return error.MissingNode;
        return err;
    };
}

fn buildFullTree(
    gpa: std.mem.Allocator,
    entries: []const artifact.FCard,
    k: u4,
) error{OutOfMemory}!?artifact.TreeBuild {
    var built = try artifact.buildTree(gpa, entries, k, .sha3_256);
    if (built.isFlat()) {
        built.deinit();
        return null;
    }
    return built;
}

/// `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.
pub fn runCommit(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb_in: cli.Ambient,
) cli.Exit {
    // `--stdin` is the one mode `-R` is granted for; everything else is the
    // working-tree commit, which parses its own arguments and so reports any
    // malformed ones itself.
    const peek = switch (cli.parseCommitArgs(gpa, verb_args) catch return commitOom(streams)) {
        .ok => |p| p,
        .unknown_option => return runCommitIn(gpa, io, arena, verb_args, streams, amb_in, null),
    };
    defer peek.deinit(gpa);
    var amb = amb_in;
    if (!peek.help) {
        // The override is the commit's clock: both commit paths read their
        // D-card time from `amb` alone.
        if (peek.date_override) |text| {
            const t = cli.parseDateOverride(text, .{ .epoch = amb.now_epoch, .ms = amb.now_ms }) catch |e| {
                switch (e) {
                    error.Unrecognized => streams.err.print("zit commit: unrecognized date format ({s}): use \"YYYY-MM-DD HH:MM:SS.SSS\"\n", .{text}) catch {},
                    error.OutOfRange => streams.err.print("zit commit: --date-override {s} is outside the years a check-in can carry (1970 to 9999)\n", .{text}) catch {},
                }
                return .failure;
            };
            amb.now_epoch = t.epoch;
            amb.now_ms = t.ms;
        }
        if (peek.stdin_path != null or peek.renames.len != 0 or peek.deletes.len != 0)
            return runCommitDirect(gpa, io, arena, peek, streams, amb);
        if (amb.repo_override != null) return cli.usageError(streams, "commit", .repo_unsupported, "-R/--repo");
        if (peek.parent != null) {
            streams.err.writeAll("zit commit: --parent needs --stdin, --rename or --delete; a checkout commits onto the check-in it is on\n") catch {};
            streams.err.writeAll("try 'zit commit --help'\n") catch {};
            return .usage;
        }
    }
    return runCommitIn(gpa, io, arena, verb_args, streams, amb, null);
}

/// The scratch directory a direct commit holds beside the store while it
/// commits: the new bytes `--stdin` gives and nothing else, the tree the project's
/// versioned settings and its before-commit check are read and run in. One
/// name, not one per run: it is made and destroyed under the store's writer
/// lock, so no two runs can share it, and a crashed run's leftover is swept
/// by the next. The `.zit-tmp-` prefix marks it scratch for every other
/// reader.
const stdin_work_name = ".zit-tmp-commit-stdin";

/// `zit commit -R STORE -m MSG [--delete PATH]... [--rename OLD NEW]...
/// [--stdin PATH] [--user U] [--branch B] [--parent CHECKIN] [--allow-fork]`:
/// one check-in of these edits, every other file carried forward from the
/// parent: the deletes, then the renames, then stdin's bytes as PATH's new
/// content (a rename's NEW, when PATH names one, so the renamed file takes
/// the new bytes). No checkout of the caller's is created or consulted.
///
/// The check-in is minted by the direct-commit core (`zit.checkin`) from the
/// parent's manifest and these edits, under the rules a commit from a
/// checkout follows (fork guard, settings, sub-manifests, the R card); the
/// differential test holds the two to the same bytes. The store's writer lock
/// is taken before the parent is chosen and held until the check-in is
/// published: concurrent writers land one after another on one line of
/// history, each built on the last. stdout is the new check-in's full hash;
/// edits that leave the parent's file set as it was write nothing, print the
/// parent's hash, and exit `no_new`; a resend of a check-in already stored
/// prints its name and exits 0. Never autosyncs.
fn runCommitDirect(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    parsed: cli.CommitArgs,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    // The flag the messages name: --stdin when given, as it always has been.
    const mode: []const u8 = if (parsed.stdin_path != null) "--stdin" else if (parsed.renames.len != 0) "--rename" else "--delete";
    if (amb.repo_override == null) {
        streams.err.print("zit commit: {s} needs -R STORE; it records into a repository, not a checkout\n", .{mode}) catch {};
        streams.err.writeAll("try 'zit commit --help'\n") catch {};
        return .usage;
    }
    if (parsed.paths.len != 0) return cli.usageError(streams, "commit", .extra_argument, parsed.paths[0]);
    // The flags that act on a working tree or an interactive session have
    // nothing to act on here. `--no-sync` is accepted: it asks for what
    // this mode always does.
    const refused: ?[]const u8 = if (parsed.message_file != null)
        "-M/--message-file"
    else if (parsed.editor != null)
        "--editor"
    else if (parsed.dry_run)
        "-n/--dry-run"
    else if (parsed.allow_empty)
        "--allow-empty"
    else if (parsed.close)
        "--close"
    else if (parsed.sign)
        "--sign"
    else if (parsed.quiet)
        "-q/--quiet"
    else if (parsed.no_submanifest_advice)
        "--no-submanifest-advice"
    else
        null;
    if (refused) |flag| {
        streams.err.print("zit commit: {s} does not apply with {s}\n", .{ flag, mode }) catch {};
        streams.err.writeAll("try 'zit commit --help'\n") catch {};
        return .usage;
    }
    const message = parsed.message orelse {
        streams.err.print("zit commit: {s} needs -m MESSAGE\n", .{mode}) catch {};
        streams.err.writeAll("try '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;
    }
    if (parsed.stdin_path) |path| if (!directPathOk(streams, path)) return .usage;
    for (parsed.renames) |r| if (!directPathOk(streams, r.new)) return .usage;
    if (parsed.branch) |b| if (b.len == 0) {
        streams.err.writeAll("zit commit: --branch name must not be empty\n") catch {};
        return .failure;
    };
    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;
    };

    // The content IS stdin, whole, read before the store is touched.
    var bytes: []u8 = &.{};
    defer gpa.free(bytes);
    if (parsed.stdin_path != null) {
        var read_buf: [64 * 1024]u8 = undefined;
        var reader = std.Io.File.stdin().readerStreaming(io, &read_buf);
        bytes = reader.interface.allocRemaining(gpa, .limited(max_tracked_file_bytes)) catch |e| {
            switch (e) {
                error.StreamTooLong => streams.err.print("zit commit: stdin is larger than one file a check-in can hold ({d} bytes)\n", .{max_tracked_file_bytes}) catch {},
                error.OutOfMemory => return commitOom(streams),
                else => streams.err.writeAll("zit commit: cannot read the content from stdin\n") catch {},
            }
            return .failure;
        };
    }

    // The edits in their fixed order: deletes, renames, the put. `--stdin`
    // naming a rename's NEW gives that rename its content instead.
    var edits: std.ArrayList(zit.checkin.Edit) = .empty;
    var stdin_taken = false;
    for (parsed.deletes) |path| edits.append(arena, .{ .delete = path }) catch return commitOom(streams);
    for (parsed.renames) |r| {
        const takes_stdin = if (parsed.stdin_path) |p| std.mem.eql(u8, p, r.new) else false;
        stdin_taken = stdin_taken or takes_stdin;
        edits.append(arena, .{ .rename = .{ .old = r.old, .new = r.new, .bytes = if (takes_stdin) bytes else null } }) catch return commitOom(streams);
    }
    if (parsed.stdin_path) |path| if (!stdin_taken) {
        edits.append(arena, .{ .put = .{ .path = path, .bytes = bytes } }) catch return commitOom(streams);
    };

    var diag: zit.checkin.Diag = .{};
    zit.checkin.checkRequest(.{
        .branch = parsed.branch,
        .user = author,
        .comment = message,
        .now = .{ .epoch = amb.now_epoch, .ms = amb.now_ms },
        .edits = edits.items,
    }, &diag) catch |e| return stdinFail(streams, e, &diag);

    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return commitOom(streams)) orelse {
        diagnostics.reportNoRoot(streams, io, "commit", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var ctx: zit.checkin.Context = undefined;
    ctx.open(gpa, io, root_dir, .{ .hold_lock = true }, &diag) catch |e| return stdinFail(streams, e, &diag);
    defer ctx.deinit();

    // Made after the lock is taken and gone before it is released, so the
    // next writer never meets this run's area, nor this run its.
    root_dir.deleteTree(io, stdin_work_name) catch {}; // a prior run's wreckage, if any
    root_dir.createDir(io, stdin_work_name, .default_dir) catch return stdinWorkFail(streams);
    defer root_dir.deleteTree(io, stdin_work_name) catch {};
    var area = root_dir.openDir(io, stdin_work_name, .{}) catch return stdinWorkFail(streams);
    defer area.close(io);
    if (parsed.stdin_path) |path| update.restoreFile(io, area, path, bytes, .regular) catch return stdinWorkFail(streams);

    var commit_config: ?logstore.OwnedConfig = ctx.log.readConfig(gpa) catch null;
    defer if (commit_config) |*c| c.deinit(gpa);
    const cfg: ?*const logstore.Config = if (commit_config) |*c| &c.config else null;
    const settings = CommitSettings.of(io, arena, area, amb, cfg);
    var hooks: StdinHooks = .{
        .gpa = gpa,
        .io = io,
        .arena = arena,
        .area = area,
        .streams = streams,
        .amb = amb,
        .cfg = cfg,
        .no_checks = parsed.no_checks,
        .pgp_command = settings.signing.pgp_command,
    };
    const outcome = zit.checkin.commit(&ctx, .{
        .parent = parsed.parent,
        .branch = parsed.branch,
        .user = author,
        .comment = message,
        .now = .{ .epoch = amb.now_epoch, .ms = amb.now_ms },
        .edits = edits.items,
        // A given time makes a resend recognizable by its time, user and
        // comment, as the daemon's is; the clock's own time never repeats.
        .find_resend = parsed.date_override != null,
        .allow_fork = parsed.allow_fork,
        .no_checks = parsed.no_checks,
        .policy = .{
            .binary_glob = settings.binary_glob,
            .crlf_glob = settings.crlf_glob,
            .encoding_glob = settings.encoding_glob,
            .repo_cksum = settings.repo_cksum,
        },
        .hooks = .{
            .ctx = &hooks,
            .before_commit = StdinHooks.beforeCommit,
            // fossil's `clearsign` setting signs every commit unasked.
            .seal = if (settings.signing.clearsign) StdinHooks.seal else null,
        },
    }, &diag) catch |e| return stdinFail(streams, e, &diag);
    switch (outcome) {
        .unchanged => |name| {
            streams.out.print("{s}\n", .{name.slice()}) catch {};
            return .no_new;
        },
        .recorded, .existing => |name| {
            reportSubmanifestOutOfRange(streams, settings.emission);
            streams.out.print("{s}\n", .{name.slice()}) catch {};
            return .ok;
        },
    }
}

/// What `commit --stdin` hands the core for the two steps that run processes:
/// the project's before-commit check and the clearsign, both in the area.
const StdinHooks = struct {
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    area: std.Io.Dir,
    streams: cli.Streams,
    amb: cli.Ambient,
    cfg: ?*const logstore.Config,
    no_checks: bool,
    pgp_command: []const u8,

    fn beforeCommit(ctx: ?*anyopaque) error{Refused}!void {
        const self: *StdinHooks = @ptrCast(@alignCast(ctx.?));
        if (runBeforeCommit(self.gpa, self.io, self.arena, self.area, self.streams, self.amb, self.cfg, self.no_checks) != .ok) return error.Refused;
    }

    fn seal(ctx: ?*anyopaque, gpa: std.mem.Allocator, plain: []const u8) error{ Refused, OutOfMemory }!?[]u8 {
        const self: *StdinHooks = @ptrCast(@alignCast(ctx.?));
        return clearsignBytes(gpa, self.io, self.amb, self.area, self.pgp_command, plain) orelse error.Refused;
    }
};

/// The content policy and R card `commit -R` resolves for a store, for a
/// resident committer that resolves it once and hands it to the core on every
/// commit. `clearsign` is reported rather than acted on: the caller decides
/// what to do about a store that asks for every check-in to be signed.
pub const DirectPolicy = struct {
    policy: zit.checkin.Policy,
    clearsign: bool,
};

pub fn directCommitPolicy(
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    amb: cli.Ambient,
    cfg: ?*const logstore.Config,
) DirectPolicy {
    const settings = CommitSettings.of(io, arena, root_dir, amb, cfg);
    return .{
        .policy = .{
            .binary_glob = settings.binary_glob,
            .crlf_glob = settings.crlf_glob,
            .encoding_glob = settings.encoding_glob,
            .repo_cksum = settings.repo_cksum,
        },
        .clearsign = settings.signing.clearsign,
    };
}

/// Renders a core refusal: each line of its detail as one `zit commit:`
/// sentence, except the fork guard's advice, which follows its line bare as
/// it does from a checkout.
fn stdinFail(s: cli.Streams, e: zit.checkin.Error, diag: *const zit.checkin.Diag) cli.Exit {
    if (e == error.OutOfMemory) return commitOom(s);
    if (e == error.NotARepo) {
        s.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    }
    renderCoreDiag(s, e, diag);
    return .failure;
}

fn renderCoreDiag(s: cli.Streams, e: anyerror, diag: *const zit.checkin.Diag) void {
    var lines = std.mem.splitScalar(u8, diag.text(), '\n');
    var first = true;
    while (lines.next()) |line| {
        if (line.len == 0) continue;
        if (first or e != error.NotTip) {
            s.err.print("zit commit: {s}\n", .{line}) catch {};
        } else {
            s.err.print("{s}\n", .{line}) catch {};
        }
        first = false;
    }
}

/// A direct commit's path must be one a check-in can hold; a usage error
/// otherwise, before anything is read.
fn directPathOk(s: cli.Streams, path: []const u8) bool {
    zit.control_paths.validateWorktreePath(path) catch {
        s.err.print("zit commit: '{s}' is not a path a check-in can hold\n", .{path}) catch {};
        s.err.writeAll("try 'zit commit --help'\n") catch {};
        return false;
    };
    return true;
}

fn stdinWorkFail(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit commit: cannot write the working area beside the repository\n") catch {};
    return .failure;
}

/// `commit`, against a checkout this caller NAMES. See `runMergeIn`: same
/// reasoning, same borrowing rule. This is the ONE manifest minter -- the R
/// card, the delta-dialect continuation and sub-manifest emission are decided
/// here and nowhere else -- so a caller that needs a check-in comes through
/// it rather than growing a second writer whose artifacts other conforming
/// implementations would hash differently.
/// What `runCommitInner` did with the comment file: the wrapper
/// keeps it for recovery when the commit failed after the editor ran.
const CommitSession = struct {
    comment_file_used: bool = false,
    dependency_root: ?[]const u8 = null,
    dependency_fetched: bool = false,
};

fn commitMissingNode(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    root_abs: []const u8,
    streams: cli.Streams,
    dry_run: bool,
    session: *CommitSession,
) cli.Exit {
    if (zit.repocache.readStoreCone(gpa, io, root_dir)) |stored| {
        var sparse = stored;
        sparse.deinit(gpa);
        if (dry_run) {
            streams.err.writeAll("zit commit: required structural content is elided by the store's sparse cone; fetch it before a dry-run commit\n") catch {};
            return .failure;
        }
        if (!session.dependency_fetched) {
            session.dependency_root = root_abs;
            return .failure;
        }
        streams.err.writeAll("zit commit: the saved remote did not supply required structural content; refusing to commit\n") catch {};
        return .failure;
    }
    return commitParentCorrupt(streams, "a required sub-manifest is missing");
}

pub const comment_file_name = ".zit-ci-comment";

pub fn runCommitIn(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
) cli.Exit {
    var session: CommitSession = .{};
    return runCommitSession(gpa, io, arena, verb_args, streams, amb, checkout_root, &session);
}

fn runCommitSession(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
    session: *CommitSession,
) cli.Exit {
    var rc = runCommitInner(gpa, io, arena, verb_args, streams, amb, checkout_root, session);
    if (session.dependency_root) |abs| {
        // The attempt has unwound: no snapshot handle or writer lock survives
        // into network I/O. --no-sync suppresses autosync, not required content.
        const root = (cli.resolveRoot(arena, io, abs) catch null) orelse return .failure;
        var dir = root.dir;
        defer dir.close(io);
        var url_buf: [logstore.max_config_str]u8 = undefined;
        if (updateResolveRemote(gpa, io, dir, &url_buf) == null) {
            streams.err.writeAll(
                "zit commit: structural content is elided by the store's sparse cone and no remote is saved; refusing to commit\n" ++
                    "zit commit: set one with 'zit remote URL', or re-clone with a wider --cone\n",
            ) catch {};
            return .failure;
        }
        streams.err.writeAll("zit commit: fetching required structural content from the saved remote\n") catch {};
        var fetch_amb = amb;
        fetch_amb.repo_override = abs;
        if (cmd_sync.pullCommitDependencies(gpa, io, arena, .{ .out = streams.err, .err = streams.err }, fetch_amb) != .ok) {
            streams.err.writeAll("zit commit: required structural content could not be obtained; refusing to commit\n") catch {};
            return .failure;
        }
        session.dependency_root = null;
        session.dependency_fetched = true;
        rc = runCommitInner(gpa, io, arena, verb_args, streams, amb, checkout_root, session);
    }
    if (session.comment_file_used) {
        if (checkout_root) |given| {
            settleCommentFile(io, given.dir, rc, streams);
        } else if (cli.discoverRoot(arena, io) catch null) |root| {
            var dir = root.dir;
            defer dir.close(io);
            settleCommentFile(io, dir, rc, streams);
        }
    }
    return rc;
}

/// After the editor path: a recorded check-in retires the comment file; a
/// failure keeps it and says how to reuse it.
fn settleCommentFile(io: std.Io, dir: std.Io.Dir, rc: cli.Exit, streams: cli.Streams) void {
    if (rc == .ok) {
        dir.deleteFile(io, comment_file_name) catch {};
    } else {
        streams.err.print("zit commit: your comment is kept in {s}; pass -M {s} to reuse it\n", .{ comment_file_name, comment_file_name }) catch {};
    }
}

/// The settings a commit acts on that the repository's own config can change.
/// Preparation runs unlocked, so another writer can append a config frame
/// before the commit publishes; publish then reads these again and refuses
/// a commit prepared under one policy from landing under another.
const CommitSettings = struct {
    binary_glob: []const u8,
    crlf_glob: []const u8,
    encoding_glob: []const u8,
    emission: zit.submanifest.Emission,
    signing: SigningSettings,
    /// Fossil's `repo-cksum`: compute the R card. Default on.
    repo_cksum: bool,

    fn of(io: std.Io, arena: std.mem.Allocator, root_dir: std.Io.Dir, amb: cli.Ambient, cfg: ?*const logstore.Config) CommitSettings {
        return .{
            .binary_glob = projectSetting(io, arena, root_dir, amb, cfg, .binary_glob),
            // `crnl-glob` is the fallback spelling, consulted only when no
            // tier supplies `crlf-glob`.
            .crlf_glob = (cmd_sync.resolveCrlfGlob(io, arena, root_dir, .{ .environ = amb.environ }, cfg) catch
                zit.settings.Resolved{ .value = "", .source = .default }).value,
            // Fossil's `encoding-glob`, under the same opt-in rule:
            // unset means this project has no opinion about encodings.
            .encoding_glob = projectSetting(io, arena, root_dir, amb, cfg, .encoding_glob),
            .repo_cksum = zit.settings.parseBool(projectSetting(io, arena, root_dir, amb, cfg, .repo_cksum)) orelse false,
            .emission = submanifestEmission(cfg).emission,
            .signing = signingSettings(io, arena, root_dir, amb, cfg),
        };
    }

    fn eql(a: CommitSettings, b: CommitSettings) bool {
        return std.mem.eql(u8, a.binary_glob, b.binary_glob) and
            std.mem.eql(u8, a.crlf_glob, b.crlf_glob) and
            std.mem.eql(u8, a.encoding_glob, b.encoding_glob) and
            std.meta.eql(a.emission, b.emission) and
            a.signing.clearsign == b.signing.clearsign and
            std.mem.eql(u8, a.signing.pgp_command, b.signing.pgp_command);
    }
};

/// What `commitParentChecks` decided: the parent's inherited sym-* tags a
/// `--branch` commit cancels and, when asked for, the name of the new
/// manifest's skip-delta base (`skipBaseOf`); or a refusal already reported.
const ParentChecks = union(enum) {
    ok: struct {
        syms: []const []const u8,
        skip_base: ?[]const u8 = null,
    },
    refused: cli.Exit,
};

/// The checks a commit makes against the rest of the repository, not just its
/// own tree: the fork guard, and for `--branch`, that NAME is not an open
/// branch and which of the parent's sym-* tags the new check-in cancels. Run
/// over the snapshot while preparing, and again at publish when another writer
/// appended in between, since either answer can change. `parent` is the
/// version the check-in was prepared on, the one its P card names; the
/// checkout file is not re-read, since another commit may have advanced it.
/// The sym names are duped onto `ma` so they outlive the view.
fn commitParentChecks(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    ma: std.mem.Allocator,
    parsed: cli.CommitArgs,
    branch: []const u8,
    parent: []const u8,
    want_skip_base: bool,
) ParentChecks {
    var repo: Repository = undefined;
    repo.open(gpa, io, root_dir, .{ .mode = .full }) catch |e| return .{ .refused = repoOpenFail(streams, "commit", e) };
    defer repo.deinit(gpa);
    var diag: zit.checkin.Diag = .{};
    const checked = zit.checkin.parentChecks(&repo, gpa, ma, .{
        .switch_branch = parsed.branch,
        .allow_fork = parsed.allow_fork,
    }, branch, parent, want_skip_base, &diag) catch |e| switch (e) {
        error.OutOfMemory => return .{ .refused = commitOom(streams) },
        error.NotTip, error.BranchExists => {
            renderCoreDiag(streams, e, &diag);
            return .{ .refused = .failure };
        },
    };
    return .{ .ok = .{ .syms = checked.syms, .skip_base = checked.skip_base } };
}

fn runCommitInner(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    checkout_root: ?NamedCheckout,
    session: *CommitSession,
) 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 parsed.deinit(gpa);
    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.
    // The comment comes from -m, from -M FILE, or — on a terminal,
    // or with --editor — from an editor over a template that lists what
    // this commit captures. The last needs the composed change set, so its
    // resolution waits until step 9; what is decided here is only whether
    // there is a way to get one at all. A dry run needs no comment.
    var early_message: ?[]const u8 = parsed.message;
    if (early_message == null) if (parsed.message_file) |mf| {
        early_message = readMessageFile(gpa, io, arena, mf) orelse {
            streams.err.print("zit commit: cannot read the message file '{s}'\n", .{mf}) catch {};
            return .failure;
        };
    };
    // A configured `editor` setting makes the editor path available
    // without a terminal, as --editor does.
    var ed_arena = std.heap.ArenaAllocator.init(gpa);
    defer ed_arena.deinit();
    var disc: ?std.Io.Dir = null;
    defer if (disc) |*d| d.close(io);
    const editor_configured = blk: {
        const ea = ed_arena.allocator();
        const dir = if (checkout_root) |c| c.dir else dblk: {
            const root = (cli.discoverRoot(ea, io) catch null) orelse break :blk false;
            disc = root.dir;
            break :dblk root.dir;
        };
        const r = cmd_sync.resolveSetting(gpa, io, ea, dir, .{ .environ = amb.environ }, .editor) catch break :blk false;
        break :blk r.value.len != 0;
    };
    const editor_capable = parsed.editor != null or editor_configured or ((std.Io.File.stdin().isTty(io) catch false) and (std.Io.File.stderr().isTty(io) catch false));
    if (early_message == null and !parsed.dry_run and !editor_capable) {
        streams.err.writeAll(
            "zit commit: a check-in message is required\n" ++
                "  give one with -m <message>,\n" ++
                "  run from a terminal to compose it in $EDITOR,\n" ++
                "  or set an editor: zit settings editor <command>\n" ++
                "try 'zit commit --help'\n",
        ) catch {};
        return .usage;
    }
    if (early_message) |m| if (std.mem.trim(u8, m, " \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;
    };
    if (zit.control_paths.hasControlByte(author)) {
        streams.err.print("zit commit: --user \"{f}\" holds a control byte; a check-in cannot carry it\n", .{std.zig.fmtString(author)}) catch {};
        return .failure;
    }

    // 3b. Autosync pull: see the freshest DAG before the fork guard asks
    //     whether the parent is still a leaf. Best-effort — offline commits
    //     must keep working, so a failure warns and this verb proceeds.
    if (!parsed.no_sync and !session.dependency_fetched) cmd_sync.autosyncPull(gpa, io, arena, streams, "commit");

    // 4. The checkout root (B-commit-14) and the working state. Discovered from
    //    the cwd for the verb; NAMED by an in-process caller driving a checkout
    //    it created (`runCommitIn`). A named dir is borrowed, so it is not
    //    closed here.
    var root_dir: std.Io.Dir = undefined;
    var root_abs: []const u8 = undefined;
    var owns_root = false;
    if (checkout_root) |given| {
        root_dir = given.dir;
        root_abs = given.abs;
    } else {
        const root = (cli.discoverRoot(arena, io) catch
            return commitOom(streams)) orelse {
            streams.err.writeAll(not_a_repo_msg) catch {};
            return .failure;
        };
        root_dir = root.dir;
        root_abs = root.abs;
        owns_root = true;
    }
    defer if (owns_root) 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;
    // The pending merge operations (from `zit merge`, stacked as Fossil stacks
    // them) are what this check-in records beyond its files, and the advance
    // clears them (B-merge-8/9). A merged check-in -- plain or --integrate --
    // extends the P card; a cherrypick or backout is NOT a merge parent
    // (B-merge-33) but a Q card of provenance (§4.7.14). None pending → the
    // ordinary single-parent path, untouched (B-merge-9 negative space).
    var n_parents: usize = 0;
    var n_special: usize = 0;
    {
        var pit = checkout.pending(ck);
        while (pit.next()) |p| {
            if (p.isParent()) n_parents += 1 else n_special += 1;
        }
    }
    const is_merge = n_parents != 0;
    const has_special = n_special != 0;
    // A merge needs a prior version, so a pending operation never coexists
    // with an unborn (root) checkout.
    std.debug.assert(!is_root or (!is_merge and !has_special));

    // 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;
        }
        if (zit.control_paths.hasControlByte(bname)) {
            streams.err.print("zit commit: --branch \"{f}\" holds a control byte; a check-in cannot carry it\n", .{std.zig.fmtString(bname)}) 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. Snapshot the store. The writer lock is held only while the store is
    //    opened and the checks that read the rest of the repository run, so
    //    the open sees no half-written frame. Everything after that -- the
    //    tree scan, the content checks, the message editor, the project's
    //    `before-commit` check, signing -- runs with no lock held: a person
    //    at the editor must not keep every other writer out. Step 11 takes
    //    the lock again to publish, and re-checks what this snapshot read.
    //    The handle stays open for reads; a rewrite (`pack`, `shun --force`)
    //    installs a new file and leaves this one intact.
    var snap = cli.openStoreAppend(io, root_dir) catch |e| return commitLockFail(streams, e);
    var snap_locked = true;
    defer {
        snap.file.close(io);
        if (snap_locked) snap.lock.release(io);
    }
    const log_st = snap.file.stat(io) catch return commitLogFail(streams, error.Storage);
    var fs = storage.FileStorage.init(io, snap.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).
    // Opened for append, under the lock, so a torn tail a crashed writer left
    // is repaired here exactly as before.
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch |e|
        return commitLogFail(streams, e);
    defer log.deinit(gpa);
    const snap_key = log.logKey() catch |e| return commitLogFail(streams, switch (e) {
        error.Storage => error.Storage,
        error.Corrupt => error.Corrupt,
    });
    const snap_config_offset = log.config_offset;

    // One frame read for the whole commit gate. Every setting this verb
    // resolves from here on answers its REPOSITORY tier out of `cfg`, so the
    // store is opened once instead of once per name — the shape `update` and
    // `open` already have. Read after the autosync pull, which is the only
    // thing that can rewrite the frame under us. An unreadable frame is null,
    // which every reader below treats as "this repository said nothing",
    // leaving the other tiers reachable.
    var commit_config: ?logstore.OwnedConfig = log.readConfig(gpa) catch null;
    defer if (commit_config) |*c| c.deinit(gpa);
    const cfg: ?*const logstore.Config = if (commit_config) |*c| &c.config else null;

    // 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 the store lacks is held in `pending` until
    //    step 11 stores it.
    var m_arena = std.heap.ArenaAllocator.init(gpa);
    defer m_arena.deinit();
    const ma = m_arena.allocator();
    var pending: PendingBlobs = .{};
    defer pending.deinit(gpa);

    // 6b. The fork guard and branch prep, over the snapshot. Step 11 runs
    //     them again if another writer appended in the meantime.
    var parent_syms: []const []const u8 = &.{};
    // The name of the manifest's skip-delta base, resolved to a rid at publish.
    var skip_base: ?[]const u8 = null;
    if (!is_root) switch (commitParentChecks(gpa, io, root_dir, streams, ma, parsed, branch, ck.version, true)) {
        .ok => |ok| {
            parent_syms = ok.syms;
            skip_base = ok.skip_base;
        },
        .refused => |rc| return rc,
    };

    // The snapshot is taken; from here until step 11 no lock is held. The
    // handle can no longer append, and nothing below asks it to.
    log.writable = false;
    snap.lock.release(io);
    snap_locked = false;

    // 7. Parent manifest (child only): draft-fossil-submanifests-00 §§5.1–5.2
    //    require an S-bearing parent to be resolved to its complete F-set
    //    before carry-forward, no-op, or same-path delta-base decisions. Load it
    //    before capture so resolver corruption cannot leave a captured blob.
    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 baseline_bytes: ?[]u8 = null;
    defer if (baseline_bytes) |b| gpa.free(b);
    var baseline_manifest: ?artifact.Manifest = null;
    defer if (baseline_manifest) |*bm| bm.deinit();
    var baseline_normalized: ?[]u8 = null;
    defer if (baseline_normalized) |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) {
        var pdigest_buf: [digest_len]u8 = undefined;
        const pdigest = hexToDigest(ck.version, &pdigest_buf) orelse return commitParentCorrupt(streams, "the checkout names it in a form this build cannot decode");
        const prid = log.lookup(pdigest) orelse return commitParentCorrupt(streams, "not present in this repository");
        parent_manifest_rid = prid;
        parent_bytes = (log.content(gpa, prid) catch |e| return commitContentFail(streams, e)) orelse
            return commitParentCorrupt(streams, "its content is unreadable");
        const parent_im = artifact.parseForImport(gpa, parent_bytes.?) catch |err| switch (err) {
            error.OutOfMemory => return commitOom(streams),
            else => |pe| return commitParentCorrupt(streams, @errorName(pe)),
        };
        pm = parent_im.manifest;
        pm_normalized = parent_im.normalized;
        if (pm.?.kind != .manifest) return commitParentCorrupt(streams, "it is not a check-in manifest");
        if (pm.?.s.len != 0) {
            flattenCommitParent(gpa, &log, &pm.?) catch |err| switch (err) {
                error.OutOfMemory => return commitOom(streams),
                error.MissingNode => return commitMissingNode(gpa, io, root_dir, root_abs, streams, parsed.dry_run, session),
                else => |te| return commitParentCorrupt(streams, @errorName(te)),
            };
        }
        if (pm.?.b) |b| {
            // §8.2/§8.3 — a delta parent's own F run is a PATCH, not a file
            // set. Whole-tree capture masks that on the default path (every
            // managed file is captured regardless), but carry-forward and
            // the delta-frame base hints read `parent_f` as the parent's
            // EFFECTIVE set, and the dialect emission below diffs against
            // the true baseline — so resolve it, hard-failure discipline,
            // and retain the raw baseline beside the merged result.
            var bdigest_buf: [digest_len]u8 = undefined;
            const bdigest = hexToDigest(b.hash, &bdigest_buf) orelse return commitParentCorrupt(streams, "its baseline is named in a form this build cannot decode");
            const brid = log.lookup(bdigest) orelse return commitParentCorrupt(streams, "its baseline is not present in this repository");
            baseline_bytes = (log.content(gpa, brid) catch |e| return commitContentFail(streams, e)) orelse
                return commitParentCorrupt(streams, "its baseline content is unreadable");
            const bim = artifact.parseForImport(gpa, baseline_bytes.?) catch |err| switch (err) {
                error.OutOfMemory => return commitOom(streams),
                else => |pe| return commitParentCorrupt(streams, @errorName(pe)),
            };
            baseline_manifest = bim.manifest;
            baseline_normalized = bim.normalized;
            // A baseline that is itself a delta is accepted and merged one
            // level, as Fossil does (§4.7.3); the dialect step below then
            // emits flat rather than name it in a B card.
            if (baseline_manifest.?.kind != .manifest)
                return commitParentCorrupt(streams, "its baseline is not a manifest");
            if (baseline_manifest.?.s.len != 0) {
                flattenCommitParent(gpa, &log, &baseline_manifest.?) catch |err| switch (err) {
                    error.OutOfMemory => return commitOom(streams),
                    error.MissingNode => return commitMissingNode(gpa, io, root_dir, root_abs, streams, parsed.dry_run, session),
                    else => |te| return commitParentCorrupt(streams, @errorName(te)),
                };
            }
            const BaselineCtx = struct {
                bm: *const artifact.Manifest,
                fn resolve(ctx: *anyopaque, hash: []const u8) ?artifact.ManifestFiles {
                    const self_ctx: *@This() = @ptrCast(@alignCast(ctx));
                    _ = hash; // one candidate, already matched to the B card above
                    return zit.manifestFilesOf(self_ctx.bm);
                }
            };
            var bctx = BaselineCtx{ .bm = &baseline_manifest.? };
            var walk = artifact.enumerate(zit.manifestFilesOf(&pm.?), .{
                .ctx = @ptrCast(&bctx),
                .resolveFn = BaselineCtx.resolve,
            }) catch return commitParentCorrupt(streams, "its baseline does not enumerate");
            var effective: std.ArrayList(artifact.FCard) = .empty;
            while (walk.next()) |fc| {
                if (fc.hash == null) continue; // merged delete markers carry no file
                effective.append(ma, fc) catch return commitOom(streams);
            }
            parent_f = effective.items;
        } else {
            parent_f = pm.?.flattened orelse pm.?.f;
        }
        // Sparse-cone RFC section 4.4: a pending cross-cone merge left its
        // resolved out-of-cone outcomes in the merge_overlay section. Apply
        // them onto the parent's effective set BEFORE anything reads it --
        // the compose's carry-forward then records theirs' hashes, and the
        // base-hint loop below sees the overlaid cards too. The section is
        // cleared by the post-commit record write, same one-shot rule as
        // merge_parent itself.
        {
            const overlay_payload = checkout.readSectionAlloc(gpa, io, root_dir, .merge_overlay) catch |e| switch (e) {
                error.OutOfMemory => return commitOom(streams),
                else => return commitLogFail(streams, error.Storage),
            };
            if (overlay_payload) |payload| {
                defer gpa.free(payload);
                // Decoded entries BORROW the payload; the merged cards below
                // borrow the entries. Re-home the bytes in the commit arena
                // so everything outlives this block together.
                const payload_owned = ma.dupe(u8, payload) catch return commitOom(streams);
                const overlay_entries = update.decodeOverlay(ma, payload_owned) catch
                    return commitParentCorrupt(streams, "the pending merge's overlay record is unreadable");
                var merged: std.ArrayList(artifact.FCard) = .empty;
                for (parent_f) |fc| {
                    var replaced = false;
                    var deleted = false;
                    for (overlay_entries) |entry| {
                        if (!std.mem.eql(u8, entry.path, fc.filename)) continue;
                        if (entry.hash) |h| {
                            var card = fc;
                            card.hash = h;
                            card.perm = entry.perm;
                            merged.append(ma, card) catch return commitOom(streams);
                            replaced = true;
                        } else {
                            deleted = true;
                        }
                        break;
                    }
                    if (!replaced and !deleted) merged.append(ma, fc) catch return commitOom(streams);
                }
                // Overlay entries for paths the parent lacks are additions.
                for (overlay_entries) |entry| {
                    const h = entry.hash orelse continue;
                    var known = false;
                    for (parent_f) |fc| {
                        if (std.mem.eql(u8, entry.path, fc.filename)) {
                            known = true;
                            break;
                        }
                    }
                    if (!known) merged.append(ma, .{
                        .filename = entry.path,
                        .hash = h,
                        .perm = entry.perm,
                        .old_name = null,
                        .mode = .regular,
                    }) catch return commitOom(streams);
                }
                std.mem.sort(artifact.FCard, merged.items, {}, struct {
                    fn less(_: void, a: artifact.FCard, b: artifact.FCard) bool {
                        return artifact.compareBytes(a.filename, b.filename) == .lt;
                    }
                }.less);
                parent_f = merged.items;
            }
        }

        // 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;
            var bd_buf: [digest_len]u8 = undefined;
            const bd = hexToDigest(h, &bd_buf) 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;
    // Resolved once for the whole commit, not per file: the tier chain
    // reads the working tree, and a policy that changed mid-commit would make
    // the refusal depend on capture order. `--no-checks` waives this the same
    // way it waives `before-commit` — one flag for "skip the commit-time
    // checks" rather than a second spelling for the same intent. Unreadable
    // settings resolve to empty, which REFUSES the odd content rather than
    // admitting it: the safe direction for a check, and the opposite of the
    // choice `signingSettings` makes, where guessing "sign" would fail a
    // commit that should have succeeded.
    var content_notes: std.ArrayList(ContentNote) = .empty;
    const settings = CommitSettings.of(io, arena, root_dir, amb, cfg);
    const content_policy: ContentPolicy = .{
        .binary_glob = settings.binary_glob,
        .crlf_glob = settings.crlf_glob,
        .encoding_glob = settings.encoding_glob,
        .waived = parsed.no_checks,
    };
    const policy: cli.ComposePolicy = if (parsed.paths.len == 0) .snapshot else .carry_forward;
    var treestat = cmd_tracking.TreeStat.load(gpa, io, root_dir);
    defer treestat.deinit();
    defer treestat.persist(io, root_dir);
    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, &pending, path, parent_blob.get(path), content_policy, &content_notes, &treestat)) {
                .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),
                .too_large => |size| return commitTooLarge(streams, path, size),
                .content_class => |f| return commitContentClass(streams, path, f),
                .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, &pending, key, parent_blob.get(key), content_policy, &content_notes, &treestat)) {
                .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),
                .too_large => |size| return commitTooLarge(streams, key, size),
                .content_class => |f| return commitContentClass(streams, key, f),
                .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: std.ArrayList([]const u8) = .empty;
    for (set.pendingRenames()) |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.append(ma, c.filename) catch return commitOom(streams);
                break;
            }
        }
    }

    // Managed-set agreement: every captured card names a path in the managed set
    // (all-files iterates it; partial gates each arg on `set.contains`), so the
    // manifest assembles only over tracked files.
    if (std.debug.runtime_safety) {
        for (captured.items) |c| std.debug.assert(set.contains(c.filename));
    }

    // 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.
    // Sparse-cone RFC section 4.2: a commit from a sparse checkout unions the
    // in-cone worktree state with the baseline's out-of-cone entries carried
    // verbatim. The reader-indistinguishability rule is the point: the minted
    // check-in is ordinary, and no reader can tell it was committed sparsely.
    var commit_cone = zit.update.readStoredCone(gpa, io, root_dir) catch |e| switch (e) {
        error.OutOfMemory => return commitOom(streams),
        else => return commitLogFail(streams, error.Storage),
    };
    defer if (commit_cone) |*c| c.deinit(gpa);

    const composed = cli.composeFCards(ma, .{
        .parent = parent_f,
        .captured = captured.items,
        .policy = policy,
        .sparse = if (commit_cone) |*c| c else null,
    }) 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 and !parsed.allow_empty) {
        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;
        }
        // Every conflict this merge produced is resolved: remember how.
        // Placed after the refusal so a precedent can only ever be learned from
        // bytes that passed the same gate the check-in did.
        _ = cmd_precedent.promoteAtCommit(gpa, io, root_dir, streams);
    }

    // The change set is composed and every refusal that needs no
    // comment has had its say: a dry run reports here, and a comment that is
    // still missing is composed in the editor over exactly this list.
    const change_lines = commitChangeLines(arena, parent_f, composed.f) catch return commitOom(streams);
    if (parsed.dry_run) {
        for (change_lines) |l| streams.err.print("{s} {s}\n", .{ l.word, l.path }) catch {};
        streams.err.print("(dry run: would record {d} file(s) on branch {s}; nothing was written)\n", .{ composed.f.len, branch }) catch {};
        return .ok;
    }
    const message: []const u8 = early_message orelse blk: {
        const got = composeMessageInEditor(gpa, io, arena, root_dir, root_abs, streams, amb, cfg, parsed.editor, branch, if (is_root) "" else ck.version, change_lines) orelse return .failure;
        session.comment_file_used = true;
        break :blk got;
    };

    // 9c. submanifests §6.2 canonical tree construction, behind the §8.1 gate.
    //     Default OFF: the setting is `false` on every repository that has not
    //     been opted in by an operator act (`zit submanifest enable`), so this
    //     branch does not run and every check-in this verb mints keeps today's
    //     bytes exactly. §8.1 forbids enabling it on a repository that a peer
    //     unable to read trees serves: that peer would see a truncated check-in
    //     graph from the first tree on. What the branch owns is the library's storage
    //     contract: `subs` arrives in the order §6.2 requires ("Sub-manifest
    //     artifacts are stored before the manifest that references them"), so
    //     storing it front to back is the whole obligation — no heights, groups,
    //     or keys cross the boundary.
    var tree: ?artifact.TreeBuild = null;
    defer if (tree) |*t| t.deinit();
    var r_hex: [32]u8 = undefined;
    var r_card: ?artifact.RCard = null;
    const emission_decision = submanifestEmission(cfg);
    const emission_k: ?u4 = emission_decision.emission.treeK();
    reportSubmanifestOutOfRange(streams, emission_decision.emission);
    if (emission_k) |k| {
        // Stored by step 11, front to back, before the manifest.
        tree = buildFullTree(gpa, composed.f, k) catch return commitOom(streams);
    }

    // 9d. The R aggregate content checksum, EVERY shape (§6.3; Fossil emits it
    //     by default). Flat: over the manifest's own F run. Tree (§5.5): "the R
    //     card MUST be computed over the walk enumeration of Section 5.1 ...
    //     after which the computation of [FossilArtifact], Section 6.3.2 applies
    //     byte-for-byte unchanged" — and for a freshly constructed tree that
    //     enumeration is `composed.f` in order, the very list the construction
    //     partitioned. One computation serves both shapes.
    //
    //     The content comes from the LOG, keyed by the card's own hash, not
    //     from a second read of the working tree. R exists to detect an F run
    //     that disagrees with the content it names, so computing the two from
    //     different sources defeats it: a file edited between capture (step 8)
    //     and here would mint a check-in whose R card contradicts its own F
    //     hashes. Every entry is present — captured this commit or carried
    //     forward from the parent — so a miss is a corrupt repository, and it
    //     costs no extra working-tree I/O.
    //     Only when `repo-cksum` is on (Fossil's setting of the same name,
    //     off by default here): the aggregate reads every blob of the tree out
    //     of the store, which on a 68k-file tree is most of what a one-file
    //     commit costs.
    if (settings.repo_cksum) {
        var agg: artifact.ChecksumAggregator = .{};
        var r_computable = true;
        for (composed.f) |f| {
            const fhash = f.hash orelse return commitParentCorrupt(streams, "a parent F card carries no hash");
            var fdigest_buf: [digest_len]u8 = undefined;
            const fdigest = hexToDigest(fhash, &fdigest_buf) orelse return commitParentCorrupt(streams, "a parent F card names a blob in an undecodable form");
            // Captured this commit and not yet stored: the bytes are in hand.
            if (pending.get(fdigest)) |held| {
                agg.update(f.filename, held);
                continue;
            }
            const frid = log.lookup(fdigest) orelse {
                // Sparse-cone RFC section 4.3: over a SPARSE store an elided
                // carried-forward blob makes the aggregate uncomputable, and
                // the commit MUST omit R rather than fabricate or fail. The
                // absence must be the STORE cone's doing -- a dense store
                // missing a parent blob is still the corruption it always was.
                var probe = zit.repocache.readStoreCone(gpa, io, root_dir);
                if (probe) |*c| {
                    const covered = c.covers(f.filename);
                    c.deinit(gpa);
                    if (!covered) {
                        r_computable = false;
                        break;
                    }
                }
                return commitParentCorrupt(streams, "a parent F card names a blob this repository lacks");
            };
            const fbytes = (log.content(gpa, frid) catch |e| return commitContentFail(streams, e)) orelse
                return commitParentCorrupt(streams, "a parent F card's blob is unreadable");
            defer gpa.free(fbytes);
            agg.update(f.filename, fbytes);
        }
        if (r_computable) {
            r_card = .{ .checksum = agg.final(&r_hex) };
        }
    }

    // 9e. Dialect continuation: once this repository carries delta manifests
    //     (a fossil-imported history, or an earlier delta commit here), keep
    //     emitting them — a multi-megabyte flat manifest in a delta-dialect
    //     store changes the repository's shape and bloats it. The baseline is
    //     the parent when the parent is flat, or the parent's OWN baseline
    //     when it is a delta (§4.7.3: never a delta of a delta). Skipped for
    //     tree emission (§4.4: B and S never mix), for roots, when the
    //     parent's baseline is itself a delta (foreign history the writer
    //     must not extend), and whenever the patch would not be smaller than
    //     the flat F run.
    var delta_b: ?artifact.BCard = null;
    var delta_f: []const artifact.FCard = &.{};
    if (tree == null and !is_root) dialect: {
        const base = zit.compose.dialectBase(
            &pm.?,
            if (baseline_manifest) |*bm| bm else null,
            ck.version,
            pm.?.b != null or seenDeltaManifest(gpa, &log),
        ) orelse break :dialect;
        const patch = (zit.compose.deltaPatch(ma, composed.f, base) catch return commitOom(streams)) orelse break :dialect;
        delta_b = patch.b;
        delta_f = patch.f;
        // First delta authored HERE (parent-dialect fallback on a store whose
        // config predates the indicator): step 11 makes the memory durable
        // alongside it.
    }

    // 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: [23]u8 = undefined;
    const ts = cli.formatWriterTimestampMs(amb.now_epoch, amb.now_ms, &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);
    // The P card is Fossil's (checkin.c `create_manifest`): the primary parent,
    // then every pending merged check-in in the order it was merged, SP-joined
    // so `appendPCard` renders the tokens verbatim (B-merge-8; §4.7.13 /
    // repostate §3.2 first-listed-is-primary). A merge of the check-in itself
    // is no parent and is skipped, as Fossil skips it. With nothing merged
    // `parents == ck.version` and `count == 1`: today's bytes exactly.
    var parent_tokens: std.ArrayList(u8) = .empty;
    parent_tokens.appendSlice(ma, ck.version) catch return commitOom(streams);
    var parent_count: usize = 1;
    // Each cherrypick/backout mints a Q card (§4.7.14, B-merge-33): `Q +<rev>`
    // or `Q -<rev>`, baseline token OMITTED -- the omitted-baseline default IS
    // the primary parent the merge used. Fossil orders them by that signed
    // text, so '+' precedes '-'. The targets borrow `ck`, which outlives
    // `create`, exactly as the P card does.
    var q_list: std.ArrayList(artifact.QCard) = .empty;
    {
        var pit = checkout.pending(ck);
        while (pit.next()) |p| {
            if (std.mem.eql(u8, p.hash, ck.version)) continue;
            switch (p.kind) {
                .merge, .integrate => {
                    parent_tokens.append(ma, ' ') catch return commitOom(streams);
                    parent_tokens.appendSlice(ma, p.hash) catch return commitOom(streams);
                    parent_count += 1;
                },
                .cherrypick, .backout => q_list.append(ma, .{
                    .sign = if (p.kind == .cherrypick) .cherrypick else .backout,
                    .target = p.hash,
                    .baseline = null,
                }) catch return commitOom(streams),
            }
        }
    }
    std.mem.sort(artifact.QCard, q_list.items, {}, struct {
        fn lt(_: void, a: artifact.QCard, b: artifact.QCard) bool {
            if (a.sign != b.sign) return a.sign == .cherrypick;
            return std.mem.order(u8, a.target, b.target) == .lt;
        }
    }.lt);
    const child_parents = [_]artifact.PCard{.{
        .parents = parent_tokens.items,
        .count = parent_count,
    }};
    const q_slice: []const artifact.QCard = q_list.items;
    // Checkout-record agreement: a child's parent version resolved to a stored
    // manifest (its rid feeds the delta base and the P card); only a root has none.
    std.debug.assert(is_root or parent_manifest_rid != null);
    var m: artifact.Manifest = .{
        .arena_state = std.heap.ArenaAllocator.init(gpa),
        .kind = .manifest,
        .a = null,
        .b = delta_b,
        .c = .{ .comment = message },
        .d = .{ .timestamp = ts },
        .e = null,
        .g = null,
        .h = null,
        .i = null,
        .k = null,
        .l = null,
        .n = null,
        .r = r_card,
        .u = .{ .login = author },
        .z = null,
        .w = null,
        // submanifests §4.4: the file set is conveyed by the F run or the S run,
        // "never a mixture". With the gate off `tree` is null, so this is
        // `composed.f` and an empty S run — not one byte of difference.
        .f = if (tree != null) &.{} else if (delta_b != null) delta_f else composed.f,
        .j = &.{},
        .m = &.{},
        .p = if (is_root) &.{} else &child_parents,
        .q = q_slice,
        .s = if (tree) |t| t.s else &.{},
        .t = tags,
    };
    defer m.deinit(); // frees the empty arena_state; card storage is m_arena's
    const plain = artifact.create(&m, gpa) catch return commitOom(streams);
    defer gpa.free(plain);
    // `--sign`: clearsign the manifest through the operator's PGP
    // command and store the WRAPPED text as the artifact, fossil's own
    // behavior: the name hashes the wrapper too, readers strip it (§4.1.1)
    // to reach the cards, and the signature therefore survives every
    // byte-preserving path for free. The wrapped payload MUST strip back to
    // the exact input — a signer that rewrites the manifest (CRLF
    // normalization, dash-escaping a line, a charset filter) would sign
    // different bytes than the cards the reader interprets, so that is a
    // refusal, never a store.
    // The project's own pre-commit check, run BEFORE anything is minted
    // so a refusal costs nothing and leaves no artifact behind.
    switch (runBeforeCommit(gpa, io, arena, root_dir, streams, amb, cfg, parsed.no_checks)) {
        .ok => {},
        else => |e| return e,
    }

    const signing = settings.signing;
    // fossil's `clearsign` setting: sign every commit without the caller
    // asking. `--sign` on top of it is a no-op, not a doubling.
    const sign = parsed.sign or signing.clearsign;
    const bytes: []const u8 = if (!sign) plain else blk: {
        const wrapped = clearsignBytes(gpa, io, amb, root_dir, signing.pgp_command, plain) orelse
            return commitSignFail(streams);
        if (!std.mem.eql(u8, artifact.stripSignatureWrapper(wrapped), plain)) {
            gpa.free(wrapped);
            return commitSignFail(streams);
        }
        break :blk wrapped;
    };
    defer if (sign) gpa.free(@constCast(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. Publish, under the writer lock, taken again. First, what happened
    //     to the store since the snapshot. Unchanged: everything prepared
    //     still holds. Appended to: the parent may no longer be the tip, a
    //     `--branch` name may now be taken, and the config may have moved, so
    //     those are checked again, and a prepared check-in that no longer
    //     fits is refused, never re-parented: its bytes, maybe signed, name
    //     their parent. Rewritten (`pack`, `shun --force`): the rids the
    //     preparation holds no longer mean anything, so it is refused too.
    //     Every refusal writes nothing, and a comment from the editor is kept
    //     for `-M`.
    var store_append = cli.openStoreAppend(io, root_dir) catch |e| return commitLockFail(streams, e);
    var file_open = true;
    defer if (file_open) store_append.close(io);
    // The checkout must still be on the version this check-in was prepared
    // on. Another commit in this checkout advances it under this lock, and
    // publishing over that would overwrite its advance (even under
    // --allow-fork, which only lifts the fork guard).
    {
        var now_ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
        const now_ck = (checkout.read(io, root_dir, &now_ck_buf) catch |e|
            return checkoutFail(streams, "commit", e)) orelse
            return commitCheckoutMissing(streams);
        if (!std.mem.eql(u8, now_ck.version, ck.version)) {
            streams.err.writeAll("zit commit: another commit moved this checkout while this check-in was being prepared; nothing was written, run 'zit update' and commit again\n") catch {};
            return .failure;
        }
    }
    const pub_st = store_append.file.stat(io) catch return commitLogFail(streams, error.Storage);
    var pub_fs = storage.FileStorage.init(io, store_append.file, pub_st.size);
    const untouched = logstore.LogStore.validateTail(pub_fs.storageFile(), snap_key);
    if (!untouched and !logstore.LogStore.validatePrefix(pub_fs.storageFile(), snap_key)) {
        streams.err.writeAll("zit commit: the repository was rewritten (by pack or shun --force) while this check-in was being prepared; nothing was written, commit again\n") catch {};
        return .failure;
    }
    var wlog = logstore.LogStore.open(gpa, pub_fs.storageFile(), 0) catch |e|
        return commitLogFail(streams, e);
    var wlog_open = true;
    defer if (wlog_open) wlog.deinit(gpa);
    if (!untouched) {
        if (!is_root) switch (commitParentChecks(gpa, io, root_dir, streams, ma, parsed, branch, ck.version, false)) {
            .ok => |now| if (!sameNames(now.syms, parent_syms)) {
                streams.err.writeAll("zit commit: the parent check-in's branch tags changed while this check-in was being prepared; nothing was written, commit again\n") catch {};
                return .failure;
            },
            .refused => |rc| return rc,
        };
        if (wlog.config_offset != snap_config_offset) {
            var now_config: ?logstore.OwnedConfig = wlog.readConfig(gpa) catch null;
            defer if (now_config) |*c| c.deinit(gpa);
            const now_cfg: ?*const logstore.Config = if (now_config) |*c| &c.config else null;
            if (!CommitSettings.of(io, arena, root_dir, amb, now_cfg).eql(settings)) {
                streams.err.writeAll("zit commit: the repository's settings changed while this check-in was being prepared; nothing was written, commit again\n") catch {};
                return .failure;
            }
        }
    }
    // The prefix is intact, so every rid the preparation took (delta bases,
    // the parent manifest) names the same artifact here.
    for (pending.items.items) |it| {
        _ = wlog.putArtifact(&it.digest, it.bytes, it.base) catch |e| return commitLogFail(streams, e);
    }
    if (tree) |t| {
        // submanifests §6.2: sub-manifests are stored before the manifest
        // that references them, in the order `subs` arrives. No delta base:
        // a sub-manifest is content-addressed and shared across check-ins,
        // so there is no "same path in the parent" to delta against.
        for (t.subs) |sub| {
            var sdigest: [digest_len]u8 = undefined;
            std.crypto.hash.sha3.Sha3_256.hash(sub.bytes, &sdigest, .{});
            _ = wlog.putArtifact(&sdigest, sub.bytes, null) catch |e| return commitLogFail(streams, e);
        }
        // submanifests §8.1 — "When the first S-bearing artifact is stored,
        // an implementation SHOULD record a local seen-submanifest indicator
        // so operational surfaces can warn before the setting is enabled or
        // a pre-S client is granted access." The sync receive path already
        // does this at its own persist boundary (`persistStore`); this is the
        // other place S-bearing artifacts enter a log, and it is the one that
        // matters most — a repository whose own commits mint trees must arm
        // the §7.2 transfer gate even after the operator disables the setting
        // again, since §8.1's "Disabling ... cannot retire existing ones".
        // Written only on the false->true edge, so a steady-state enabled
        // repository appends no extra config frame per commit.
        setSeenSubmanifest(gpa, &wlog) catch |e| return commitLogFail(streams, e);
    }
    if (delta_b != null) setSeenDelta(gpa, &wlog) catch |e| return commitLogFail(streams, e);
    // The manifest itself (B-commit-15 order: last, then the fsync). 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 its skip base
    // (`skipBaseOf`), so reading any check-in walks popcount(height) frames
    // and no manifest past the root is stored whole; when that base is
    // unusable, against the primary parent or whatever best-of-N finds, else
    // a full §4.1 container. The reported name is the 64-hex of the
    // UNCOMPRESSED manifest, so delta/compression is address-transparent.
    // The base is named by hash: the prefix is intact, so it resolves here.
    const skip_base_rid: ?logstore.Rid = if (skip_base) |name| blk: {
        var sdigest_buf: [digest_len]u8 = undefined;
        const sdigest = hexToDigest(name, &sdigest_buf) orelse break :blk null;
        break :blk wlog.lookup(sdigest);
    } else null;
    _ = wlog.putArtifactSkipBase(&mdigest, bytes, skip_base_rid, parent_manifest_rid) catch |e| return commitLogFail(streams, e);
    wlog.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.items.len != 0) {
        for (carried.items) |new| set.clearRename(new);
        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).
    // Every pending merge operation is consumed by this check-in, so the
    // advanced checkout clears them all (B-merge-9/34 one-shot clear).
    {
        var post_ck_buf: [checkout.max_ck_payload]u8 = undefined;
        const post_ck = checkout.encodeCk(&post_ck_buf, .{ .version = manifest_name, .branch = target_branch, .merge_parent = "", .special_op = "", .manifest_flags = "" });
        checkout.updateSections(io, root_dir, &.{
            .{ .tag = .checkout, .payload = post_ck },
            // The overlay is consumed by this check-in exactly as the pending
            // merge is: one-shot, cleared in the same splice.
            .{ .tag = .merge_overlay, .payload = null },
        }) catch return commitCheckoutWriteFail(streams);
    }

    // The advance above was made under the store lock, so the next commit in
    // this checkout sees it when it publishes. The append is durable; release
    // the lock before the steps that reopen the store themselves (the
    // --integrate closes, autosync's push, the §6.4 advisory's retune write),
    // and a second writer open in the same process is refused while this one
    // holds the lock.
    wlog.deinit(gpa);
    wlog_open = false;
    store_append.close(io);
    file_open = false;

    // --integrate: the check-in is durable, so close each merged-in leaf
    // with the same control artifact `branch close` mints. A failure here
    // leaves the check-in standing and says what to run by hand.
    var integrated = checkout.pending(ck);
    while (integrated.next()) |p| {
        if (p.kind != .integrate) continue;
        const close_tags = cli.composeTagCards(ma, p.hash, .{ .sign = .add, .name = "closed", .raw = true, .value = null }) catch return commitOom(streams);
        var cname_buf: [64]u8 = undefined;
        if (mintControlArtifact(gpa, io, root_dir, amb, close_tags, &cname_buf)) |_| {
            streams.out.print("closed {s} (integrated)\n", .{p.hash[0..@min(p.hash.len, 12)]}) catch {};
        } else |_| {
            streams.err.print("zit commit: the merged branch was not closed; run 'zit branch close {s}'\n", .{p.hash[0..@min(p.hash.len, 12)]}) catch {};
        }
    }

    // 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 {};
        commitReceipt(streams, change_lines, content_notes.items);
    }

    // 13b. Autosync push: the new check-in reaches the saved remote
    //      immediately, fossil's collaboration default. Strictly after the
    //      success line — the local commit is already true — and void like the
    //      advisory below: no autosync outcome can change this verb's exit.
    if (!parsed.no_sync) cmd_sync.autosyncPush(gpa, io, arena, streams, "commit", amb);

    // 14. submanifests §6.4 post-commit drift advisory — strictly after the
    //     check-in line above, never before it and never interleaved with the
    //     commit itself: `commitSubmanifestAdvice` returns void, so it is
    //     structurally incapable of changing this verb's exit code.
    commitSubmanifestAdvice(
        gpa,
        io,
        root_dir,
        streams,
        composed.f,
        emission_k,
        emission_decision.settled_cost_shape,
        emission_decision.auto_retune,
        parsed.no_submanifest_advice,
    );
    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;
}

/// draft-fossil-submanifests-00 §6.4's post-commit drift advisory: a re-tune
/// "MUST be manual and operator-initiated unless automatic re-tuning is
/// authorized below", and "A writer MAY re-tune automatically only while the
/// repository's submanifest-auto-retune setting -- a project-scope boolean,
/// default false -- is true ... setting it true is the durable
/// project-operator act authorizing subsequent automatic re-tunes." With
/// `auto_retune` false — the config field's own default, so every repository
/// predating this slice reads it as such — the two arms below are
/// byte-identical to the manual-only path: the pin moves only after an
/// explicit 'y' typed at the prompt, never automatically.
///
/// Called from `runCommit` exactly once, strictly after the check-in is
/// durably recorded (never before, never interleaved with it) — `void` return
/// makes it structurally impossible for anything here to change the commit's
/// own exit code. Any failure along the way (allocator failure, a failed prompt
/// read, a failed write) simply stops and prints nothing further: the commit
/// already succeeded, and a broken advisory is not worth confusing that success.
///
/// `pinned_k` is `runCommit`'s own `emission_k` — the same `.treeK()`-derived
/// "enabled AND pinned-in-range" value step 9c already computed for the tree
/// build, so a repository that never turned submanifests on (`pinned_k ==
/// null`) reaches here and returns immediately, at zero added cost: no config
/// read, no `driftCheck` scan, no output (requirement 1). `no_advice` is
/// `--no-submanifest-advice`; when set, step 3 onward (the `driftCheck` scan
/// itself included) never runs (requirement 2), regardless of `auto_retune` —
/// an explicit per-commit "say nothing" wins over the durable opt-in.
/// `auto_retune` is `runCommit`'s own `emission_decision.auto_retune`, read
/// from the same config frame `pinned_k` was derived from.
fn commitSubmanifestAdvice(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    entries: []const artifact.FCard,
    pinned_k: ?u4,
    settled_cost_shape: ?[32]u8,
    auto_retune: bool,
    no_advice: bool,
) void {
    if (no_advice) return;
    const k = pinned_k orelse return;

    // `entries` is `runCommit`'s exact canonical final F-set: §6.4 advice runs
    // after durability, but it must not reopen/flatten the checkout merely to
    // rediscover the same §6.2 tree input.
    const shape = submanifestCostShapeCheck(entries, settled_cost_shape);
    if (shape.settled) return;
    const drift = (zit.submanifest.driftCheck(gpa, entries, k, .sha3_256) catch return) orelse {
        _ = submanifestWrite(
            gpa,
            io,
            root_dir,
            null,
            null,
            replaceSettledCostShape(shape.digest),
            streams,
        );
        return;
    };

    // §6.4's advisory line — exact wording, one line, stdout. Printed
    // regardless of `auto_retune`: §6.4's automatic path still advises, it
    // just skips the prompt that would otherwise gate the write.
    streams.out.print(
        "submanifest-k has drifted from {d} to {d} ({d:.1}% read-cost improvement)\n",
        .{ k, drift.recommended.k, drift.margin_pct },
    ) catch return;

    if (auto_retune) {
        if (!submanifestWrite(
            gpa,
            io,
            root_dir,
            null,
            drift.recommended.k,
            replaceSettledCostShape(shape.digest),
            streams,
        )) return;
        streams.out.print("submanifest-k: {d} -> {d}\n", .{ k, drift.recommended.k }) catch {};
        streams.out.writeAll(
            "note: the next commit shares only the sub-manifests whose bytes are unchanged under\n" ++
                "the new k: all, some or none. No history is rewritten and no reader behaves differently.\n",
        ) catch {};
        return;
    }

    if (!promptRetune(streams)) return;
    if (!submanifestWrite(
        gpa,
        io,
        root_dir,
        null,
        drift.recommended.k,
        replaceSettledCostShape(shape.digest),
        streams,
    )) return;
    streams.out.print("submanifest-k: {d} -> {d}\n", .{ k, drift.recommended.k }) catch {};
    streams.out.writeAll(
        "note: the next commit shares only the sub-manifests whose bytes are unchanged under\n" ++
            "the new k: all, some or none. No history is rewritten and no reader behaves differently.\n",
    ) catch {};
}

const SubmanifestCostShapeCheck = struct {
    digest: [32]u8,
    settled: bool,
};

/// Internal cache decision only: §6.4 still governs advisory timing and output.
/// It needs only the already-composed F-set, never a repository read.
fn submanifestCostShapeCheck(
    entries: []const artifact.FCard,
    settled_cost_shape: ?[32]u8,
) SubmanifestCostShapeCheck {
    var digest: [32]u8 = undefined;
    const current = zit.submanifest.costShapeDigest(entries, &digest);
    return .{
        .digest = digest,
        .settled = if (settled_cost_shape) |cached| std.mem.eql(u8, cached[0..], current) else false,
    };
}

test "commit submanifest advice §6.4: settled equal shape needs no repository read" {
    const entries = [_]artifact.FCard{
        .{ .filename = "a", .hash = null, .perm = null, .old_name = null, .mode = .regular },
        .{ .filename = "b", .hash = null, .perm = null, .old_name = null, .mode = .regular },
    };
    const initial = submanifestCostShapeCheck(&entries, null);
    const cached = submanifestCostShapeCheck(&entries, initial.digest);
    try std.testing.expect(cached.settled);
}

/// The §6.4 drift-advisory confirm prompt: `retune now? [y/N] ` on stderr
/// (the same stream `readPasswordNoEcho` prompts on, `cmd/sync.zig`), one line
/// read from stdin, true only when its first byte is `y`/`Y`.
///
/// `tcgetattr(STDIN_FILENO)` success/failure is the sole interactivity signal,
/// checked BEFORE printing anything — matching `readPasswordNoEcho`'s own
/// precedent for "is this interactive" rather than inventing a second one for
/// this single call site. On a non-terminal stdin (every automated gate) this
/// returns false without printing the prompt or attempting a read, which is
/// what makes the non-interactive/advisory-only path exercised by ordinary
/// commit tests for free.
///
/// Not exercised by the automated gates (they never run against a real tty)
/// — this is the interactive path, same honesty `readPasswordNoEcho`'s own
/// doc comment states about itself.
fn promptRetune(streams: cli.Streams) bool {
    const fd = std.posix.STDIN_FILENO;
    _ = std.posix.tcgetattr(fd) catch return false;
    streams.err.writeAll("retune now? [y/N] ") catch return false;
    streams.err.flush() catch return false;
    var buf: [8]u8 = undefined;
    const n = std.posix.read(fd, &buf) catch return false;
    if (n == 0) return false;
    return buf[0] == 'y' or buf[0] == 'Y';
}

/// Bound on what a `before-commit` check may print. Generous -- a failing test
/// run is exactly when an operator wants the whole output -- but finite,
/// because an unbounded child could otherwise hold the commit open forever.
const max_check_output: usize = 8 * 1024 * 1024;

/// Run the project's `before-commit` check, if there is one this
/// checkout has agreed to run.
///
/// Ordering matters: this runs before the manifest is composed, so a refusal
/// mints nothing and the failed commit leaves the repository exactly as it was.
///
/// The three outcomes an operator can meet:
///   * no declaration, or one they wrote here -> run it (or nothing);
///   * a versioned declaration they have not accepted -> REFUSE, with the
///     command printed and the one command that accepts it;
///   * a versioned declaration that CHANGED since they accepted it -> refuse
///     and say so, because that is the case where a pull may have edited a
///     script they already agreed to run.
///
/// Refusing rather than warning is the deliberate choice. A warning lets an
/// operator believe they are gated when they are not, and "I thought the tests
/// ran" is a worse failure than "I had to type one command once".
fn runBeforeCommit(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    amb: cli.Ambient,
    cfg: ?*const logstore.Config,
    skip: bool,
) cli.Exit {
    const resolved = cmd_sync.localSetting(io, arena, root_dir, .{ .environ = amb.environ }, cfg, .before_commit) catch
        return .ok; // unreadable settings must not invent a check
    if (resolved.value.len == 0) return .ok;

    if (skip) {
        // Loud on purpose, and it names the command that did not run: a silent
        // bypass is how `--no-verify` became a habit rather than a decision.
        streams.err.print(
            "zit commit: --no-checks: SKIPPING before-commit: {s}\n",
            .{resolved.value},
        ) catch {};
        return .ok;
    }

    // The trust record is a field of the frame the caller is holding,
    // so it is read from there rather than re-opening the store (`trustRecord`
    // stays for `zit trust`, which has no frame in hand). A null frame is a
    // repository whose config could not be read at all: no stored acceptance.
    const stored: []const u8 = if (cfg) |c| c.before_commit_trust else "";
    switch (zit.settings.trustVerdict(resolved.value, resolved.source, stored)) {
        .none => return .ok,
        .self_authored, .trusted => {},
        .untrusted => {
            streams.err.print(
                "zit commit: this repository ships a before-commit check that has not been accepted here:\n  {s}\n",
                .{resolved.value},
            ) catch {};
            streams.err.writeAll("read it, then run 'zit trust --yes' to accept it (or 'zit commit --no-checks' to skip once)\n") catch {};
            return .failure;
        },
        .changed => {
            streams.err.print(
                "zit commit: the before-commit check CHANGED since you accepted it:\n  {s}\n",
                .{resolved.value},
            ) catch {};
            streams.err.writeAll("re-read it, then run 'zit trust --yes' to accept the new text\n") catch {};
            return .failure;
        },
    }

    // Run it against THIS worktree, through a shell so a pipeline works --
    // which is the whole use case (`zig fmt --check src && zig build test`).
    // The command was explicitly trusted, so the shell is not a new exposure.
    var env_map = amb.environ.createMap(gpa) catch {
        streams.err.writeAll("zit commit: out of memory preparing before-commit\n") catch {};
        return .failure;
    };
    defer env_map.deinit();
    const result = std.process.run(gpa, io, .{
        .argv = &.{ "/bin/sh", "-c", resolved.value },
        .cwd = .{ .dir = root_dir },
        .environ_map = &env_map,
        .stdout_limit = .limited(max_check_output),
    }) catch {
        streams.err.print("zit commit: before-commit could not be run: {s}\n", .{resolved.value}) catch {};
        return .failure;
    };
    defer gpa.free(result.stdout);
    defer gpa.free(result.stderr);
    const failed = switch (result.term) {
        .exited => |code| code != 0,
        else => true, // signalled or stopped is not success
    };
    // The check's OWN diagnostics are what an operator needs to fix the commit,
    // so they are relayed verbatim rather than summarised -- and on success too,
    // because a check that prints a warning has something to say either way.
    if (result.stdout.len != 0) streams.out.writeAll(result.stdout) catch {};
    if (result.stderr.len != 0) streams.err.writeAll(result.stderr) catch {};
    if (failed) {
        streams.err.writeAll("zit commit: before-commit failed; nothing was committed\n") catch {};
        return .failure;
    }
    return .ok;
}

/// 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.
/// Clearsign `plain` through the operator's signing command, fossil's
/// `clearsign()` contract byte for byte (fossil src/clearsign.c), so a
/// `pgp-command` value that works there works here verbatim:
///
///   * the command is `$ZIT_PGP_COMMAND`, else the repository's stored
///     `pgp-command` setting, else `gpg --clearsign -o ` (fossil's own
///     default, trailing space included);
///   * it is invoked as `COMMAND OUTFILE INFILE` — the `-o ` in the default
///     binds OUTFILE, and the manifest arrives as the positional INFILE;
///   * a command whose basename starts with `ssh` is the DETACHED case
///     (2025: ssh cannot make a non-detached signature): it is invoked as
///     `COMMAND INFILE`, writes `INFILE.sig`, and the armor is assembled
///     here — `-----BEGIN SSH SIGNED MESSAGE-----` + blank line + manifest
///     + the detached signature, exactly fossil's assembly;
///   * a false-ish command (`off`/`no`/`0`/`false`) means "do not sign".
///
/// Returns the wrapped bytes (caller frees), or null on any failure. `null`
/// is the SIGNING FAILURE signal; whether that aborts the commit is the
/// caller's policy, not this function's.
fn clearsignBytes(
    gpa: std.mem.Allocator,
    io: std.Io,
    amb: cli.Ambient,
    root_dir: std.Io.Dir,
    stored_command: []const u8,
    plain: []const u8,
) ?[]u8 {
    // Precedence, widest scope last: the environment overrides the repository's
    // stored `pgp-command`, which overrides fossil's built-in default. That is
    // fossil's own order — an operator must be able to redirect one invocation
    // without editing the repository.
    const command: []const u8 = amb.environ.getPosix("ZIT_PGP_COMMAND") orelse
        if (stored_command.len != 0) stored_command else "gpg --clearsign -o ";
    if (isFalseSetting(command)) return null;
    const ssh_style = std.mem.startsWith(u8, commandBasename(command), "ssh");

    const in_name = ".zit-tmp-sign-in";
    const out_name = ".zit-tmp-sign-out";
    const sig_name = ".zit-tmp-sign-in.sig"; // ssh writes INFILE.sig
    {
        var f = root_dir.createFile(io, in_name, .{ .truncate = true }) catch return null;
        defer f.close(io);
        f.writePositionalAll(io, plain, 0) catch {
            root_dir.deleteFile(io, in_name) catch {};
            return null;
        };
    }
    defer {
        root_dir.deleteFile(io, in_name) catch {};
        root_dir.deleteFile(io, out_name) catch {};
        root_dir.deleteFile(io, sig_name) catch {};
    }

    var abs_buf: [std.fs.max_path_bytes]u8 = undefined;
    const abs_len = root_dir.realPath(io, &abs_buf) catch return null;
    const root_abs = abs_buf[0..abs_len];

    // Fossil interpolates the file names straight into the shell command, and
    // so does this — but the names are OURS (fixed literals under a resolved
    // root), never operator input, so there is nothing here for a quoted
    // path to protect against that single-quoting does not already cover.
    const script = if (ssh_style)
        std.fmt.allocPrint(gpa, "{s} '{s}/{s}'", .{ command, root_abs, in_name }) catch return null
    else
        std.fmt.allocPrint(gpa, "{s} '{s}/{s}' '{s}/{s}'", .{ command, root_abs, out_name, root_abs, in_name }) catch return null;
    defer gpa.free(script);

    var env_map = amb.environ.createMap(gpa) catch return null;
    defer env_map.deinit();
    const result = std.process.run(gpa, io, .{
        .argv = &.{ "/bin/sh", "-c", script },
        .environ_map = &env_map,
        .stdout_limit = .limited(max_signature_bytes),
    }) catch return null;
    gpa.free(result.stdout);
    gpa.free(result.stderr);
    switch (result.term) {
        .exited => |c| if (c != 0) return null,
        else => return null,
    }

    if (!ssh_style) {
        return root_dir.readFileAlloc(io, out_name, gpa, .limited(max_signature_bytes)) catch null;
    }

    // SSH: assemble what ssh-keygen will not. Fossil's exact layout — armor
    // line, ONE blank line (no `Hash:` header), the manifest verbatim, then
    // the already-armored detached signature.
    const sig = root_dir.readFileAlloc(io, sig_name, gpa, .limited(max_signature_bytes)) catch return null;
    defer gpa.free(sig);
    var out: std.ArrayListUnmanaged(u8) = .empty;
    errdefer out.deinit(gpa);
    out.appendSlice(gpa, "-----BEGIN SSH SIGNED MESSAGE-----\n\n") catch return null;
    out.appendSlice(gpa, plain) catch return null;
    out.appendSlice(gpa, sig) catch return null;
    return out.toOwnedSlice(gpa) catch null;
}

/// One signature's ceiling: a manifest plus armor, never a payload channel.
const max_signature_bytes: usize = 8 * 1024 * 1024;

/// Fossil's `is_false()` over a setting value: the spellings that mean
/// "disabled". Anything else is a command to run.
fn isFalseSetting(v: []const u8) bool {
    const off = [_][]const u8{ "off", "no", "false", "0" };
    for (off) |o| if (std.ascii.eqlIgnoreCase(v, o)) return true;
    return false;
}

/// The command word's basename — fossil's `command_basename()`, used only to
/// spot the `ssh*` family. Reads up to the first space, then after the last
/// path separator.
fn commandBasename(command: []const u8) []const u8 {
    const word_end = std.mem.indexOfScalar(u8, command, ' ') orelse command.len;
    const word = command[0..word_end];
    const slash = std.mem.lastIndexOfScalar(u8, word, '/') orelse return word;
    return word[slash + 1 ..];
}

/// Renders the signing refusal: the signer failed, or its output does
/// not strip back to the exact manifest it was given.
fn commitSignFail(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit commit: --sign failed: the clearsign command errored or altered the manifest (set ZIT_PGP_COMMAND to override 'gpg --clearsign')\n") catch {};
    return .failure;
}

/// The writer lock or the store could not be opened. A busy lock has already
/// said who holds it and what to do.
fn commitLockFail(s: cli.Streams, err: anyerror) cli.Exit {
    if (err == error.StoreBusy) return .failure;
    return commitLogFail(s, error.Storage);
}

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.
///
/// `why` names WHICH step failed. Every one of these used to print the same
/// sentence, so a name this build could not decode, a parent absent from the
/// log, and genuine damage were indistinguishable at the CLI -- which is how
/// `zit verify` could report a store clean while `commit` called its parent
/// corrupt, with no way to tell from the outside which one was wrong.
fn commitParentCorrupt(s: cli.Streams, why: []const u8) cli.Exit {
    s.err.print("zit commit: the parent check-in is corrupt ({s})\n", .{why}) 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 tracked file too large for one artifact frame. States the actual size and
/// the limit, because the operator's next question is "by how much" — and says
/// the limit is the repository format's, so it does not read as a setting they
/// should go looking for.
fn commitTooLarge(s: cli.Streams, path: []const u8, size: u64) cli.Exit {
    s.err.print(
        "zit commit: cannot commit '{s}': {d} bytes exceeds the {d}-byte limit on one file\n",
        .{ path, size, cmd_tracking.max_tracked_file_bytes },
    ) catch {};
    s.err.print("zit commit: that limit is the repository format's artifact size, not a setting\n", .{}) catch {};
    return .failure;
}

/// The file's content is a class this repository has not accepted. Names
/// the file, what it is, and BOTH ways forward: the durable one (record the
/// glob, which then applies to every clone) and the one-off waiver. Refusing
/// with only "use --no-warnings" would train the reflex that discards the check.
fn commitContentClass(s: cli.Streams, path: []const u8, fault: ContentFault) cli.Exit {
    s.err.print("zit commit: refusing '{s}': it {s}\n", .{ path, fault.describe() }) catch {};
    s.err.print(
        "zit commit: accept it for good with 'zit settings {s} \"{s}\"' (a tracked .zit-settings/{s} applies to every clone), or once with --no-checks\n",
        .{ fault.glob(), path, fault.glob() },
    ) 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;
}

/// Captures a mapper's stderr into a fixed buffer and returns (exit, bytes).
pub 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-checkout 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 (not present in this repository)\n",
        commitMapCapture(commitParentCorrupt, .{"not present in this repository"}).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 "commit: ContentPolicy classifies binary before crlf, and a glob permits each" {
    // Ordering matters: a binary file usually also contains CR/LF, and naming
    // it "binary" is the diagnostic the operator can act on.
    const both = "a\x00b\r\n";
    // Undeclared is no opinion: a repository that never asked keeps committing
    // binary content exactly as before. This is the whole opt-in rule.
    const silent: ContentPolicy = .{};
    try std.testing.expectEqual(@as(?ContentFault, null), silent.fault("x.dat", both));

    // Declared: binary first, since a binary file usually also has CR/LF.
    const declared: ContentPolicy = .{ .binary_glob = "*.ok", .crlf_glob = "*.ok" };
    try std.testing.expectEqual(ContentFault.binary, declared.fault("x.dat", both).?);
    try std.testing.expectEqual(ContentFault.crlf, declared.fault("x.txt", "a\r\nb").?);
    try std.testing.expectEqual(@as(?ContentFault, null), declared.fault("x.txt", "plain\n"));

    // Each glob permits only its own class, and only its own paths.
    const bin_ok: ContentPolicy = .{ .binary_glob = "*.dat" };
    try std.testing.expectEqual(@as(?ContentFault, null), bin_ok.fault("x.dat", "a\x00b"));
    try std.testing.expectEqual(ContentFault.binary, bin_ok.fault("x.bin", "a\x00b").?);
    // Declaring only binary-glob leaves CR/LF undeclared, hence unchecked.
    try std.testing.expectEqual(@as(?ContentFault, null), bin_ok.fault("x.dat", "a\r\nb"));

    const crlf_ok: ContentPolicy = .{ .crlf_glob = "*.txt" };
    try std.testing.expectEqual(@as(?ContentFault, null), crlf_ok.fault("x.txt", "a\r\nb"));
    // crlf-glob alone leaves the binary class undeclared, so it stays silent.
    try std.testing.expectEqual(@as(?ContentFault, null), crlf_ok.fault("x.bin", "a\x00b"));

    // --no-checks waives everything, which is the only way past a class with
    // no glob — and is deliberately one flag, not one per class.
    const waived: ContentPolicy = .{ .binary_glob = "*.ok", .crlf_glob = "*.ok", .waived = true };
    try std.testing.expectEqual(@as(?ContentFault, null), waived.fault("x.bin", both));
}

test "encoding-glob gates UTF-16 and invalid UTF-8, and binary-glob stops claiming UTF-16" {
    const utf16 = "\xFF\xFEa\x00b\x00";
    const utf16_crlf = "\xFF\xFE\x0D\x00\x0A\x00";
    const bad_utf8 = "hello \xC3\x28 there";

    // Opt-in, as for every other class: with no encoding-glob declared the
    // repository has no opinion and nothing is refused.
    const silent: ContentPolicy = .{};
    try std.testing.expectEqual(@as(?ContentFault, null), silent.fault("x.txt", utf16));
    try std.testing.expectEqual(@as(?ContentFault, null), silent.fault("x.txt", bad_utf8));

    // Declared: only the named paths may carry either encoding class.
    const enc: ContentPolicy = .{ .encoding_glob = "*.bin" };
    try std.testing.expectEqual(ContentFault.unicode, enc.fault("x.txt", utf16).?);
    try std.testing.expectEqual(ContentFault.invalid_utf8, enc.fault("x.txt", bad_utf8).?);
    try std.testing.expectEqual(@as(?ContentFault, null), enc.fault("x.bin", utf16));
    try std.testing.expectEqual(@as(?ContentFault, null), enc.fault("x.bin", bad_utf8));
    // `*` is how a project turns the whole check back off.
    const off: ContentPolicy = .{ .encoding_glob = "*" };
    try std.testing.expectEqual(@as(?ContentFault, null), off.fault("x.txt", utf16));

    // fossil: Unicode WITH CR is exempt only when both globs permit the file
    // (checkin.c's "crlf-glob and encoding-glob settings" branch).
    const both: ContentPolicy = .{ .encoding_glob = "*.ok", .crlf_glob = "*.ok" };
    try std.testing.expectEqual(@as(?ContentFault, null), both.fault("x.ok", utf16_crlf));
    try std.testing.expectEqual(ContentFault.unicode, both.fault("x.txt", utf16_crlf).?);
    const crlf_only: ContentPolicy = .{ .encoding_glob = "*.txt", .crlf_glob = "*.ok" };
    try std.testing.expectEqual(ContentFault.crlf, crlf_only.fault("x.txt", utf16_crlf).?);
    // ...but invalid UTF-8 with CR/LF is exempt on encoding-glob ALONE: fossil's
    // `fHasInvalidUtf8` branch returns before crlf-glob is consulted, so
    // `fossil commit` accepts this Latin-1 file where zit once refused it.
    const latin1_crlf = "caf\xE9 latin-1\r\nline two\r\n";
    try std.testing.expectEqual(@as(?ContentFault, null), crlf_only.fault("x.txt", latin1_crlf));
    try std.testing.expectEqual(ContentFault.invalid_utf8, crlf_only.fault("x.ok", latin1_crlf).?);
    try std.testing.expectEqual(@as(?ContentFault, null), crlf_only.undeclared(latin1_crlf));

    // A UTF-16 file is NOT binary. Before this it tripped
    // binary-glob on the zero bytes inside its units, which is a class fossil
    // never puts it in.
    const bin: ContentPolicy = .{ .binary_glob = "*.dat" };
    try std.testing.expectEqual(@as(?ContentFault, null), bin.fault("x.txt", utf16));
    // NUL still wins over encoding when the units really are zero.
    const bin_enc: ContentPolicy = .{ .binary_glob = "*.dat", .encoding_glob = "*.dat" };
    try std.testing.expectEqual(ContentFault.binary, bin_enc.fault("x.txt", "\xFF\xFEa\x00\x00\x00").?);

    // One waiver for every class, as before.
    const waived: ContentPolicy = .{ .encoding_glob = "*.ok", .waived = true };
    try std.testing.expectEqual(@as(?ContentFault, null), waived.fault("x.txt", utf16));

    // The receipt half: an undeclared class is said, never refused.
    try std.testing.expectEqual(ContentFault.unicode, silent.undeclared(utf16).?);
    try std.testing.expectEqual(ContentFault.invalid_utf8, silent.undeclared(bad_utf8).?);
    try std.testing.expectEqual(@as(?ContentFault, null), enc.undeclared(utf16));
}

test "binary wins over encoding whether or not binary-glob is declared" {
    // fossil decides the binary class FIRST and returns from that branch
    // (checkin.c `commit_warning`): a blob with a NUL is never reported as an
    // encoding or a CR/LF fault, and only `binary-glob` can exempt it. The
    // opt-in model keeps that ordering: with the binary class undeclared a
    // binary blob passes with a receipt note, it does not fall through to the
    // encoding rows and get refused under the wrong glob.
    const png = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\xFF\xFE\x01";
    const wide_nul = "\xFF\xFE\x0D\x00\x00\x00";

    // encoding-glob alone: a PNG is not this project's business, so it goes in.
    const enc_only: ContentPolicy = .{ .encoding_glob = "*.txt" };
    try std.testing.expectEqual(@as(?ContentFault, null), enc_only.fault("pic.png", png));
    try std.testing.expectEqual(@as(?ContentFault, null), enc_only.fault("wide.png", wide_nul));
    // ... and the receipt says "binary", the class it is actually in.
    try std.testing.expectEqual(ContentFault.binary, enc_only.undeclared(png).?);
    try std.testing.expectEqual(ContentFault.binary, enc_only.undeclared(wide_nul).?);

    // crlf-glob alone is the same story: a binary blob full of CR/LF pairs is
    // binary, not a line-ending problem.
    const crlf_only: ContentPolicy = .{ .crlf_glob = "*.txt" };
    try std.testing.expectEqual(@as(?ContentFault, null), crlf_only.fault("pic.png", png));

    // Declared and matched: fossil returns 0 from the binary branch, so no
    // later class is consulted for the file at all.
    const bin_ok: ContentPolicy = .{ .binary_glob = "*.png", .crlf_glob = "*.txt", .encoding_glob = "*.txt" };
    try std.testing.expectEqual(@as(?ContentFault, null), bin_ok.fault("pic.png", png));
    try std.testing.expectEqual(@as(?ContentFault, null), bin_ok.undeclared(png));
    // Declared and unmatched: refused as binary, never as an encoding fault.
    try std.testing.expectEqual(ContentFault.binary, bin_ok.fault("pic.dat", png).?);
}

/// One line of the commit template / dry run: the composed file set
/// against the parent's, in Fossil's words.
const ChangeLine = struct { word: []const u8, path: []const u8 };

/// The stderr receipt under the check-in line: what went in, then every
/// binary or CRLF file no glob declared (what Fossil prompts about).
fn commitReceipt(streams: cli.Streams, lines: []const ChangeLine, notes: []const ContentNote) void {
    const e = streams.err;
    if (lines.len == 1) {
        e.print("{s} {s}\n", .{ lines[0].path, changeWordLower(lines[0].word) }) catch {};
    } else if (lines.len != 0) {
        var counts = [3]usize{ 0, 0, 0 };
        for (lines) |l| counts[changeWordIndex(l.word)] += 1;
        e.print("{d} files:", .{lines.len}) catch {};
        var sep: []const u8 = " ";
        for (counts, [3][]const u8{ "added", "edited", "deleted" }) |c, w| {
            if (c == 0) continue;
            e.print("{s}{d} {s}", .{ sep, c, w }) catch {};
            sep = ", ";
        }
        e.writeAll("\n") catch {};
    }
    for (notes) |note| switch (note.fault) {
        .binary => e.print("note: {s} is binary ({d} bytes); declare binaries with 'zit settings binary-glob'\n", .{ note.path, note.size }) catch {},
        .unicode => e.print("note: {s} is UTF-16 (Unicode); declare its encoding with 'zit settings encoding-glob'\n", .{note.path}) catch {},
        .invalid_utf8 => e.print("note: {s} is not valid UTF-8; declare its encoding with 'zit settings encoding-glob'\n", .{note.path}) catch {},
        .crlf => e.print("note: {s} has CRLF line endings; declare them with 'zit settings crlf-glob'\n", .{note.path}) catch {},
    };
}

fn changeWordIndex(word: []const u8) usize {
    if (std.mem.eql(u8, word, "ADDED")) return 0;
    if (std.mem.eql(u8, word, "EDITED")) return 1;
    return 2;
}

fn changeWordLower(word: []const u8) []const u8 {
    return ([3][]const u8{ "added", "edited", "deleted" })[changeWordIndex(word)];
}

fn commitChangeLines(arena: std.mem.Allocator, parent: []const artifact.FCard, child: []const artifact.FCard) error{OutOfMemory}![]const ChangeLine {
    var lines: std.ArrayList(ChangeLine) = .empty;
    var i: usize = 0;
    var j: usize = 0;
    while (i < parent.len or j < child.len) {
        if (j >= child.len or (i < parent.len and std.mem.order(u8, parent[i].filename, child[j].filename) == .lt)) {
            try lines.append(arena, .{ .word = "DELETED", .path = parent[i].filename });
            i += 1;
        } else if (i >= parent.len or std.mem.order(u8, parent[i].filename, child[j].filename) == .gt) {
            try lines.append(arena, .{ .word = "ADDED", .path = child[j].filename });
            j += 1;
        } else {
            const same = std.mem.eql(u8, parent[i].hash orelse "", child[j].hash orelse "") and parent[i].mode == child[j].mode;
            if (!same) try lines.append(arena, .{ .word = "EDITED", .path = child[j].filename });
            i += 1;
            j += 1;
        }
    }
    return lines.items;
}

/// `-M FILE`: the file's bytes, or null when it cannot be read.
fn readMessageFile(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, path: []const u8) ?[]const u8 {
    const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)) catch return null;
    defer gpa.free(bytes);
    return arena.dupe(u8, bytes) catch null;
}

/// Compose the comment in an editor. The template is written to
/// `.zit-ci-comment` in the checkout root: a blank line for the comment,
/// then `#` lines naming the branch, the parent and every file this commit
/// captures — stripped on the way back, so a comment can never carry them.
/// The editor is `--editor`, else $VISUAL, else $EDITOR; it runs with the
/// terminal inherited, as `sh -c 'EDITOR "$1"'`. An empty result aborts, and
/// the file stays for `-M`.
fn composeMessageInEditor(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    root_abs: []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    cfg: ?*const logstore.Config,
    editor_override: ?[]const u8,
    branch: []const u8,
    parent: []const u8,
    lines: []const ChangeLine,
) ?[]const u8 {
    var env_map = amb.environ.createMap(gpa) catch {
        streams.err.writeAll("zit commit: out of memory\n") catch {};
        return null;
    };
    defer env_map.deinit();
    // The `editor` setting sits between --editor and the environment.
    const configured: ?[]const u8 = blk: {
        const r = cmd_sync.localSetting(io, arena, root_dir, .{ .environ = amb.environ }, cfg, .editor) catch break :blk null;
        break :blk if (r.value.len == 0) null else r.value;
    };
    const editor = editor_override orelse configured orelse env_map.get("VISUAL") orelse env_map.get("EDITOR") orelse {
        streams.err.writeAll("zit commit: no editor: set $VISUAL or $EDITOR, 'zit settings editor PROG', pass --editor PROG, or give the comment with -m\n") catch {};
        return null;
    };
    var tpl: std.ArrayList(u8) = .empty;
    defer tpl.deinit(gpa);
    tpl.appendSlice(gpa, "\n# Enter a check-in comment. Lines starting with '#' are ignored;\n# an empty comment aborts the commit.\n#\n") catch return null;
    tpl.print(gpa, "# branch: {s}\n", .{branch}) catch return null;
    if (parent.len != 0) tpl.print(gpa, "# parent: {s}\n", .{parent[0..@min(parent.len, 12)]}) catch return null;
    tpl.appendSlice(gpa, "#\n") catch return null;
    for (lines) |l| tpl.print(gpa, "# {s: <8}{s}\n", .{ l.word, l.path }) catch return null;
    root_dir.writeFile(io, .{ .sub_path = comment_file_name, .data = tpl.items }) catch {
        streams.err.print("zit commit: cannot write {s}\n", .{comment_file_name}) catch {};
        return null;
    };
    const path = std.fs.path.join(arena, &.{ root_abs, comment_file_name }) catch return null;
    const script = std.fmt.allocPrint(arena, "{s} \"$1\"", .{editor}) catch return null;
    var child = std.process.spawn(io, .{
        .argv = &.{ "/bin/sh", "-c", script, "zit-editor", path },
        .cwd = .{ .dir = root_dir },
        .environ_map = &env_map,
    }) catch {
        streams.err.print("zit commit: cannot start the editor '{s}'\n", .{editor}) catch {};
        return null;
    };
    const term = child.wait(io) catch {
        streams.err.print("zit commit: the editor '{s}' did not finish\n", .{editor}) catch {};
        return null;
    };
    switch (term) {
        .exited => |code| if (code != 0) {
            streams.err.print("zit commit: the editor exited with status {d}; comment kept in {s}\n", .{ code, comment_file_name }) catch {};
            return null;
        },
        else => {
            streams.err.print("zit commit: the editor did not exit normally; comment kept in {s}\n", .{comment_file_name}) catch {};
            return null;
        },
    }
    const raw = root_dir.readFileAlloc(io, comment_file_name, gpa, .limited(1 << 20)) catch {
        streams.err.print("zit commit: cannot read {s} back\n", .{comment_file_name}) catch {};
        return null;
    };
    defer gpa.free(raw);
    var out: std.ArrayList(u8) = .empty;
    var it = std.mem.splitScalar(u8, raw, '\n');
    while (it.next()) |line| {
        if (std.mem.startsWith(u8, line, "#")) continue;
        out.appendSlice(arena, line) catch return null;
        out.append(arena, '\n') catch return null;
    }
    const trimmed = std.mem.trim(u8, out.items, " \t\r\n");
    if (trimmed.len == 0) {
        streams.err.print("zit commit: aborting — empty check-in message (template kept in {s})\n", .{comment_file_name}) catch {};
        return null;
    }
    return arena.dupe(u8, trimmed) catch null;
}