Skip to content
zit Artifact [e4055e9c69]
Login

Artifact [e4055e9c69]

Artifact e4055e9c698a92d26e56edf814260cac8cdfb8f53a93fd1c41ad279397d1fb4e:


//! `zit pull`: fetch what an existing repository lacks from its peer, and the
//! horizon deepen and merge-base query that ride on a pull.

const std = @import("std");
const ClientHoldings = zit.sync_session.ClientHoldings;
const CloneProgress = @import("sync_dialogue.zig").CloneProgress;
const ErasureLatch = zit.sync_session.ErasureLatch;
const LeafWatch = @import("sync_dialogue.zig").LeafWatch;
const PeerErrorCopy = zit.sync_session.PeerErrorCopy;
const PostClassify = zit.sync_session.PostClassify;
const RepoElidedSet = zit.sync_session.RepoElidedSet;
const RepoSyncIdentity = zit.sync_session.RepoSyncIdentity;
const Repository = @import("zit").Repository;
const SparseClassification = zit.sparse.SparseClassification;
const StoreStamp = @import("sync_dialogue.zig").StoreStamp;
const applySessionErasures = @import("session_erasures.zig").applySessionErasures;
const armBasicAuth = @import("sync_dialogue.zig").armBasicAuth;
const artifact = zit.artifact;
const cli = @import("zit").cli;
const cmd_init = @import("init.zig");
const d4OpenLog = @import("sync_test_support.zig").d4OpenLog;
const d4SeedEmptyRepo = @import("sync_test_support.zig").d4SeedEmptyRepo;
const decodeWireName = zit.digest_name.decodeWireName;
const diagnostics = @import("../cli/diagnostics.zig");
const digest_len = zit.digest_name.digest_len;
const fallBackToContent = @import("sync_dialogue.zig").fallBackToContent;
const finishExchange = @import("sync_dialogue.zig").finishExchange;
const heldSeedName = zit.sync_session.heldSeedName;
const help_pages = @import("../cli/help.zig");
const loadClusterIndex = zit.receive.loadClusterIndex;
const logstore = @import("zit").logstore;
const max_password_len = @import("sync_dialogue.zig").max_password_len;
const noRemoteError = @import("sync_dialogue.zig").noRemoteError;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const noteLoginNotSaved = @import("sync_dialogue.zig").noteLoginNotSaved;
const notePlaintext = @import("sync_dialogue.zig").notePlaintext;
const openStoreLogForRead = zit.repo_config.openStoreLogForRead;
const persistStore = zit.receive.persistStore;
const plural = @import("sync_dialogue.zig").plural;
const pullRun = @import("sync_exchange.zig").pullRun;
const pull_help = help_pages.pull_help;
const readSyncCone = zit.sync_session.readSyncCone;
const readSyncCursor = zit.sync_session.readSyncCursor;
const reclassifyPull = zit.sync_session.reclassifyPull;
const refusePendingImport = @import("sync_dialogue.zig").refusePendingImport;
const renderStorage = cmd_init.renderStorage;
const repeat = @import("zit").repeat;
const repoReadFail = diagnostics.repoReadFail;
const repoSyncIdentity = zit.sync_session.repoSyncIdentity;
const repo_filename = zit.repo_filename;
const reportPeerRefusal = @import("sync_dialogue.zig").reportPeerRefusal;
const reportTruncatedPayloads = @import("sync_dialogue.zig").reportTruncatedPayloads;
const reportUvSkipped = @import("sync_dialogue.zig").reportUvSkipped;
const repostate = zit.repostate;
const resolveCredential = @import("sync_dialogue.zig").resolveCredential;
const resolvePushCredential = @import("sync_dialogue.zig").resolvePushCredential;
const resolveRemoteUrl = zit.sync_session.resolveRemoteUrl;
const s77SeedPolicyRepo = @import("sync_test_support.zig").s77SeedPolicyRepo;
const savedRemoteIn = zit.sync_session.savedRemoteIn;
const seedShunnedRepo = @import("sync_test_support.zig").seedShunnedRepo;
const send_shun_digests = @import("sync_test_support.zig").send_shun_digests;
const send_shun_names = @import("sync_test_support.zig").send_shun_names;
const shun_test_held_name = @import("sync_test_support.zig").shun_test_held_name;
const shun_test_name = @import("sync_test_support.zig").shun_test_name;
const stateOom = diagnostics.stateOom;
const storage = @import("zit").storage;
const storePushCredential = @import("sync_dialogue.zig").storePushCredential;
const storedLoginIn = @import("sync_dialogue.zig").storedLoginIn;
const syncClient = zit.sync_session.syncClient;
const syncIdentityIn = zit.sync_session.syncIdentityIn;
const syncOpenFail = @import("sync_dialogue.zig").syncOpenFail;
const syncRunFail = @import("sync_dialogue.zig").syncRunFail;
const sync_client_version = zit.sync_session.sync_client_version;
const sync_driver = @import("../net/sync_driver.zig");
const sync_projectcode = zit.sync_session.sync_projectcode;
const sync_servercode = zit.sync_session.sync_servercode;
const transport = @import("../net/transport.zig");
const treeManifestBytes = @import("sync_test_support.zig").treeManifestBytes;
const urlUser = @import("sync_dialogue.zig").urlUser;
const writeSyncCursor = zit.sync_session.writeSyncCursor;
const zit = @import("zit");

/// Evidence seam: stored frames `subManifestGaps` read to find references.
/// Zero on a run whose gap index already covered the whole log.
pub var submanifest_gap_walk_rids: u64 = 0;

/// The durable gap index: every sub-manifest reference the stored artifacts
/// make that no stored artifact answered, as a `nameindex` list keyed to the
/// log prefix it covers.
const submanifest_gaps_magic = "ZITSMGP\x00";

const submanifest_gaps_member = "submanifest-gaps";

/// submanifests §7.1 — how many sub-manifest references this repository's
/// stored artifacts make that it does not hold (an elided node under a cone
/// is not one): the gaps a sync or pull reports until the nodes arrive.
///
/// The gap set is a pure function of the durable frames, so it outlives the
/// run that found it without a durable phantom: the index carries it from
/// run to run, each run reads only the frames appended since the index was
/// written, and every carried name is checked against the log again, so a
/// node that arrived closes its gap. A missing or stale index (a pack, a
/// shun rewrite) is one walk of the store. A repository whose §8.1 indicator
/// says it never stored a sub-manifest has no gaps and keeps no index.
fn subManifestGaps(
    gpa: std.mem.Allocator,
    io: std.Io,
    dir: std.Io.Dir,
    log: *logstore.LogStore,
    sparse: ?*const SparseClassification,
) error{ OutOfMemory, Storage, Corrupt }!usize {
    {
        var oc = (try log.readConfig(gpa)) orelse return 0;
        defer oc.deinit(gpa);
        if (!oc.config.seen_submanifest) return 0;
    }
    var arena_state = std.heap.ArenaAllocator.init(gpa);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    var names: std.ArrayListUnmanaged([]const u8) = .empty;
    var after: logstore.Rid = 0;
    var adopted = false;
    if (try zit.repocache.loadMember(gpa, io, dir, submanifest_gaps_member)) |blob| {
        defer gpa.free(blob);
        if (try zit.nameindex.parse(arena, submanifest_gaps_magic, blob, log)) |p| {
            for (p.names) |n| try names.append(arena, try arena.dupe(u8, n));
            after = @intCast(p.n_rids);
            adopted = true;
        }
    }
    const n: logstore.Rid = @intCast(log.entryCount());
    if (after > n) {
        names.clearRetainingCapacity();
        after = 0;
        adopted = false;
    }
    if (after < n) {
        var cache = logstore.PlaintextCache.init();
        defer cache.deinit(gpa);
        var refs: std.ArrayListUnmanaged([]const u8) = .empty;
        defer refs.deinit(gpa);
        var rid: logstore.Rid = after + 1;
        while (rid <= n) : (rid += 1) {
            if (log.isPhantom(rid)) continue;
            submanifest_gap_walk_rids += 1;
            const plain = (try log.contentCached(gpa, rid, &cache)) orelse continue;
            defer gpa.free(plain);
            refs.clearRetainingCapacity();
            if (!try repostate.collectSubManifestRefs(gpa, plain, &refs)) continue;
            for (refs.items) |r| try names.append(arena, try arena.dupe(u8, r));
        }
    }
    // Keep what is still unanswered, once each.
    var seen: std.StringHashMapUnmanaged(void) = .empty;
    defer seen.deinit(gpa);
    var open: std.ArrayListUnmanaged([]const u8) = .empty;
    for (names.items) |name| {
        if ((try seen.getOrPut(gpa, name)).found_existing) continue;
        var digest_buf: [digest_len]u8 = undefined;
        // A name no digest decodes from names nothing this store can hold;
        // the index is advisory, so it is dropped rather than failing the run.
        const digest = decodeWireName(name, &digest_buf) orelse continue;
        if (log.lookup(digest)) |r| if (!log.isPhantom(r)) continue;
        try open.append(arena, name);
    }
    if (!adopted or after < n or open.items.len != names.items.len) {
        if (try zit.nameindex.serialize(gpa, submanifest_gaps_magic, log, n, open.items)) |blob| {
            defer gpa.free(blob);
            zit.repocache.storeNamedMember(io, dir, submanifest_gaps_member, blob);
        }
    }
    var gaps: usize = 0;
    for (open.items) |name| {
        if (sparse) |c| if (c.elidedNode(name)) continue;
        gaps += 1;
    }
    return gaps;
}

/// `subManifestGaps` over the store as it stands after an exchange: the
/// holdings' log when nothing was appended, a fresh read otherwise.
pub fn gapsAfterExchange(
    gpa: std.mem.Allocator,
    io: std.Io,
    dir: std.Io.Dir,
    holdings: *ClientHoldings,
    sparse: ?*const SparseClassification,
) error{ OutOfMemory, Storage, Corrupt }!usize {
    const now = StoreStamp.of(io, dir) orelse return error.Storage;
    if (now.size == holdings.index.log.end) return subManifestGaps(gpa, io, dir, &holdings.index.log, sparse);
    const opened = openStoreLogForRead(gpa, io, dir) catch |e| switch (e) {
        error.OutOfMemory => return error.OutOfMemory,
        else => return error.Storage,
    };
    defer opened.close(gpa, io);
    return subManifestGaps(gpa, io, dir, &opened.log, sparse);
}

// ---------------------------------------------------------------------------
// `zit pull URL` — incremental sync into an EXISTING repository. The sibling of
// clone: it reuses the same transport + `runSync` + persist machinery, but opens
// the cwd's `.zit` (never creating one), announces what it already holds so the
// peer sends only the missing artifacts (sync §3.2/§3.3 igot/gimme), and drives
// to §3.7 termination. Receive-only (§3.3 r24: pull obtains but never uploads).
// ---------------------------------------------------------------------------

/// `zit pull URL` — open the current repository, converge it toward the peer at
/// URL, and persist the newly received artifacts. Thin wiring over the same deep
/// modules clone uses: `transport` (HTTP/IO), `sync.Client` + `runSync` (sans-IO
/// §3.7 loop), and `LogStore` (persistence). With URL omitted the saved remote
/// (`zit remote`) is used; a repo with neither is a usage error. Anonymous only.
pub fn runPull(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    return runPullMode(gpa, io, arena, verb_args, streams, amb, false, false);
}

/// `zit pull` as typed: `runPull`, reporting the forks the pull leaves. The
/// pulls other verbs make for themselves (autosync, demand fetches) stay
/// silent about forks, since the hosting verb owns the exit status.
pub fn runPullVerb(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    return runPullMode(gpa, io, arena, verb_args, streams, amb, false, true);
}

/// Fetch structural closure without changing the stored cone. The peer sees a
/// dense request, while receive filtering still elides out-of-cone file blobs.
pub fn pullCommitDependencies(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    return runPullMode(gpa, io, arena, &.{}, streams, amb, true, false);
}

/// Sparse-cone RFC section 5.1, read side. An origin serving a path cone
/// withholds the sub-manifest nodes whose slots cannot reach it, so a verb
/// that reads a whole check-in tree (ls, cat, tarball, zip, merge, revert)
/// can meet a tree the store holds only in part. Every such request is one
/// the saved remote can answer: the verb records the miss here instead of
/// refusing, the caller fetches the nodes once -- a structural-closure pull,
/// which keeps the store cone and the nodes it brings -- and runs again.
pub const ElidedTree = struct {
    /// The run met withheld nodes and printed nothing: fetch and run again.
    pending: bool = false,
    /// The fetch already ran; a second miss is the remote's, and final.
    fetched: bool = false,

    /// Where a verb maps `ElidedByCone`. Silent on the first run (the
    /// caller fetches); after the fetch, the refusal.
    pub fn note(self: *ElidedTree, s: cli.Streams, verb: []const u8) void {
        if (!self.fetched) {
            self.pending = true;
            return;
        }
        s.err.print("zit {s}: part of this check-in's tree is elided by the store's sparse cone, and the saved remote did not supply it\n", .{verb}) catch {};
    }

    /// After a run that noted a miss: fetch the withheld nodes from the saved
    /// remote. True when the verb should run again; false when it already
    /// failed, with the refusal printed here.
    pub fn fetch(
        self: *ElidedTree,
        gpa: std.mem.Allocator,
        io: std.Io,
        arena: std.mem.Allocator,
        streams: cli.Streams,
        amb: cli.Ambient,
        verb: []const u8,
    ) bool {
        if (!self.pending) return false;
        std.debug.assert(!self.fetched);
        self.pending = false;
        self.fetched = true;
        const root = (cli.resolveRoot(arena, io, amb.repo_override) catch null) orelse return false;
        var dir = root.dir;
        defer dir.close(io);
        var url_buf: [logstore.max_config_str]u8 = undefined;
        _ = resolveRemoteUrl(gpa, io, dir, "", &url_buf) catch {
            streams.err.print(
                "zit {s}: part of this check-in's tree is elided by the store's sparse cone and no remote is saved\n" ++
                    "zit {s}: set one with 'zit remote URL', or widen the cone with 'zit cone add PATH'\n",
                .{ verb, verb },
            ) catch {};
            return false;
        };
        streams.err.print("zit {s}: part of this check-in's tree is elided by the store's sparse cone; fetching from the saved remote\n", .{verb}) catch {};
        var fetch_amb = amb;
        fetch_amb.repo_override = root.abs;
        // The pull's report is the fetch's, not the verb's output.
        if (pullCommitDependencies(gpa, io, arena, .{ .out = streams.err, .err = streams.err }, fetch_amb) != .ok) {
            streams.err.print("zit {s}: the withheld tree nodes could not be fetched\n", .{verb}) catch {};
            return false;
        }
        return true;
    }
};

fn runPullMode(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    structural_closure: bool,
    report_forks: bool,
) cli.Exit {
    const parsed = switch (cli.parsePullArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "pull", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "pull", .extra_argument, tok),
        .bad_resolve => |tok| return cli.usageError(streams, "pull", .bad_resolve, tok),
        .too_many_resolves => |tok| return cli.usageError(streams, "pull", .too_many_resolves, tok),
        // An omitted URL is not an error: it falls back to the saved remote below.
        .no_url => |p| p,
    };
    if (parsed.help) {
        streams.out.writeAll(pull_help) catch {};
        return .ok;
    }

    if (parsed.user) |u| {
        if (u.len > 0 and zit.sync.containsFossilWhitespace(u)) {
            streams.err.writeAll("zit pull: --user must not contain whitespace\n") catch {};
            return .usage;
        }
    }

    // Locate the current repository before any network I/O: a pull outside a repo
    // is a usage failure, not a wasted connection.
    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "pull")) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    if (refusePendingImport(streams, io, root_dir, "pull")) |rc| return rc;
    // The client's holdings view: igot names, held/phantom, shun mask, and
    // hash-policy off the log's frame index, with content lazy (the
    // old whole-store `MemStore` snapshot held the repository's plaintext
    // resident for the run).
    var holdings = ClientHoldings.open(gpa, io, root_dir) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
    };
    defer holdings.deinit(io);
    // The leaves before the exchange tell a fork it made from one already here.
    // Read after the holdings open, which heals a torn final frame: the leaf
    // read is a reader and refuses one.
    var leaves: LeafWatch = undefined;
    if (report_forks and !leaves.open(gpa, io, arena, root_dir, streams, "pull")) return .failure;

    // sync §4/§6 — the explicit URL wins; an omitted one falls back to the saved
    // remote; a repo with neither is a usage error. `url_buf` outlives `open`.
    // Read off the holdings' log, as every config read below is: one open.
    var url_buf: [logstore.max_config_str]u8 = undefined;
    const url = if (parsed.url.len > 0) parsed.url else savedRemoteIn(gpa, &holdings.index.log, &url_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
        error.NoRemote => return noRemoteError(streams, "pull"),
    };

    var tr = transport.Transport.open(io, gpa, url) catch |e|
        return syncOpenFail(streams, "pull", url, e);
    defer tr.close();
    tr.setResolve(parsed.resolve.slice());
    notePlaintext(streams, "pull", url);
    var admission = holdings.admission();
    var latch: ErasureLatch = .{};
    defer latch.deinit(gpa);
    // A pull another verb makes for itself (a structural closure) asks too:
    // the rows it latches are applied on the same terms.
    admission.erasure_latch = &latch;
    var seed_name_buf: [64]u8 = undefined;
    // Sparse-cone RFC section 5.2 rule 3: under a store cone, classify once
    // and suppress spontaneous requests for elided phantoms. Both the
    // classification and the wrapper outlive the run below.
    var sync_cone: ?zit.cone.Cone = null;
    defer if (sync_cone) |*c| c.deinit(gpa);
    var sync_classification: ?SparseClassification = null;
    defer if (sync_classification) |*c| c.deinit(gpa);
    var sync_elided: RepoElidedSet = undefined;
    // The local count the prior cursor recorded as announced to this origin;
    // null when there was no cursor and this pull announces the whole holding.
    var cursor_prior_local: ?repostate.Rid = null;
    if (readSyncCone(gpa, io, root_dir, &holdings)) |c| {
        sync_cone = c;
        sync_classification = zit.sparse.classifyCached(gpa, io, root_dir, &holdings.index.log, holdings.index.classifyStore(), &sync_cone.?, .{ .boundary_transit = true }, .parse) catch
            return stateOom(streams, "pull");
        sync_elided = .{ .classification = &sync_classification.?, .store = holdings.store(), .nodes = !structural_closure };
        admission.elided = sync_elided.shunSet();
        if (!structural_closure) {
            admission.cone_members = sync_cone.?.members;
            admission.cone_not_members = sync_cone.?.not_members;
            admission.cone_parents = sync_cone.?.parents;
        }
        admission.horizon = sync_cone.?.horizon;
        admission.seed_held = heldSeedName(gpa, io, root_dir, &seed_name_buf);
        // The cursor is a position in what the origin served the cone's
        // request. A structural closure asks without path members, so the
        // origin serves it the nodes the cone's request was never sent:
        // under that cursor it would not announce them again.
        if (!structural_closure) {
            if (readSyncCursor(gpa, io, root_dir, url, &sync_cone.?, holdings.logBackedCount())) |cur| {
                admission.horizon_cursor = cur.peer;
                admission.announce_from = cur.local + 1;
                cursor_prior_local = cur.local;
            }
        }
    }

    // §9.1 — announce this repository's adopted project code in the pull card;
    // a real peer refuses a PROJECTCODE mismatch, so the placeholder cannot be
    // sent against fossil. The buffer outlives the run (the client borrows it).
    // The cluster index: what the held clusters already announce
    // (never announced again individually) and what they promised that this
    // repository never collected (seeded as phantoms, so the run asks for it).
    // The clusters' plaintext is memoised by the holdings adapter while it
    // resolves; drop it — the index keeps only names and bits.
    var clusters = loadClusterIndex(gpa, io, root_dir, &holdings.index.log, holdings.store()) catch return stateOom(streams, "pull");
    defer clusters.deinit();
    holdings.index.releaseTransient();

    var pc_buf: [zit.sync.max_projectcode_len]u8 = undefined;
    const identity = syncIdentityIn(gpa, &holdings.index.log, root.abs, &pc_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
    };

    // sync §6 — a read of a private repository is as gated as a write. The
    // login comes from --user, the URL's user@, or the login a previous
    // authenticated push or pull stored here; with none the pull is anonymous.
    var pw_buf: [max_password_len]u8 = undefined;
    defer std.crypto.secureZero(u8, &pw_buf);
    var user_buf: [logstore.max_config_str]u8 = undefined;
    const stored_login = storedLoginIn(gpa, &holdings.index.log) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
    };
    const resolved = resolveCredential(stored_login, streams, identity.project_code, .{ .url = url, .user = parsed.user, .password = parsed.password }, amb, &pw_buf, &user_buf) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
        error.NoPassword => {
            streams.err.print("zit pull: no password for '{s}' (give --password, set ZIT_PASSWORD, or run on a terminal)\n", .{parsed.user orelse urlUser(url) orelse ""}) catch {};
            return .failure;
        },
    };

    // Live per-round progress on a terminal, the same sink clone uses.
    const stderr_tty = std.Io.File.stderr().isTty(io) catch false;
    var progress: CloneProgress = .{ .err = streams.err };
    const sink: ?sync_driver.RoundSink = if (stderr_tty) .{ .ctx = &progress, .emit = CloneProgress.emit } else null;
    defer progress.finishLine();
    if (resolved) |r| armBasicAuth(&tr, r.credential.user, r.plaintext) catch return stateOom(streams, "pull");
    var truncated: u64 = 0;
    defer reportTruncatedPayloads(streams, "pull", truncated);
    // Sparse-cone RFC section 6.3 applies to EVERY receive: a dense peer
    // volunteers content the client never announced, so the filter runs at
    // persist. Reclassified over the post-run store after every run, the
    // horizon reruns below included, so a brand-new commit's blobs classify
    // by their own F cards -- new in-cone content persists, new out-of-cone
    // content elides with the rest.
    var post_classification: ?SparseClassification = null;
    defer if (post_classification) |*c| c.deinit(gpa);
    const post: ?PostClassify = if (sync_cone) |*c| .{
        .cone = c,
        .out = &post_classification,
        .settle_nodes = !structural_closure,
        .cached = .{ .io = io, .root_dir = root_dir, .holdings = &holdings },
    } else null;
    var peer_error: PeerErrorCopy = .{};
    var outcome = pullRun(gpa, &tr, holdings.store(), identity, if (resolved) |r| r.credential else null, admission, sink, &clusters, &truncated, post, &peer_error) catch |e| {
        // As for push: a refusal is quoted in the server's own words.
        if (e == error.FatalProtocolError) {
            if (peer_error.text()) |text| {
                reportPeerRefusal(streams, "pull", text);
                return .failure;
            }
        }
        return syncRunFail(streams, "pull", url, e, &tr);
    };
    defer if (outcome.seed) |b| gpa.free(b);
    // Horizon draft sections 6.2.5 and 6.3 -- an origin that did not serve
    // the structural horizon sent no seed and no labels: the store falls
    // back to the content horizon, and the reruns below fetch the manifests
    // below C that the content depth holds and the structural one did not.
    var fell_back = false;
    // Horizon draft section 5.2.4 -- a seed bound to another horizon, or
    // dated before the one held, is refused as a wrongly signed one is: the
    // store falls back to the content horizon.
    var served = outcome.horizon_served;
    if (sync_cone) |*c| if (c.horizon) |h| if (h.depth == .structural) if (outcome.seed) |b| {
        const held = zit.repocache.readHorizonSeed(gpa, io, root_dir);
        defer if (held) |hb| gpa.free(hb);
        const verdict = zit.sync.judgeSeed(gpa, b, h, held) catch return stateOom(streams, "pull");
        switch (verdict) {
            .ok => {},
            .unbound => streams.err.writeAll("zit pull: the origin's seed is not bound to this store's horizon check-in and rule; refusing it\n") catch {},
            .older => streams.err.writeAll("zit pull: the origin's seed is dated before the one held, a replay; refusing it\n") catch {},
        }
        if (verdict != .ok) {
            gpa.free(b);
            outcome.seed = null;
            served = .content;
        }
    };
    if (sync_cone) |*c| {
        fell_back = fallBackToContent(gpa, io, root_dir, streams, "pull", c, served) catch return stateOom(streams, "pull");
        if (fell_back) {
            admission.horizon = c.horizon;
            if (!structural_closure) {
                admission.cone_members = c.members;
                admission.cone_not_members = c.not_members;
                admission.cone_parents = c.parents;
            }
            admission.seed_held = null;
            // The cursor was handed out for the structural cone's keep set,
            // which omits what the content one keeps: announce in full.
            admission.horizon_cursor = null;
            admission.announce_from = 1;
            cursor_prior_local = null;
        }
    }
    // Horizon draft section 4.2 -- elision is a function of K, and K grows as
    // check-ins arrive: a blob elided when this pull began is above the
    // horizon once an arriving check-in in K names it, and the origin's
    // cursor never announces it again. So classify what arrived, and run
    // again while that unveils phantoms the run was told to leave alone.
    if (sync_cone) |*c| if (c.horizon != null) {
        var again: usize = 0;
        while (again < max_horizon_pull_reruns) : (again += 1) {
            const unveiled = reclassifyPull(gpa, io, root_dir, &holdings, c, &sync_classification.?) catch return stateOom(streams, "pull");
            // After a fallback the run's post-classification is the
            // structural cone's, which drops the manifests below C that
            // arrived: one more run classifies them under the content cone.
            if (!unveiled and !(fell_back and again == 0)) break;
            const more = pullRun(gpa, &tr, holdings.store(), identity, if (resolved) |r| r.credential else null, admission, sink, &clusters, &truncated, post, null) catch |e|
                return syncRunFail(streams, "pull", url, e, &tr);
            outcome.absorb(gpa, more);
        }
    };
    // Horizon draft section 5.2 -- a re-minted seed replaces the held one; the
    // next open applies it, and the later D card wins by timestamp.
    if (outcome.seed) |b| {
        if (sync_cone) |*c| if (c.horizon != null and c.horizon.?.depth == .structural) zit.repocache.writeHorizonSeed(io, root_dir, b);
    }

    // Persist a freshly derived secret only after the peer accepted the
    // authenticated session (mirrors push and sync).
    if (resolved) |r| {
        // --once authenticates this run and saves nothing.
        if (r.persist and !parsed.once) {
            const saved = storePushCredential(gpa, io, root_dir, r.credential, url) catch |e| switch (e) {
                error.OutOfMemory => return stateOom(streams, "pull"),
                else => return repoReadFail(streams, "pull"),
            };
            if (!saved) noteLoginNotSaved(streams, "pull", url);
        }
    }

    // Persist only what this pull received. The holdings store appends
    // received artifacts beyond its log-backed prefix, so the walk begins at that
    // boundary and never re-visits the already-durable holdings. A pull that
    // received nothing persists nothing: a no-op pull was O(store) here (every
    // holding read once from disk to be early-returned), 196 s on a 905k store.
    const persisted = persistStore(gpa, io, root_dir, holdings.store(), if (post_classification) |*c| c else null, holdings.logBackedCount()) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        error.Storage => return repoReadFail(streams, "pull"),
        error.StoreBusy => return .failure, // the lock notice already said it
        error.Corrupt => return renderStorage(streams, root.abs, "the peer sent a malformed artifact name"),
    };
    // The walk started past the holdings, so `written` is exactly the received
    // count (each received artifact is persisted once).
    const received = persisted.written;
    // Last, on every exit from here, as for sync.
    var erasures_deferred: ?usize = null;
    defer if (erasures_deferred == null) {
        _ = applySessionErasures(gpa, io, root_dir, streams, "pull", &holdings.index.log, latch.rows.items, true);
    };

    // The peer named artifacts this run never obtained. Everything is persisted
    // — a partial pull is still progress — but the exit status says so, because
    // "exit 0 with nothing said" is indistinguishable from a converged sync and
    // leaves a repository quietly out of date. This holds whether `received` is
    // zero or not: the invariant is convergence, not motion.
    // A promise a held cluster made that this peer could not keep is
    // reported, not failed on: the run asked on its own initiative (no peer
    // igot set the expectation) and the repository IS converged against this
    // peer. Fossil asks for these every round, silently; zit says so once.
    if (outcome.cluster_gaps > 0) {
        streams.err.print(
            "zit pull: {d} artifact{s} named by held clusters could not be obtained from this peer\n",
            .{ outcome.cluster_gaps, plural(outcome.cluster_gaps) },
        ) catch {};
    }
    if (outcome.unresolved > 0) {
        streams.err.print(
            "zit pull: the peer holds {d} artifacts this pull did not obtain\n",
            .{outcome.unresolved},
        ) catch {};
        return .failure;
    }

    // submanifests §7.1/§7.3 — the same reasoning one level down. A pull can
    // converge against the peer (nothing left to gimme) while the tree closure
    // this repository now holds is still open, because the peer's own closure
    // was open: §7.1's "at most d+1 pull rounds" bounds a tree whose levels are
    // ARRIVING, not one whose leaves nobody has. The phantoms the persist hook
    // minted are that distinction, so report them rather than call it converged.
    // They are counted over the whole store, not just what this run stored
    // (`subManifestGaps`), so a gap stays reported until its node arrives.
    //
    // §7.3/§9.4 — two counts, because they answer different questions and the
    // draft names both: `submanifest_gaps` is the durable store's missing-hash
    // count, `deferred_trees` is the session's DEPENDENT-keyed record ("enough
    // to rediscover that manifest"). A run reporting the first without the
    // second tells the operator something is missing but not what it breaks.
    const submanifest_gaps = gapsAfterExchange(gpa, io, root_dir, &holdings, if (post_classification) |*c| c else null) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "pull"),
        else => return repoReadFail(streams, "pull"),
    };
    if (submanifest_gaps > 0 or outcome.deferred_trees > 0) {
        // Two sentences, not one, because the two counts have different
        // LIFETIMES and a single sentence reads as one fact. `submanifest_gaps`
        // is a property of the durable store and survives a restart;
        // `deferred_trees` is this SESSION's §9.4 record and is zero for a run
        // that received no S card — including every re-run against an already
        // open closure. Printed together they said "N references are missing; 0
        // check-ins cannot be enumerated", which is exactly backwards.
        if (submanifest_gaps > 0) {
            streams.err.print(
                "zit pull: {d} sub-manifest references are missing; the check-ins that reference them cannot be enumerated\n",
                .{submanifest_gaps},
            ) catch {};
        }
        if (outcome.deferred_trees > 0) {
            streams.err.print(
                "zit pull: {d} check-ins received this session are deferred until they arrive\n",
                .{outcome.deferred_trees},
            ) catch {};
        }
        return .failure;
    }

    // Under -F json the counts are the object's, and stdout holds only it.
    if (received == 0) {
        if (!parsed.json) streams.out.print("pull from {s}: already in sync\n", .{url}) catch {};
    } else {
        if (!parsed.json) streams.out.print("pull from {s}: received {d} artifact{s} in {d} round{s}\n", .{ url, received, plural(received), outcome.rounds, plural(outcome.rounds) }) catch {};
        reportUvSkipped(streams, "pull", outcome.uv_skipped);
        if (outcome.cone_mode == .filtered or outcome.cone_mode == .mixed) {
            streams.err.print("zit pull: cone {s}\n", .{outcome.cone_mode.phrase()}) catch {};
        }
    }
    // Horizon draft section 6.2.6 -- a converged pull moves the cursor: the
    // origin's position from its replies (kept when it named none), and the
    // local count the origin HOLDS. A pull delivers nothing of this store's
    // (announcing is not sending), so it may advance that count only past
    // what it received, and only when nothing undelivered preceded them;
    // otherwise the count stays and the next push announces from there.
    // Without a prior cursor nothing is known delivered, and the next push
    // announces the whole holding once. (A pull that recorded its whole log
    // made a commit before it vanish from every later push; the origin then
    // held that commit's children without their parent.)
    if (sync_cone != null and !structural_closure) {
        const before = holdings.logBackedCount();
        const local: repostate.Rid = if (cursor_prior_local) |prior|
            (if (prior == before) before + persisted.written else prior)
        else
            0;
        writeSyncCursor(gpa, io, root_dir, url, &sync_cone.?, .{
            .peer = outcome.peer_cursor orelse admission.horizon_cursor,
            .local = local,
        });
    }
    if (outcome.horizon_served != null) zit.repocache.writeHorizonUrl(io, root_dir, outcome.horizon_url.get());
    if (!report_forks) return .ok;
    // Before the JSON is written, so the object can say what did not land.
    erasures_deferred = applySessionErasures(gpa, io, root_dir, streams, "pull", &holdings.index.log, latch.rows.items, true);
    return finishExchange(gpa, io, arena, root_dir, streams, "pull", &leaves, parsed.json, .{
        .sent = null,
        .received = received,
        .rounds = outcome.rounds,
        .erasures_deferred = erasures_deferred.?,
    });
}

/// Horizon draft section 5.5 / 6.2.4 -- ask the saved remote for the pivot of
/// `primary` against `secondaries`, which this clone cannot compute (some
/// side's ancestry lies below its horizon). Runs one ordinary pull against
/// the saved remote with the query attached.
/// Returns the base's hash copied into `out`, an empty slice when the origin
/// answered "no common ancestor", and null when it did not answer or the
/// pull could not run (the caller prints what it printed).
pub fn queryMergeBase(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    amb: cli.Ambient,
    primary: []const u8,
    secondaries: []const []const u8,
    out: *[64]u8,
) ?[]const u8 {
    var url_buf: [logstore.max_config_str]u8 = undefined;
    const url = resolveRemoteUrl(gpa, io, root_dir, "", &url_buf) catch return null;
    var tr = transport.Transport.open(io, gpa, url) catch return null;
    defer tr.close();
    var holdings = ClientHoldings.open(gpa, io, root_dir) catch return null;
    defer holdings.deinit(io);
    var admission = holdings.admission();
    var seed_name_buf: [64]u8 = undefined;
    var sync_cone: ?zit.cone.Cone = null;
    defer if (sync_cone) |*c| c.deinit(gpa);
    var sync_classification: ?SparseClassification = null;
    defer if (sync_classification) |*c| c.deinit(gpa);
    var sync_elided: RepoElidedSet = undefined;
    if (readSyncCone(gpa, io, root_dir, &holdings)) |c| {
        sync_cone = c;
        sync_classification = zit.sparse.classifyCached(gpa, io, root_dir, &holdings.index.log, holdings.index.classifyStore(), &sync_cone.?, .{ .boundary_transit = true }, .parse) catch return null;
        sync_elided = .{ .classification = &sync_classification.?, .store = holdings.store() };
        admission.elided = sync_elided.shunSet();
        admission.cone_members = sync_cone.?.members;
        admission.cone_not_members = sync_cone.?.not_members;
        admission.cone_parents = sync_cone.?.parents;
        admission.horizon = sync_cone.?.horizon;
        admission.seed_held = heldSeedName(gpa, io, root_dir, &seed_name_buf);
        if (readSyncCursor(gpa, io, root_dir, url, &sync_cone.?, holdings.logBackedCount())) |cur| {
            admission.horizon_cursor = cur.peer;
            admission.announce_from = cur.local + 1;
        }
    }
    admission.mergebase_query = .{ .primary = primary, .secondaries = secondaries };
    holdings.index.releaseTransient();
    var pc_buf: [zit.sync.max_projectcode_len]u8 = undefined;
    const identity = repoSyncIdentity(gpa, io, root_dir, "", &pc_buf) catch return null;
    var pw_buf: [max_password_len]u8 = undefined;
    defer std.crypto.secureZero(u8, &pw_buf);
    var user_buf: [logstore.max_config_str]u8 = undefined;
    const resolved = resolvePushCredential(gpa, io, root_dir, streams, identity.project_code, .{ .url = url, .user = null, .password = null }, amb, &pw_buf, &user_buf) catch return null;
    if (resolved) |r| armBasicAuth(&tr, r.credential.user, r.plaintext) catch return null;
    var truncated: u64 = 0;
    const outcome = pullRun(gpa, &tr, holdings.store(), identity, if (resolved) |r| r.credential else null, admission, null, null, &truncated, null, null) catch return null;
    defer if (outcome.seed) |sb| gpa.free(sb);
    if (!outcome.mergebase_answered) return null;
    @memcpy(out[0..outcome.mergebase_len], outcome.mergebase_buf[0..outcome.mergebase_len]);
    return out[0..outcome.mergebase_len];
}

/// Horizon draft section 5.8 -- where a deepen that must reach `target` moves
/// C. A deepen moves C to an ancestor of C, so K only grows; moving C to
/// `target` itself is one only when `target` is C's ancestor, and otherwise
/// drops C's own descendants out of every later pull. A common ancestor of
/// the two always is: from this store's own derivation when it holds both
/// (any common ancestor serves, the nearest is only the cheapest), else the
/// origin's merge-base answer. Null, with the refusal printed, when neither
/// names one: there is then no point a deepen may move C to.
pub fn deepenPoint(
    gpa: std.mem.Allocator,
    io: std.Io,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    amb: cli.Ambient,
    verb: []const u8,
    c: []const u8,
    target: []const u8,
    out: *[64]u8,
) ?[]const u8 {
    if (std.ascii.eqlIgnoreCase(c, target)) return target;
    local: {
        var repo: Repository = undefined;
        Repository.open(&repo, gpa, io, root_dir, .{ .mode = .fast_read }) catch break :local;
        defer repo.deinit(gpa);
        const rc = repo.lookup(c) orelse break :local;
        const rt = repo.lookup(target) orelse break :local;
        if (!repo.view.state.hasEvent(rc) or !repo.view.state.hasEvent(rt)) break :local;
        const base = (repo.mergeBaseOf(gpa, rc, rt) catch break :local) orelse break :local;
        const h = repo.hashOf(base);
        @memcpy(out[0..h.len], h);
        return out[0..h.len];
    }
    if (queryMergeBase(gpa, io, root_dir, streams, amb, target, &.{c}, out)) |base| {
        if (base.len != 0) return base;
    }
    streams.err.print(
        "zit {s}: no common ancestor of the store's horizon {s} and {s} is known here or at the saved remote, so no deepen reaches it\n" ++
            "zit {s}: re-clone with an earlier --horizon\n",
        .{ verb, cli.shortHash(c), cli.shortHash(target), verb },
    ) catch {};
    return null;
}

/// What one pull run reports: the round count, and how many artifacts the peer
/// announced (§3.3 r24 — by igot, or as a member of a cluster it sent) that this
/// side still lacks when §3.7 reached its clean terminal. A nonzero `unresolved`
/// is a pull that stopped short of what it was told existed; the caller must not
/// report success for it, however well-formed every card on the wire was.
/// submanifests §7.3/§9.4 — `deferred_trees` is the §9.4 record read back: the
/// count of DEPENDENTS (check-ins) whose processing this session deferred on a
/// sub-manifest that never arrived. `unresolved` counts missing HASHES; a
/// dependent-keyed count is what §9.4 requires be recorded and is what an
/// operator can act on ("which check-in is broken", not "how many blobs").
/// Horizon draft section 4.2 -- how many times one pull re-runs after K
/// grew under it. Each re-run needs the classification to have unveiled a
/// phantom the previous run left alone, and K only grows, so this is a
/// backstop: a structural clone's closure deepens one B or S level a run.
pub const max_horizon_pull_reruns: usize = 64;

/// Horizon draft section 5.8 -- deepen: write the cone whose horizon is the
/// new C', discard the seed for the old C (its later-dated application would
/// shadow propagation from the new one), and run an ordinary pull, which then
/// asks for K(C'). A pull that fails puts the old cone and seed back: the
/// deepen never reached the origin, and a horizon moved without the content
/// behind it would leave the store calling what it lacks missing, not elided.
pub fn deepenHorizon(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    root_dir: std.Io.Dir,
    streams: cli.Streams,
    verb: []const u8,
    deepened: *const zit.cone.Cone,
) cli.Exit {
    std.debug.assert(deepened.horizon != null);
    var old = zit.repocache.readStoreCone(gpa, io, root_dir);
    defer if (old) |*c| c.deinit(gpa);
    const old_seed = zit.repocache.readHorizonSeed(gpa, io, root_dir);
    defer if (old_seed) |b| gpa.free(b);
    if (deepened.horizon.?.depth == .structural) zit.repocache.writeHorizonSeed(io, root_dir, null);
    zit.repocache.writeStoreCone(gpa, io, root_dir, deepened);
    // A demand fetch has no ambient environment of its own; the stored login
    // still authenticates, and a prompt is never raised from here.
    const pull_exit = runPull(gpa, io, arena, &.{}, streams, .{ .now_epoch = 0, .user_env = null });
    if (pull_exit == .ok) return .ok;
    zit.repocache.writeStoreCone(gpa, io, root_dir, if (old) |*c| c else null);
    if (old_seed) |b| zit.repocache.writeHorizonSeed(io, root_dir, b);
    streams.err.print("zit {s}: the deepen did not reach the origin; the store's horizon is unchanged\n", .{verb}) catch {};
    return pull_exit;
}

test "submanifests §7.1: a sub-manifest gap outlives the run that found it, walking only what was appended since" {
    // Sync and pull persist only what arrived, so the gap a tree left open
    // must be carried by the durable gap index from run to run: still
    // reported by a run that receives nothing, closed by the run that
    // brings the node, and never paid for with a walk of the whole store.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try d4SeedEmptyRepo(gpa, io, tmp.dir);

    const leaf_a = "F a.txt " ++ (repeat("1", 64)) ++ "\n";
    const leaf_b = "F b.txt " ++ (repeat("2", 64)) ++ "\n";
    var an: [64]u8 = undefined;
    var bn: [64]u8 = undefined;
    const name_a = zit.artifact.artifactName(.sha3_256, leaf_a, &an);
    const name_b = zit.artifact.artifactName(.sha3_256, leaf_b, &bn);
    const tree = try treeManifestBytes(gpa, &.{ name_a, name_b });
    defer gpa.free(tree);
    var tn: [64]u8 = undefined;
    const tree_name = zit.artifact.artifactName(.sha3_256, tree, &tn);

    var ms = repostate.MemStore.init(gpa);
    defer ms.deinit();
    _ = try ms.store().put(tree_name, tree);
    _ = try persistStore(gpa, io, tmp.dir, ms.store(), null, 0);

    const Probe = struct {
        fn gaps(dir: std.Io.Dir, walked: *u64) !usize {
            var fs: storage.FileStorage = undefined;
            var log = try d4OpenLog(std.testing.allocator, std.testing.io, dir, &fs);
            defer fs.file.close(std.testing.io);
            defer log.deinit(std.testing.allocator);
            const before = submanifest_gap_walk_rids;
            const n = try subManifestGaps(std.testing.allocator, std.testing.io, dir, &log, null);
            walked.* = submanifest_gap_walk_rids - before;
            return n;
        }
    };
    var walked: u64 = 0;
    // First run: no index yet, so the store is walked once.
    try std.testing.expectEqual(@as(usize, 2), try Probe.gaps(tmp.dir, &walked));
    try std.testing.expectEqual(@as(u64, 1), walked);
    // A run that received nothing: same gap, nothing walked.
    try std.testing.expectEqual(@as(usize, 2), try Probe.gaps(tmp.dir, &walked));
    try std.testing.expectEqual(@as(u64, 0), walked);
    // One node arrives: one gap left, and only the new frame is read.
    _ = try ms.store().put(name_a, leaf_a);
    _ = try persistStore(gpa, io, tmp.dir, ms.store(), null, 1);
    try std.testing.expectEqual(@as(usize, 1), try Probe.gaps(tmp.dir, &walked));
    try std.testing.expectEqual(@as(u64, 1), walked);
    _ = try ms.store().put(name_b, leaf_b);
    _ = try persistStore(gpa, io, tmp.dir, ms.store(), null, 2);
    try std.testing.expectEqual(@as(usize, 0), try Probe.gaps(tmp.dir, &walked));
}

test "submanifests §8.1: a repository that never stored a sub-manifest keeps no gap index" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try d4SeedEmptyRepo(gpa, io, tmp.dir);
    var ms = repostate.MemStore.init(gpa);
    defer ms.deinit();
    var nm: [64]u8 = undefined;
    _ = try ms.store().put(zit.artifact.artifactName(.sha3_256, "plain", &nm), "plain");
    _ = try persistStore(gpa, io, tmp.dir, ms.store(), null, 0);
    var fs: storage.FileStorage = undefined;
    var log = try d4OpenLog(gpa, io, tmp.dir, &fs);
    defer fs.file.close(io);
    defer log.deinit(gpa);
    const before = submanifest_gap_walk_rids;
    try std.testing.expectEqual(@as(usize, 0), try subManifestGaps(gpa, io, tmp.dir, &log, null));
    try std.testing.expectEqual(before, submanifest_gap_walk_rids);
}

test "sync §3.3 L553-556: a pull client carrying the repository shun set creates the phantom but never gimme's it" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try seedShunnedRepo(gpa, io, tmp.dir);

    var holdings = try ClientHoldings.open(gpa, io, tmp.dir);
    defer holdings.deinit(io);

    // The pull client, constructed exactly as `pullRun` does.
    var client = zit.sync.Client{
        .state = zit.sync.initialState(.pull),
        .operation = .pull,
        .self_servercode = sync_servercode,
        .project_code = sync_projectcode,
        .version = .{ .version = sync_client_version },
        .shun = holdings.admission().shun,
    };
    defer client.deinit(gpa);

    // The peer announces BOTH artifacts. §3.3 r24(1) is unconditional on the
    // shun table, so the shunned one still becomes a phantom.
    const reply = "pragma server-version 1\nigot " ++ shun_test_name ++ "\n";
    const obs = try client.consumeReply(gpa, holdings.store(), reply);
    try std.testing.expect(obs.phantom_created);
    try std.testing.expectEqual(@as(usize, 1), client.phantoms.count());

    // …and the request never asks for it, in any round.
    var buf: std.ArrayListUnmanaged(u8) = .empty;
    defer buf.deinit(gpa);
    var round: usize = 0;
    while (round < 3) : (round += 1) {
        const request = try client.buildRequest(gpa, holdings.store(), &buf);
        try std.testing.expect(std.mem.indexOf(u8, request, "gimme " ++ shun_test_name) == null);
        // The held artifact is still announced — nothing else changed.
        try std.testing.expect(std.mem.indexOf(u8, request, "igot " ++ shun_test_held_name) != null);
    }
}

test "horizon §5.2.3: a pull client never asks again for a seed its store recorded as dropped, and asks for one it did not" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    const dropped = "d772be953838592e4b9296bb15e1232f821f029cfb7c93f592f027d616502e4d";
    for ([_]bool{ true, false }) |recorded| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try d4SeedEmptyRepo(gpa, io, tmp.dir);
        // Recorded in upper case: the record and the wire may differ in case.
        if (recorded) try zit.repocache.recordDroppedSeeds(gpa, io, tmp.dir, &.{"D772BE953838592E4B9296BB15E1232F821F029CFB7C93F592F027D616502E4D"});

        var holdings = try ClientHoldings.open(gpa, io, tmp.dir);
        defer holdings.deinit(io);
        var client = zit.sync.Client{
            .state = zit.sync.initialState(.pull),
            .operation = .pull,
            .self_servercode = sync_servercode,
            .project_code = sync_projectcode,
            .version = .{ .version = sync_client_version },
            .shun = holdings.admission().shun,
        };
        defer client.deinit(gpa);
        _ = try client.consumeReply(gpa, holdings.store(), "pragma server-version 1\nigot " ++ dropped ++ "\n");
        var buf: std.ArrayListUnmanaged(u8) = .empty;
        defer buf.deinit(gpa);
        const request = try client.buildRequest(gpa, holdings.store(), &buf);
        const asked = std.mem.indexOf(u8, request, "gimme " ++ dropped) != null;
        try std.testing.expectEqual(!recorded, asked);
        // Nothing missing either way it is left alone.
        if (recorded) try std.testing.expectEqual(@as(usize, 0), client.unresolvedPhantoms(holdings.store()));
    }
}

test "sync §3.3 L553-556: the CLIENT's holdings snapshot carries the same masked-basis guard — a surviving delta on a masked base is held as full content" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    // The same `zit shun --defer` shape as the serve-side test above, asked of
    // the CLIENT's builder: `ClientHoldings`, which every `zit pull`/`push`/
    // `sync` client announces from. Serving the delta wire form would give the
    // snapshot an entry that `held()` calls true but whose DELTASRC names a
    // masked basis — so §3.2's igot walk would announce a name the gimme send
    // gate can never answer, and a push would spin the round with nothing to
    // send while reporting success. The artifact itself is NOT shunned; only
    // its basis is.
    const base_plain = "the quick brown fox jumps over the lazy dog, and then again once more";
    const child_plain = "the quick brown fox jumps over the lazy dog, and then twice more, at last";
    const hk: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
    {
        var f = try tmp.dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
        defer f.close(io);
        var fs = storage.FileStorage.init(io, f, 0);
        var log = try logstore.LogStore.open(gpa, fs.storageFile(), hk);
        defer log.deinit(gpa);
        try log.putConfig(.{ .hash_policy = hk, .default_branch = "trunk", .project_id = "", .project_code = "" });
        const base_rid = try log.put(send_shun_digests[0], base_plain);
        const d = try zit.delta.create(gpa, base_plain, child_plain);
        defer gpa.free(d);
        _ = try log.putDelta(send_shun_digests[1], base_rid, d);
        try log.putShun(send_shun_digests[0], "operator request", 1);
        try log.commit();
    }

    var holdings = try ClientHoldings.open(gpa, io, tmp.dir);
    defer holdings.deinit(io);
    const s = holdings.store();

    // The masked basis is ABSENT from the name map — `lookup` answers null,
    // which IS §3.3 L569-572's "If absent, silently skip" on the gimme path —
    // and a peer-announced intern lands on the masked slot rather than minting
    // a second identity: held by nothing, readable as nothing.
    try std.testing.expect(s.lookup(send_shun_names[0]) == null);
    const base_rid = try s.intern(send_shun_names[0]);
    try std.testing.expect(!s.held(base_rid));
    try std.testing.expect(s.content(base_rid) == null);

    // The survivor is held AND readable — held-ness and readability agree, which
    // is the property a recorded dangling delta would have broken.
    const child_rid = s.lookup(send_shun_names[1]).?;
    try std.testing.expect(s.held(child_rid));
    try std.testing.expectEqualStrings(child_plain, s.content(child_rid).?);
    try std.testing.expect(s.wire(child_rid) == null); // full content, no DELTASRC to dangle on
}

test "sync §7.7 L1463-1467: ClientHoldings carries the stored hash-policy into the one place a Client is built from repository state" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try s77SeedPolicyRepo(gpa, io, tmp.dir, .shun_sha1);

    var holdings = try ClientHoldings.open(gpa, io, tmp.dir);
    defer holdings.deinit(io);
    const admission = holdings.admission();
    try std.testing.expectEqual(artifact.HashPolicy.shun_sha1, admission.hash_policy);

    // `syncClient` is the sole construction `pullRun`/`pushRun`/`syncRun` share,
    // so this one assertion covers all three verbs: a client that dropped either
    // half of `RepoAdmission` would apply half a filter with nothing failing.
    // A placeholder identity: this test is about `RepoAdmission`, and the
    // sub-manifest half of the same client is covered by the §7.2 tests.
    const identity: RepoSyncIdentity = .{ .project_code = "", .seen_submanifest = false, .enable_submanifests = false, .server_code = zit.sync.deriveServerCode(&.{"test-fixture-repo"}) };
    for ([_]zit.sync.Operation{ .pull, .push, .sync }) |op| {
        const client = syncClient(op, &identity, null, admission);
        try std.testing.expectEqual(op, client.operation);
        try std.testing.expectEqual(artifact.HashPolicy.shun_sha1, client.hash_policy);
        // A 40-hex name is rejected by the very predicate this policy feeds.
        try std.testing.expectEqual(
            zit.sync.Admission.reject,
            zit.sync.admitInbound(client.hash_policy, client.shun, repeat("a", 40)),
        );
    }

    // And the `.auto` repository next door admits the same name, so the
    // assertion above is reading the stored byte and not a constant.
    var tmp2 = std.testing.tmpDir(.{});
    defer tmp2.cleanup();
    try s77SeedPolicyRepo(gpa, io, tmp2.dir, .auto);
    var holdings2 = try ClientHoldings.open(gpa, io, tmp2.dir);
    defer holdings2.deinit(io);
    const admission2 = holdings2.admission();
    try std.testing.expectEqual(artifact.HashPolicy.auto, admission2.hash_policy);
    const c2 = syncClient(.pull, &identity, null, admission2);
    try std.testing.expectEqual(
        zit.sync.Admission.admit,
        zit.sync.admitInbound(c2.hash_policy, c2.shun, repeat("a", 40)),
    );
}

test "sync §7.7 L1463-1467: a DAMAGED repository never yields a hash-policy — the admission predicate fails the load rather than defaulting" {
    // The property: no damaged repository may hand the receiver a policy value.
    // `readConfig` answers `Corrupt`/`Storage` for a config frame that will not
    // read or will not parse, and that is UNKNOWN, not "no defined policy":
    // answering `.auto` there would silently disable shun-sha1 and admit
    // SHA1-named content this repository is configured to refuse, with nothing
    // failing. §3.3's shun half already refuses to fail open (`RepoShunSet.load`
    // propagates, and `serveRound` returns `error.ServerStorage` rather than
    // serving tableless); the two halves of one predicate must not differ.
    //
    // HONESTY ABOUT WHAT THIS PINS: with the injury below, the fault is caught
    // UPSTREAM, at `LogStore.openReadOnly`, so this test does not by itself kill
    // a mutant that restores `effectiveHashPolicy`'s old blanket
    // `catch return .auto` — verified by applying that mutant, which leaves the
    // suite green. It is here as the end-to-end guard: the day the log open grows
    // tolerant of a damaged frame, the read below must still not answer `.auto`.
    // Pinning `effectiveHashPolicy`'s own catch would need a storage layer that
    // faults a single frame read, which this tree does not have.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try s77SeedPolicyRepo(gpa, io, tmp.dir, .shun_sha1);

    // Damage the config frame in place: its default_branch bytes are on disk
    // verbatim, so overwriting them is a one-frame injury that leaves every other
    // frame — and the log's own scan — intact.
    {
        var f = try tmp.dir.openFile(io, repo_filename, .{ .mode = .read_write });
        defer f.close(io);
        const st = try f.stat(io);
        const buf = try gpa.alloc(u8, st.size);
        defer gpa.free(buf);
        var r = f.reader(io, buf);
        try r.interface.readSliceAll(buf);
        const at = std.mem.indexOf(u8, buf, "trunk") orelse return error.TestUnexpectedResult;
        var w = f.writer(io, &.{});
        try w.seekTo(at);
        try w.interface.writeAll("\xff\xff\xff\xff\xff");
        try w.interface.flush();
    }

    try std.testing.expectError(error.Storage, ClientHoldings.open(gpa, io, tmp.dir));
}