Skip to content
zit Artifact [5acf461448]
Login

Artifact [5acf461448]

Artifact 5acf461448981d27f4507374387e2ef2f09b611a56486af75553f1b169cbd308:


//! `zit open`: check out a repository into a directory, fetching on demand
//! from the saved remote what a sparse or horizon store does not hold.

const std = @import("std");
const Io = std.Io;
const Repository = @import("zit").Repository;
const artifact = zit.artifact;
const checkinSetting = @import("settings.zig").checkinSetting;
const checkout = @import("zit").checkout;
const cli = @import("zit").cli;
const deepenHorizon = @import("pull.zig").deepenHorizon;
const deepenPoint = @import("pull.zig").deepenPoint;
const diagnostics = @import("../diagnostics.zig");
const digest_len = zit.digest_name.digest_len;
const help_pages = @import("../help.zig");
const hexToDigest = zit.digest_name.hexToDigest;
const localSetting = zit.repo_config.localSetting;
const logstore = @import("zit").logstore;
const openRepo = diagnostics.openRepo;
const open_help = help_pages.open_help;
const repoOpenFail = diagnostics.repoOpenFail;
const repo_filename = zit.repo_filename;
const resolveRemoteUrl = zit.sync_session.resolveRemoteUrl;
const runClone = @import("clone.zig").runClone;
const runPull = @import("pull.zig").runPull;
const storage = @import("zit").storage;
const update = @import("zit").update;
const zit = @import("zit");

fn storeIsSparse(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir) bool {
    var probe = zit.repocache.readStoreCone(gpa, io, root_dir) orelse return false;
    probe.deinit(gpa);
    return true;
}

fn openFetchable(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir, allow_fetch: bool) bool {
    if (!allow_fetch) return false;
    var url_buf: [logstore.max_config_str]u8 = undefined;
    _ = resolveRemoteUrl(gpa, io, root_dir, "", &url_buf) catch return false;
    return true;
}

/// Sparse-cone RFC section 6.4, policy form: the requested materialization
/// IS the new coverage intent. Write it as the store cone (null = dense),
/// run an ordinary pull -- whose suppression and receive filtering read the
/// NEW policy -- and reprobe. Anything the peer lacked stays a transit
/// phantom for later synchronization to heal.
fn openDemandFetch(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    root_dir: std.Io.Dir,
    sparse: update.SparseOpt,
) cli.Exit {
    const requested: ?*const zit.cone.Cone = switch (sparse) {
        .set => |c| c,
        .inherit => null, // a dense open drops the cone
    };
    // Horizon draft section 5.7: widening the paths keeps the store's
    // horizon. Writing the requested paths alone would drop it, and the pull
    // would densify the whole history to open one check-in.
    var store_cone = zit.repocache.readStoreCone(gpa, io, root_dir);
    defer if (store_cone) |*c| c.deinit(gpa);
    var widened: ?zit.cone.Cone = null;
    defer if (widened) |*c| c.deinit(gpa);
    if (store_cone) |*sc| if (sc.horizon) |h| if (requested == null or requested.?.horizon == null) {
        widened = (if (requested) |c| zit.cone.Cone.initFrom(gpa, c, h) else zit.cone.Cone.initHorizon(gpa, &.{}, &.{}, h)) catch
            return openDiag(streams, "the requested cone cannot be combined with the store's horizon");
    };
    zit.repocache.writeStoreCone(gpa, io, root_dir, if (widened) |*c| c else requested);
    const pull_exit = runPull(gpa, io, arena, &.{}, streams, .{ .now_epoch = 0, .user_env = null });
    if (pull_exit != .ok) return pull_exit;
    // Everything resolved so far (tip, branch, the log handle) predates the
    // fetch; re-attempt from scratch with fetching disabled, so a peer that
    // also lacked the content produces the elided refusal rather than a loop.
    return openAttempt(gpa, io, arena, verb_args, streams, amb, false);
}

/// Whether an open materializing `sparse` needs `path`: every path for a
/// dense open, the requested cone's paths otherwise.
fn wantsPath(sparse: update.SparseOpt, path: []const u8) bool {
    return switch (sparse) {
        .set => |c| if (c) |r| r.covers(path) else true,
        .inherit => true,
    };
}

/// Render an `open` diagnostic to stderr and fail. Best-effort on the write: a
/// diagnostic that cannot be printed must not change the exit code.
fn openDiag(s: cli.Streams, msg: []const u8) cli.Exit {
    s.err.print("zit open: {s}\n", .{msg}) catch {};
    return .failure;
}

/// Map a materialization fault to its `open` diagnostic, one arm per
/// `update.ApplyError` variant and NO `else`: a new variant must fail this
/// compile and force a decision here, exactly as it does in `updateApplyFail`.
///
/// Only `InvalidCheckinId` and `CheckinNotFound` are genuinely unreachable —
/// `open` hands the engine a hash it just resolved out of this repository's own
/// derived state, never a caller-supplied name — and even those get honest
/// prose rather than a corruption claim. Everything else is reachable on an
/// intact repository: the content/manifest arms describe a repository that
/// really is damaged, while `SymlinkUnsupported` / `InvalidPath` /
/// `ReservedPath` are raised while planning the TARGET manifest, so a clone of
/// any repository containing a symlink or a path this platform cannot represent
/// reaches them with nothing corrupt at all. Reporting those as corruption
/// would be a false accusation against a healthy repository; the prose mirrors
/// `updateApplyFail`'s.
/// Decode a lowercase-hex artifact name to its raw digest for a presence probe.
/// Null for anything that cannot be a stored name, which the caller reads as
/// "not a name this store could hold" and therefore not a missing-content claim.
fn openDecodeName(name: []const u8, out: *[logstore.max_hash_len]u8) ?[]const u8 {
    if (name.len == 0 or name.len % 2 != 0) return null;
    const bytes = name.len / 2;
    if (bytes > logstore.max_hash_len) return null;
    _ = std.fmt.hexToBytes(out[0..bytes], name) catch return null;
    return out[0..bytes];
}

/// The tip resolved to a check-in whose file content this repository does not
/// hold. Named as a CLASS rather than as a missing file, because the missing
/// file is a symptom: the usual cause is that the store holds artifacts which
/// parse as check-ins of a different repository, and no amount of looking at the
/// named path explains that.
///
/// This refuses. It never falls back to another check-in — picking a different
/// tip because the real one is unusable would be inventing history, and the
/// operator would have no way to know it happened.
fn openForeignCheckin(
    s: cli.Streams,
    target: []const u8,
    branch: []const u8,
    missing: usize,
    first: []const u8,
) cli.Exit {
    s.err.print(
        "zit open: the tip of '{s}' is check-in {s}, whose file content this repository does not hold\n",
        .{ branch, target },
    ) catch {};
    s.err.print(
        "zit open: {d} file(s) are missing, starting with '{s}'\n",
        .{ missing, first },
    ) catch {};
    s.err.writeAll(
        "zit open: this happens when a repository stores artifacts that parse as check-ins of\n" ++
            "zit open: ANOTHER repository -- imported mirror metadata is the common source -- so they\n" ++
            "zit open: join the branch as check-ins whose blobs were never here. The working tree was\n" ++
            "zit open: not modified. 'zit leaves' shows the branch's check-ins; 'zit update <check-in>'\n" ++
            "zit open: materializes a specific one.\n",
    ) catch {};
    return .failure;
}

fn openApplyFail(s: cli.Streams, err: update.ApplyError) cli.Exit {
    return switch (err) {
        // applyCheckin never emits this: only applyMerge's cross-cone guard
        // does, and this switch maps a checkin materialization. The unreachable
        // IS the assertion; a future emitter trips it in tests immediately.
        error.SparseMergeUnsupported => unreachable,
        error.FileContentMissing => blk: {
            var b: [512]u8 = undefined;
            break :blk openDiag(s, update.stageFaultReason(&b));
        },
        error.OutOfMemory => openDiag(s, "out of memory"),
        error.InvalidCheckinId => openDiag(s, "cannot read repository: the resolved check-in ID is not a valid artifact name"),
        error.CheckinNotFound => openDiag(s, "cannot read repository: the resolved check-in is not present"),
        error.CheckinContentMissing => openDiag(s, "cannot read repository: check-in content is missing"),
        error.AggregateChecksumMismatch => openDiag(s, "the check-in's R checksum disagrees with its content"),
        error.CheckinNameMismatch => openDiag(s, "cannot read repository: check-in content does not match its name"),
        error.TargetNotManifest => openDiag(s, "cannot read repository: the check-in is not a valid manifest"),
        error.BaselineNotFound => openDiag(s, "cannot read repository: the check-in baseline is not found"),
        error.BaselineContentMissing => openDiag(s, "cannot read repository: the check-in baseline content is missing"),
        error.BaselineNameMismatch => openDiag(s, "cannot read repository: the check-in baseline content does not match its name"),
        error.BaselineNotManifest => openDiag(s, "cannot read repository: the check-in baseline is not a valid manifest"),
        error.StateRecordInvalid => openDiag(s, "cannot read repository: " ++ update.state_record_invalid_reason),
        error.Corrupt => openDiag(s, "cannot read repository: repository is corrupt"),
        error.SymlinkUnsupported => openDiag(s, "the check-in contains an unsupported symlink entry"),
        error.InvalidPath => openDiag(s, "the check-in names an invalid file path"),
        error.ReservedPath => openDiag(s, "the check-in names a reserved file path"),
        error.WorktreeNotClean => openDiag(s, "working tree is not clean"),
        error.UnmanagedCollision => openDiag(s, "an untracked file or directory is in the way"),
        error.CurrentStateInvalid => openDiag(s, "current working-tree state is invalid"),
        error.Storage => openDiag(s, "cannot update working tree: input/output error"),
        error.TransactionUnavailable => openDiag(s, "cannot create a transaction directory"),
        error.RollbackFailed => openDiag(s, "open failed and could not be rolled back; the previous working-tree state is retained for recovery"),
        error.CleanupFailed => openDiag(s, "open committed, but the transaction directory could not be removed"),
    };
}

/// `zit open` — the second half of `zit clone URL DIR`: turn a repository whose
/// checkout is still UNBORN into a materialized working tree. Fossil's own UX is
/// the same two steps (`fossil clone` then `fossil open`), and splitting them
/// keeps `runClone` strictly repo-only.
///
/// Thin wiring over the shipped machinery, deliberately: probe the checkout
/// record, resolve the tip of the main branch out of the derived repo state, and
/// hand materialization to the SAME `update.applyCheckin` engine every other
/// working-tree move rides (journal-armed, transactional, rollback-safe). Only
/// the tip resolution is open's own work, and it is load-bearing: `update`
/// accepts nothing but a literal 40/64-hex check-in ID, so a freshly cloned tree
/// has no way to name its own tip.
///
/// It writes NO checkout record and NO managed set of its own. `init` — which
/// `clone` delegates repo creation to — already wrote the unborn record; an
/// absent managed set already reads as the empty set; and the update engine is
/// the single writer of the born record and the managed set. Adding a second
/// writer of that bootstrap state would only create two things to keep in sync.
pub fn runOpen(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    // One demand-fetch retry, statically bounded (TigerStyle: no unbounded
    // recursion -- the second attempt runs with fetching disabled).
    // `zit open URL` is `zit clone URL` — cloned into a directory
    // named from the URL and opened there.
    for (verb_args) |tok| {
        if (std.mem.startsWith(u8, tok, "http://") or std.mem.startsWith(u8, tok, "https://")) {
            return runClone(gpa, io, arena, verb_args, streams, amb);
        }
        if (tok.len > 0 and tok[0] != '-') break;
    }
    return openAttempt(gpa, io, arena, verb_args, streams, amb, true);
}

/// The `--store` bootstrap: validate both ends, then write the container.
/// The current directory must not already be a checkout (either control
/// file), and PATH must hold a readable `.zit` -- checked here so the
/// operator hears "no store at PATH" instead of a discovery miss. The
/// container write is `checkout.write`'s atomic splice plus one
/// `store_location` section carrying the store root's ABSOLUTE path: a
/// worktree is addressed from anywhere, so a relative pointer would go
/// stale with every `cd`.
const Bootstrap = union(enum) { created, repaired, failed: cli.Exit };

fn bootstrapDetached(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    store_arg: []const u8,
) Bootstrap {
    var cwd = std.Io.Dir.cwd();
    if (cwd.statFile(io, repo_filename, .{})) |_| {
        streams.err.writeAll("zit open: this directory holds the repository itself; --store points a DETACHED tree elsewhere\n") catch {};
        return .{ .failed = .failure };
    } else |_| {}
    const repairing = if (cwd.statFile(io, checkout.filename, .{})) |_| true else |_| false;

    // PATH may name the store root or the `.zit` file itself; either way the
    // pointer stored is the DIRECTORY, absolute.
    const named_file = std.mem.endsWith(u8, store_arg, "/.zit") or std.mem.eql(u8, store_arg, ".zit");
    const store_root_rel = if (named_file) (std.fs.path.dirname(store_arg) orelse ".") else store_arg;
    var store_root = cwd.openDir(io, store_root_rel, .{}) catch {
        streams.err.print("zit open: no directory at '{s}'\n", .{store_root_rel}) catch {};
        return .{ .failed = .failure };
    };
    defer store_root.close(io);
    _ = store_root.statFile(io, repo_filename, .{}) catch {
        streams.err.print("zit open: no repository ('.zit') under '{s}'\n", .{store_root_rel}) catch {};
        return .{ .failed = .failure };
    };
    const abs = store_root.realPathFileAlloc(io, ".", arena) catch {
        streams.err.print("zit open: cannot resolve '{s}'\n", .{store_root_rel}) catch {};
        return .{ .failed = .failure };
    };

    if (repairing) {
        // Re-open: the checkout exists and its pointer (or the store it
        // pointed at) went stale — a moved store strands its satellites, and
        // a stranded tree can hold uncommitted work, so the pointer must be
        // repairable in place. The one gate that matters: the NEW store must
        // contain this tree's current check-in, or the recorded tree state
        // would be a lie against the store it now names. "Same store at a
        // new address" passes; "some other repository" is refused.
        var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
        const current = checkout.read(io, cwd, &ck_buf) catch {
            streams.err.writeAll("zit open: cannot read the checkout state\n") catch {};
            return .{ .failed = .failure };
        };
        if (current) |state| if (state.version.len != 0) {
            var digest_buf: [digest_len]u8 = undefined;
            const digest = hexToDigest(state.version, &digest_buf) orelse {
                streams.err.writeAll("zit open: the checkout state is corrupt\n") catch {};
                return .{ .failed = .failure };
            };
            var store_file = cli.openStoreRead(io, store_root) catch |e| {
                streams.err.print("zit open: cannot read the repository under '{s}': {s}\n", .{ store_root_rel, diagnostics.reasonOf(e) }) catch {};
                return .{ .failed = .failure };
            };
            defer store_file.close(io);
            const store_st = store_file.stat(io) catch {
                streams.err.print("zit open: cannot read the repository under '{s}'\n", .{store_root_rel}) catch {};
                return .{ .failed = .failure };
            };
            var store_fs = storage.FileStorage.init(io, store_file, store_st.size);
            var store_log = logstore.LogStore.openReadOnly(gpa, store_fs.storageFile()) catch {
                streams.err.print("zit open: cannot read the repository under '{s}'\n", .{store_root_rel}) catch {};
                return .{ .failed = .failure };
            };
            defer store_log.deinit(gpa);
            if (store_log.lookup(digest) == null) {
                streams.err.print(
                    "zit open: the repository under '{s}' does not contain this tree's check-in '{s}'; refusing to re-point at a different repository\n",
                    .{ store_root_rel, state.version },
                ) catch {};
                return .{ .failed = .failure };
            }
        };
        checkout.updateSections(io, cwd, &.{.{ .tag = .store_location, .payload = abs }}) catch {
            streams.err.writeAll("zit open: cannot write the checkout state\n") catch {};
            return .{ .failed = .failure };
        };
        streams.out.print("checkout now points at '{s}'\n", .{abs}) catch {};
        return .repaired;
    }

    checkout.write(io, cwd, .{ .version = "", .branch = "trunk", .merge_parent = "", .special_op = "", .manifest_flags = "" }) catch {
        streams.err.writeAll("zit open: cannot write the checkout state\n") catch {};
        return .{ .failed = .failure };
    };
    checkout.updateSections(io, cwd, &.{.{ .tag = .store_location, .payload = abs }}) catch {
        cwd.deleteFile(io, checkout.filename) catch {};
        streams.err.writeAll("zit open: cannot write the checkout state\n") catch {};
        return .{ .failed = .failure };
    };
    return .created;
}

fn openAttempt(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    allow_fetch: bool,
) cli.Exit {
    const parsed = switch (cli.parseOpenArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "open", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "open", .extra_argument, tok),
        .repeated_option => |tok| return cli.usageError(streams, "open", .repeated_option, tok),
        .empty_value => |tok| return cli.usageError(streams, "open", .empty_value, tok),
        .bad_manifest => |tok| return cli.usageError(streams, "open", .bad_manifest, tok),
        .too_many_cones => |tok| return cli.usageError(streams, "open", .too_many_cones, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(open_help) catch {};
        return .ok;
    }

    // `--store PATH` bootstraps a DETACHED checkout in the current
    // directory: an unborn checkout record (exactly what `init` writes) plus
    // the store pointer, and nothing else. Everything after this block is the
    // ordinary open — discovery finds the fresh container, `Repository.open`
    // follows the pointer, and the materialization below neither knows nor
    // cares that the store lives elsewhere.
    if (parsed.store) |store_arg| {
        switch (bootstrapDetached(gpa, io, arena, streams, store_arg)) {
            .created => {},
            // A repair is complete in itself: the tree is already open at its
            // check-in, so the materialization below has nothing to do.
            .repaired => return .ok,
            .failed => |rc| return rc,
        }
    }

    // The full derive: resolving the main branch reads the tag tables, which the
    // `.fast_read` image path does not carry.
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "open", null, false, false, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    // BORN-ness, not presence, is the "already open" signal. Every fresh
    // repository carries a checkout record — `init` writes an unborn one
    // (`version == ""`, branch `trunk`) as its step 8, and `clone` delegates to
    // `init` — so a presence-based gate would reject `zit clone && zit open` on
    // every clone, the primary path this verb exists to serve. Only a non-empty
    // version means a tree has actually been materialized against a check-in.
    var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
    const current = checkout.read(io, root_dir, &ck_buf) catch |e| switch (e) {
        error.Storage => return openDiag(streams, "cannot read the checkout state: input/output error"),
        error.Corrupt => return openDiag(streams, "the checkout state is corrupt"),
    };
    if (current) |state| if (state.version.len != 0) {
        streams.err.print(
            "zit open: this working tree is already open at check-in '{s}'; use 'zit update' to change check-ins\n",
            .{state.version},
        ) catch {};
        return .failure;
    };

    // The target: an explicit CHECKIN resolved like `zit info` (§8.3), or the
    // tip of the main branch (repo-state §9 current-trunk). Everything below —
    // preflight, materialization, the manifest opt-in — is target-generic.
    const main_branch = repo.mainBranch();
    const tip = if (parsed.checkin) |name|
        repo.resolve(name, .checkin) catch |e| {
            switch (e) {
                error.NotFound => {
                    streams.err.print("zit open: check-in '{s}' not found\n", .{name}) catch {};
                    cli.horizonNameHint(gpa, io, root_dir, streams, "open");
                },
                error.Ambiguous => streams.err.print("zit open: name '{s}' is ambiguous\n", .{name}) catch {},
                error.OutOfMemory => return openDiag(streams, "out of memory"),
            }
            return .failure;
        }
    else
        // Switched, not an unbound `catch`: the success message below is an
        // exit-0 claim that the tree is already correct, and it is only honest
        // for `NotFound`. Naming the arm means a later Storage/OOM arm on
        // `currentTrunk` fails this compile instead of silently reporting a
        // genuine failure as success on a materialization verb.
        repo.state().currentTrunk(main_branch) catch |e| switch (e) {
            // A repository with no check-in on its main branch is ALREADY in its
            // correct end state — the unborn record and an empty tree. There is
            // nothing to materialize and nothing wrong, so this is reported, not
            // failed, and the record is left exactly as it was found. An
            // explicit CHECKIN never lands here: in an empty repository it
            // resolves to NotFound above, a failure, because the operator asked
            // for something specific and did not get it.
            error.NotFound => {
                streams.out.print(
                    "open: no check-in on '{s}' yet; the working tree is already in its correct (empty) state\n",
                    .{main_branch},
                ) catch {};
                return .ok;
            },
            // Settling an equal-mtime tie by ancestry allocates (repo-state
            // `MtimeMaxPick`). A failure here is a genuine failure — reporting
            // it as the exit-0 "already correct" message would be the lie the
            // switch above exists to prevent.
            error.OutOfMemory => return openDiag(streams, "out of memory"),
        };
    // Both borrow the derived view, which outlives the update below.
    const target = repo.hashOf(tip);
    const branch = repo.branchOf(tip);
    // An assertion, not a check: unlike `update`, whose target is user-supplied
    // and therefore validated, open's target comes out of this repository's own
    // derived state. A malformed name here is a defect in the derivation, not
    // bad input, so it belongs in the negative space rather than in a
    // diagnostic path no correct run can reach.
    std.debug.assert(artifact.validateName(target));

    // Distinct from the open above, which shares `repoOpenFail`'s wording: this
    // one has already derived the view successfully and is opening the log a
    // SECOND time, read-only, for materialization. Reporting both identically
    // made a failure here indistinguishable from a failure to derive — and they
    // are different repositories' worth of problem.
    const log = repo.logStore(gpa) catch |e| {
        switch (e) {
            error.Corrupt => streams.err.print(
                "zit open: the repository derived cleanly but its log will not reopen for reading: corrupt\n",
                .{},
            ) catch {},
            else => return repoOpenFail(streams, "open", e),
        }
        return .failure;
    };
    // Sparse-cone RFC section 4.1: `open --cone` materializes the first
    // checkout already scoped. Absent flag = dense, exactly the shipped
    // behavior; `open` has no --dense because a fresh checkout IS dense.
    var open_members = parsed.cone_members;
    var open_len = parsed.cone_len;
    var open_not_members = parsed.cone_not_members;
    var open_not_len = parsed.cone_not_len;
    if (parsed.cone_file) |cf| {
        const lens = cli.appendConeFile(arena, io, cf, &open_members, open_len, &open_not_members, open_not_len) orelse {
            streams.err.print("zit open: cannot read --cone-file '{s}' (or it overflows the {d}-member cap)\n", .{ cf, zit.cone.max_members }) catch {};
            return .failure;
        };
        open_len = lens.members;
        open_not_len = lens.not_members;
    }
    var open_cone: ?zit.cone.Cone = null;
    defer if (open_cone) |*c| c.deinit(gpa);
    if (parsed.cone_parents and open_len == 0) {
        streams.err.writeAll("zit open: --cone-parents needs --cone=PATH: it is a property of the cone being set\n") catch {};
        return .failure;
    }
    const sparse: update.SparseOpt = if (open_len + open_not_len != 0) blk: {
        open_cone = zit.cone.Cone.initWith(gpa, open_members[0..open_len], open_not_members[0..open_not_len], .{ .parents = parsed.cone_parents }) catch |e|
            return openConeFail(streams, e);
        break :blk .{ .set = &open_cone.? };
    } else .inherit;

    // PREFLIGHT: does this repository actually hold the content of the check-in
    // it just resolved as the tip?
    //
    // The format is content-addressed and types artifacts by STRUCTURE, so a
    // stored blob whose bytes happen to be a valid check-in manifest IS a
    // check-in — repo-state §4.4 grants opacity only to artifacts a conformant
    // parser DECLINES to classify, and a foreign manifest classifies fine. A
    // repository that tracks a file containing one (a Fossil->Git mirror's
    // `manifest`, a test fixture, a documentation example) therefore holds
    // check-ins of a DIFFERENT repository, whose file content it never had. That
    // is conformant derivation, not corruption, and Fossil behaves the same way.
    //
    // What is not acceptable is spending several minutes materializing before
    // discovering it. `stagePlan` already refuses safely — nothing is written
    // until every byte is verified and staged — so this changes no outcome; it
    // moves the refusal earlier and lets it NAME the situation, which a bare
    // missing-content error cannot.
    //
    // Presence-only: `lookup` asks whether a name is held, reconstructing
    // nothing. Cost is one probe per file in the tip, against a derive that
    // already walked every artifact in the store.
    if (repo.files(gpa, tip)) |maybe_list| {
        if (maybe_list) |list_const| {
            var list = list_const;
            defer list.deinit(gpa);
            // Sparse-cone RFC section 5.2: absence has three classes, and
            // this preflight must not read a deliberately sparse store as the
            // foreign-check-in class. A missing blob whose path the STORE
            // cone does not cover is elided -- healthy. Elided files that the
            // requested materialization would need refuse by the elision
            // class (section 6.4; demand fetch is a later wave), never as
            // foreign, and never as corruption.
            var store_cone = zit.repocache.readStoreCone(gpa, io, root_dir);
            defer if (store_cone) |*c| c.deinit(gpa);
            var missing: usize = 0;
            var first_missing: ?[]const u8 = null;
            var elided: usize = 0;
            var first_elided: ?[]const u8 = null;
            // Absent because the store's PATHS leave it out, as opposed to
            // absent below the horizon: the remedy is a widening, which a
            // deepen never performs.
            var first_path_elided: ?[]const u8 = null;
            var it = list.iterator();
            while (it.next()) |f| {
                const h = f.hash orelse continue;
                var digest_buf: [logstore.max_hash_len]u8 = undefined;
                const raw = openDecodeName(h, &digest_buf) orelse continue;
                if (log.lookup(raw) == null) {
                    if (store_cone) |*c| {
                        // Horizon draft section 4.2: under a horizon an absent
                        // blob of ANY check-in is elided by history, whatever
                        // its path; the foreign-check-in class needs a dense
                        // store to be the explanation.
                        const path_elided = !c.covers(f.filename);
                        if (c.horizon != null or path_elided) {
                            elided += 1;
                            if (first_elided == null) first_elided = f.filename;
                            if (path_elided and first_path_elided == null and wantsPath(sparse, f.filename)) first_path_elided = f.filename;
                            continue;
                        }
                    }
                    missing += 1;
                    if (first_missing == null) first_missing = f.filename;
                }
            }
            if (missing != 0) return openForeignCheckin(streams, target, branch, missing, first_missing.?);
            if (elided != 0) {
                // The materialization cone decides whether elision matters:
                // an open scoped inside the held content proceeds; one that
                // needs elided bytes refuses, naming the class and the count.
                const wants_elided = blk: {
                    switch (sparse) {
                        .set => |c| {
                            if (c) |request| {
                                if (!request.covers(first_elided.?)) {
                                    var again = list.iterator();
                                    var any = false;
                                    while (again.next()) |f| {
                                        const h2 = f.hash orelse continue;
                                        var db2: [logstore.max_hash_len]u8 = undefined;
                                        const raw2 = openDecodeName(h2, &db2) orelse continue;
                                        if (log.lookup(raw2) == null and request.covers(f.filename)) {
                                            any = true;
                                            break;
                                        }
                                    }
                                    break :blk any;
                                }
                                break :blk true;
                            }
                            break :blk true; // dense request needs everything
                        },
                        .inherit => break :blk true, // no worktree cone yet on open
                    }
                };
                if (wants_elided) {
                    const under_horizon = if (store_cone) |*c| c.horizon != null else false;
                    if (!allow_fetch) {
                        // The fetch already ran: the saved remote did not
                        // supply what this open needs.
                        streams.err.print(
                            "zit open: {d} file(s) of this check-in are still absent after fetching from the saved remote, starting with '{s}'\n" ++
                                "zit open: the remote does not hold them; open inside the cone ('zit open --cone=...') or re-clone\n",
                            .{ elided, first_elided.? },
                        ) catch {};
                        return .failure;
                    }
                    if (!openFetchable(gpa, io, root_dir, allow_fetch)) {
                        if (under_horizon) {
                            streams.err.print(
                                "zit open: {d} file(s) of this check-in lie below the store's horizon or outside its cone, starting with '{s}'\n" ++
                                    "zit open: no saved remote to fetch them from; set one ('zit remote URL') or re-clone with an earlier --horizon\n",
                                .{ elided, first_elided.? },
                            ) catch {};
                            return .failure;
                        }
                        streams.err.print(
                            "zit open: {d} file(s) of this check-in are elided by the store's sparse cone, starting with '{s}'\n" ++
                                "zit open: no saved remote to fetch them from; open inside the cone\n" ++
                                "zit open: ('zit open --cone=...'), set a remote ('zit remote URL'), or re-clone\n",
                            .{ elided, first_elided.? },
                        ) catch {};
                        return .failure;
                    }
                    // Horizon draft section 5.7 -- under a horizon the policy
                    // form is DEEPEN: C moves to a common ancestor of C and
                    // the check-in being opened (C itself when that check-in
                    // is above it), the rule unchanged, and the pull brings
                    // K(target) down. Dropping the horizon here would densify
                    // the whole store on the first open below C. The paths
                    // stay unless the open needs a file they leave out; then
                    // they become the requested cone, as `openDemandFetch`
                    // writes on a store without a horizon.
                    var deepened: ?zit.cone.Cone = null;
                    defer if (deepened) |*c| c.deinit(gpa);
                    var point_buf: [64]u8 = undefined;
                    var point: []const u8 = target;
                    if (under_horizon) {
                        const sc = &store_cone.?;
                        point = deepenPoint(gpa, io, root_dir, streams, amb, "open", sc.horizon.?.hash, target, &point_buf) orelse return .failure;
                        // The store's paths, or, when a path lies outside
                        // them, the requested ones (none for a dense open).
                        const paths: ?*const zit.cone.Cone = if (first_path_elided == null) sc else switch (sparse) {
                            .set => |c| c,
                            .inherit => null,
                        };
                        const deepen_to: zit.cone.Horizon = .{ .hash = point, .rule = sc.horizon.?.rule, .depth = sc.horizon.?.depth };
                        deepened = (if (paths) |c| zit.cone.Cone.initFrom(gpa, c, deepen_to) else zit.cone.Cone.initHorizon(gpa, &.{}, &.{}, deepen_to)) catch
                            return openDiag(streams, "the requested cone cannot be combined with the store's horizon");
                    }
                    if (deepened) |*c| {
                        const moved = !std.ascii.eqlIgnoreCase(point, store_cone.?.horizon.?.hash);
                        if (moved) {
                            streams.err.print(
                                "zit open: {d} file(s) lie below the store's horizon; deepening to {s} from the saved remote\n",
                                .{ elided, point },
                            ) catch {};
                        } else {
                            streams.err.print(
                                "zit open: {d} file(s) lie outside the store's cone; widening it under the same horizon from the saved remote\n",
                                .{elided},
                            ) catch {};
                        }
                        const deepen_exit = deepenHorizon(gpa, io, arena, root_dir, streams, "open", c);
                        if (deepen_exit != .ok) return deepen_exit;
                        return openAttempt(gpa, io, arena, verb_args, streams, amb, false);
                    }
                    streams.err.print(
                        "zit open: {d} file(s) are elided by the store's sparse cone; fetching from the saved remote\n",
                        .{elided},
                    ) catch {};
                    return openDemandFetch(gpa, io, arena, verb_args, streams, amb, root_dir, sparse);
                }
            }
        }
    } else |_| {
        // A files() fault is not this preflight's to report: the engine below
        // reaches the same data and has the diagnostics for it. Falling through
        // keeps this advisory, never a new way to fail.
    }

    // `open` is the ONE verb that SETS the manifest opt-in. `--manifest`
    // is the operator's explicit choice and always wins; `--manifest=off` is
    // remembered as the refusal. Absent, the PROJECT's
    // `manifest` setting supplies it, which is fossil's model: a clone gets
    // build stamps because the project asked for them, not because each
    // developer remembered to. The tree is not materialized yet, so the
    // versioned tier is read out of the check-in itself, as fossil's
    // `db_get_versioned` does through `historical_blob`.
    // The verb's own `log` is already open, so the project setting is
    // resolved from the config it holds rather than through a second open.
    var open_config: ?logstore.OwnedConfig = log.readConfig(gpa) catch null;
    defer if (open_config) |*c| c.deinit(gpa);
    const open_cfg: ?*const logstore.Config = if (open_config) |*c| &c.config else null;
    const manifest: update.ManifestOpt = if (parsed.manifest) |m| .{ .set = m } else .{
        .inherit_or = blk: {
            const r = checkinSetting(gpa, io, arena, &repo, tip, amb, open_cfg, .manifest) catch break :blk "";
            break :blk r.value;
        },
    };
    // The check-in is named on failure because `open` RESOLVES its own target
    // (the tip of the configured main branch) rather than being handed one. A
    // diagnostic that omits it cannot distinguish "materializing the expected
    // check-in went wrong" from "resolved a different check-in than the operator
    // believes is the tip" — and the operator has no other way to see which.
    update.applyCheckinWith(gpa, io, root_dir, log, target, manifest, sparse, &repo, null) catch |e| {
        // Sparse-cone RFC section 5.1: a store that elided out-of-cone
        // sub-manifest nodes cannot enumerate a tree wider than its cone,
        // which the preflight above (a whole-tree read) could not count.
        if (e == error.BaselineNotFound and storeIsSparse(gpa, io, root_dir)) {
            if (openFetchable(gpa, io, root_dir, allow_fetch)) {
                streams.err.writeAll("zit open: part of this check-in's tree is elided by the store's sparse cone; fetching from the saved remote\n") catch {};
                return openDemandFetch(gpa, io, arena, verb_args, streams, amb, root_dir, sparse);
            }
            streams.err.print(
                "zit open: part of check-in {s}'s tree is elided by the store's sparse cone, and no saved remote can supply it\n" ++
                    "zit open: open inside the cone ('zit open --cone=PATH'), or set a remote ('zit remote URL')\n",
                .{target},
            ) catch {};
            return .failure;
        }
        streams.err.print("zit open: materializing check-in {s} on {s}\n", .{ target, branch }) catch {};
        return openApplyFail(streams, e);
    };

    // The `empty-dirs` shape, laid over the tree the check-in
    // just produced. Read AFTER the materialization because a versioned
    // `.fossil-settings/empty-dirs` does not exist on disk before it; fossil's
    // checkout reads the same value out of the check-in it is installing, so
    // the two see the same list.
    {
        const dirs: []const u8 = blk: {
            const r = localSetting(io, arena, root_dir, .{ .environ = amb.environ }, open_cfg, .empty_dirs) catch break :blk "";
            break :blk r.value;
        };
        update.ensureEmptyDirs(io, root_dir, dirs, streams.err);
    }

    // A successful open stamps this tree into the store's worktree
    // registry (best-effort; discovery data never gates the open).
    if (std.process.currentPathAlloc(io, gpa)) |own_abs| {
        defer gpa.free(own_abs);
        cli.stampWorktreeRegistry(gpa, io, root_dir, own_abs);
    } else |_| {}

    streams.out.print("opened {s} on {s}\n", .{ target, branch }) catch {};
    return .ok;
}

/// Map a Cone.init refusal for `open`. Same wording discipline as update's
/// mapper: states the rule, never says "missing" or "corrupt".
fn openConeFail(s: cli.Streams, err: zit.cone.Error) cli.Exit {
    switch (err) {
        error.OutOfMemory => s.err.writeAll("zit open: out of memory\n") catch {},
        error.InvalidMember => s.err.writeAll(
            "zit open: invalid --cone member: members are repository-relative paths using '/', with no '.', '..', or empty components\n",
        ) catch {},
        error.ReservedMember => s.err.writeAll("zit open: a --cone member names a reserved control path\n") catch {},
        error.Bounds => s.err.writeAll("zit open: --cone needs between 1 and 255 members (exclusions included), at least one inclusion\n") catch {},
        error.DeadExclusion => s.err.writeAll("zit open: a --cone-not member no --cone member covers is a dead rule\n") catch {},
        error.Contradiction => s.err.writeAll("zit open: one path given as both --cone and --cone-not\n") catch {},
    }
    return .failure;
}

/// Render one `ApplyError` through `openApplyFail` into `buf`.
fn openFailText(buf: []u8, err: update.ApplyError) []const u8 {
    var w = Io.Writer.fixed(buf);
    var sink: [1]u8 = undefined;
    var wnull = Io.Writer.fixed(&sink);
    const s: cli.Streams = .{ .out = &wnull, .err = &w };
    _ = openApplyFail(s, err);
    return w.buffered();
}

// Same guard as the `zit update`, `zit merge` and `zit bisect` mappers.
// `Corrupt` alleges the stored bytes do not match the name they are stored
// under; `StateRecordInvalid` says only that an artifact was unusable as a
// state record. A clone of an intact fossil repository reaches the second
// without anything being damaged, so it must never be answered with a
// corruption claim.
test "open: the two read-path failures do not share a diagnostic" {
    var a: [256]u8 = undefined;
    var b: [256]u8 = undefined;
    const corrupt = openFailText(&a, error.Corrupt);
    const state = openFailText(&b, error.StateRecordInvalid);

    try std.testing.expect(!std.mem.eql(u8, corrupt, state));
    try std.testing.expect(std.mem.indexOf(u8, corrupt, "corrupt") != null);
    try std.testing.expect(std.mem.indexOf(u8, state, "corrupt") == null);
}