Skip to content
suit Artifact [7604d47e6d]
Login

Artifact [7604d47e6d]

Artifact 7604d47e6de577ca2d7073e46330218d2ef1ae423d417022e0fd01f4bc76d97a:


#include "store.h"

#include "attention.h"
#include "conf.h"
#include "lint.h"
#include "machine.h"
#include "platform.h"
#include "remote.h"
#include "stamp.h"
#include "store_fs.h"
#include "upstream.h"

#include "libfossil.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

constexpr size_t PATH_CAP = 4096;

// Every command is a list of steps run in order. A step is one libfossil call
// or one small decision of ours, and returns 0 to go on, STEP_DONE to stop
// with the exit code in Store.exit_code, STEP_ERR after reporting its own
// error, or a libfossil result code, which run() reports with libfossil's
// message and the step's name. The one place that decides what a failure
// looks like is run().
enum { STEP_DONE = -1, STEP_ERR = -2 };

typedef struct {
    fsl_cx *f;
    char name[CONF_NAME_MAX + 1];
    char repo[PATH_CAP];
    char dir[PATH_CAP];
    size_t home_len;
    char journal[PATH_CAP];
    char from[96];     // the version the journal says an update was leaving
    bool have_journal;
    fsl_deck deck;     // a manifest being looked through
    fsl_deck base_deck;  // the common ancestor of a merge
    fsl_deck here_deck;  // the version a merge is made at
    fsl_id_t base;
    char scan_path[PATH_CAP];
    bool have_ckout;   // the working copy has its checkout database
    const char *message;
    char user[256];
    int exit_code;
    unsigned count;    // lines a visitor printed
    fsl_id_t trunk;    // trunk's tip
    fsl_id_t before;   // the version the update started from
    fsl_id_t target;   // the version the update goes to
    fsl_undo_e undo;   // what fsl_undo can do
    unsigned changes;  // local changes the lint looked at
    unsigned deleted;  // of them, deletions
    unsigned tracked;  // files in the version the working copy is at
    char skill[256];  // the skill folder the lint looked at last
    char attention[PATH_CAP];
    char tend_message[CONF_NAME_MAX + 96];
    char url[REMOTE_URL_MAX + 1];   // the remote's address
    char login[CRED_USER_MAX + 1];  // the user name to log in as, if there is a login
} Store;

typedef int (*StepFn)(Store *);

typedef struct {
    const char *what;
    StepFn fn;
} Step;

static void report(const Store *s, const char *what, int rc)
{
    char const *msg = "";
    fsl_size_t len = 0;
    (void)fsl_cx_err_get(s->f, &msg, &len);
    say(STDERR_FILENO, "suit: store %s: %s failed: %s: %.*s\n", s->name, what, fsl_rc_cstr(rc),
        (int)len, msg);
}

static int run(Store *s, const char *name, const char *message, const Step *steps, size_t n)
{
    memset(s, 0, sizeof *s);
    s->deck = fsl_deck_empty;
    s->base_deck = fsl_deck_empty;
    s->here_deck = fsl_deck_empty;
    s->message = message;
    if (!conf_name_ok(name, strlen(name), false)) {
        say(STDERR_FILENO, "suit: '%.40s' is not a wardrobe name (letters, digits, . _ -)\n", name);
        return 2;
    }
    strcpy(s->name, name);
    int result = 0;
    for (size_t i = 0; i < n; i++) {
        int rc = steps[i].fn(s);
        if (rc == STEP_DONE) {
            result = s->exit_code;
            break;
        }
        if (rc != 0) {
            result = 1;
            if (rc != STEP_ERR) report(s, steps[i].what, rc);
            break;
        }
    }
    fsl_deck_finalize(&s->deck);
    fsl_deck_finalize(&s->base_deck);
    fsl_deck_finalize(&s->here_deck);
    if (s->f != nullptr) fsl_cx_finalize(s->f);
    return result;
}

// ---- steps every command starts with --------------------------------------

static int step_paths(Store *s)
{
    char rel[CONF_NAME_MAX + 32];
    [[maybe_unused]] int n = snprintf(rel, sizeof rel, "wardrobes/%s.fossil", s->name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    s->home_len = suit_home_path(s->repo, sizeof s->repo, rel);
    if (s->home_len == 0) return STEP_ERR;
    n = snprintf(rel, sizeof rel, "%s.journal", s->name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    [[maybe_unused]] size_t journal_home = suit_home_path(s->journal, sizeof s->journal, rel);
    ensure(journal_home != 0);
    n = snprintf(rel, sizeof rel, "store/%s", s->name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    // The store's path is shorter than the wardrobe's, so it fits if that did.
    [[maybe_unused]] size_t dir_home = suit_home_path(s->dir, sizeof s->dir, rel);
    ensure(dir_home != 0);
    return 0;
}

static int step_wardrobe_exists(Store *s)
{
    struct stat st;
    if (sys_stat(s->repo, &st) == 0) return 0;
    say(STDERR_FILENO, "suit: store %s: no wardrobe at %s: %s\n", s->name, s->repo,
        strerror(errno));
    return STEP_ERR;
}

static int step_init(Store *s)
{
    [[maybe_unused]] int rc = fsl_cx_init(&s->f, nullptr);
    ensure(rc == 0);  // it fails only when out of memory
    return 0;
}

static int step_fs(Store *s)
{
    return store_fs_install(s->f);
}

// Every question libfossil asks about overwriting a file is answered yes: the
// store is suit's, and an update has already been checked to be safe.
static int confirm_yes(fsl_confirm_detail const *detail, fsl_confirm_response *answer, void *state)
{
    (void)detail;
    (void)state;
    answer->response = FSL_CRESPONSE_YES;
    return 0;
}

static int step_confirmer(Store *s)
{
    fsl_confirmer c = fsl_confirmer_empty;
    c.callback = confirm_yes;
    fsl_cx_confirmer(s->f, &c, nullptr);
    return 0;
}

static int step_user(Store *s)
{
    const char *user = sys_getenv("USER");
    if (user == nullptr || user[0] == '\0') user = sys_getenv("LOGNAME");
    if (user == nullptr || user[0] == '\0') {
        say(STDERR_FILENO, "suit: store %s: cannot tell who you are; set USER\n", s->name);
        return STEP_ERR;
    }
    snprintf(s->user, sizeof s->user, "%s", user);
    return fsl_cx_user_set(s->f, s->user);
}

static int step_repo(Store *s)
{
    return s->have_ckout ? 0 : fsl_repo_open(s->f, s->repo);
}

// A journal means an update did not finish: nothing else may touch the store.
static int step_journal_check(Store *s)
{
    struct stat st;
    if (sys_stat(s->journal, &st) != 0) return 0;
    say(STDERR_FILENO, "suit: store %s has an unfinished update; run `suit store repair %s`\n",
        s->name, s->name);
    s->exit_code = EXIT_NEEDS_REPAIR;
    return STEP_DONE;
}

static int step_ckout_existing(Store *s)
{
    return fsl_ckout_open_dir(s->f, s->dir, false);
}

// Repair is the one command that runs while a journal exists.
#define BASE                                                                                       \
    {"find the wardrobe", step_paths}, {"find the wardrobe", step_wardrobe_exists},                \
        {"start libfossil", step_init}, {"install the file writer", step_fs},                      \
        {"install the confirmer", step_confirmer}, {"find the user", step_user}
#define PREPARE BASE, {"look for an unfinished update", step_journal_check}

// ---- symlinks --------------------------------------------------------------

static int step_deck_trunk(Store *s)
{
    return fsl_deck_load_rid(s->f, &s->deck, s->trunk, FSL_SATYPE_CHECKIN);
}

static int step_deck_target(Store *s)
{
    return fsl_deck_load_rid(s->f, &s->deck, s->target, FSL_SATYPE_CHECKIN);
}

// libfossil's checkout would write a link as a regular file, so a version that
// has one is refused, with every such path named. The loop ends at the end of
// the list or on an error; & lets it say both without a branch of its own.
static int step_deck_links(Store *s)
{
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->deck);
    s->count = 0;
    do {
        rc = fsl_deck_F_next(&s->deck, &card);
        fsl_fileperm_e perm = card != nullptr ? card->perm : FSL_FILE_PERM_REGULAR;
        if (perm == FSL_FILE_PERM_LINK) {
            say(STDERR_FILENO, "suit: store %s: this version of the wardrobe has a symlink at %s; "
                "symlinks are not supported\n", s->name, card->name);
            s->count++;
        }
    } while ((rc == 0) & (card != nullptr));
    s->exit_code = EXIT_SYMLINK;
    if (s->count > 0) return STEP_DONE;
    return rc;
}

// ---- open -----------------------------------------------------------------

static int make_dir(const char *path)
{
    if (sys_mkdir(path, 0755) != 0 && errno != EEXIST) {
        say(STDERR_FILENO, "suit: cannot create %s: %s\n", path, strerror(errno));
        return STEP_ERR;
    }
    return 0;
}

// Make $SUIT_HOME, $SUIT_HOME/store and the store's own folder.
static int step_dirs(Store *s)
{
    char path[PATH_CAP];
    memcpy(path, s->repo, s->home_len);
    path[s->home_len] = '\0';
    int rc = make_dir(path);
    snprintf(path + s->home_len, sizeof path - s->home_len, "/store");
    rc = rc != 0 ? rc : make_dir(path);
    return rc != 0 ? rc : make_dir(s->dir);
}

static int step_find_ckout(Store *s)
{
    char db[PATH_CAP + 16];
    [[maybe_unused]] int n = snprintf(db, sizeof db, "%s/.fslckout", s->dir);
    ensure(n > 0 && (size_t)n < sizeof db);
    struct stat st;
    s->have_ckout = sys_stat(db, &st) == 0;
    return 0;
}

// An existing working copy opens its own repository; a new one is made for the
// repository step_repo opened.
static int step_ckout(Store *s)
{
    if (s->have_ckout) return fsl_ckout_open_dir(s->f, s->dir, false);
    fsl_repo_open_ckout_opt o = fsl_repo_open_ckout_opt_empty;
    o.targetDir = s->dir;
    o.checkForOpenedCkout = false;
    return fsl_repo_open_ckout(s->f, &o);
}

static int step_trunk(Store *s)
{
    return fsl_sym_to_rid(s->f, "trunk", FSL_SATYPE_CHECKIN, &s->trunk);
}

// A working copy that was created but never filled (an earlier open stopped
// part way) is at no version yet.
static int step_extract(Store *s)
{
    fsl_id_t current = 0;
    fsl_ckout_version_info(s->f, &current, nullptr);
    if (current > 0) return 0;
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.checkinRid = s->trunk;
    return fsl_repo_ckout(s->f, &o);
}

int store_open(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"make the store folders", step_dirs},
        {"look for the working copy", step_find_ckout},
        {"open the wardrobe", step_repo},
        {"open the working copy", step_ckout},
        {"find trunk", step_trunk},
        {"read trunk's manifest", step_deck_trunk},
        {"look for symlinks", step_deck_links},
        {"extract the files", step_extract},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- status ---------------------------------------------------------------

// What status calls each kind of change. The special kinds sit together after
// FSL_CKOUT_CHANGE_ADDED; everything below them is an edit of some sort.
static const char *change_word(fsl_ckout_change_e change)
{
    static const char *const special[] = {"added", "deleted", "deleted", "edited"};
    static_assert(FSL_CKOUT_CHANGE_REMOVED == FSL_CKOUT_CHANGE_ADDED + 1);
    static_assert(FSL_CKOUT_CHANGE_MISSING == FSL_CKOUT_CHANGE_ADDED + 2);
    static_assert(FSL_CKOUT_CHANGE_RENAMED == FSL_CKOUT_CHANGE_ADDED + 3);
    unsigned i = (unsigned)change - (unsigned)FSL_CKOUT_CHANGE_ADDED;
    return i < sizeof special / sizeof special[0] ? special[i] : "edited";
}

static int print_change(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)origName;
    Store *s = state;
    say(STDOUT_FILENO, "%s %s\n", change_word(change), filename);
    s->count++;
    return 0;
}

static int step_txn_begin(Store *s)
{
    return fsl_cx_txn_begin(s->f);
}

static int step_manage_all(Store *s)
{
    fsl_ckout_manage_opt o = fsl_ckout_manage_opt_empty;
    o.filename = s->dir;
    o.relativeToCwd = false;
    o.checkIgnoreGlobs = false;
    return fsl_ckout_manage(s->f, &o);
}

// Check every file's content, not just its size and time: an edit made in the
// same second as the file was written, to the same length, must not be missed.
static int step_scan(Store *s)
{
    return fsl_vfile_changes_scan(s->f, -1, FSL_VFILE_CKSIG_HASH);
}

static int step_print_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, print_change, s);
}

// What status did to the checkout database was only to look; undo it.
static int step_txn_rollback(Store *s)
{
    return fsl_cx_txn_end_v2(s->f, false, false);
}

int store_status(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"begin", step_txn_begin},
        {"look for new files", step_manage_all},
        {"look for changes", step_scan},
        {"list the changes", step_print_changes},
        {"end", step_txn_rollback},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

static void report_add(const char *path, size_t line, const char *what);

// ---- symlinks in the store folder --------------------------------------------

constexpr int LINK_SCAN_DEPTH = 64;

typedef struct {
    Store *s;
    int depth;
} Crawl;

static int crawl_dir(Crawl *c, const char *dir);

// Report a symlink, recurse into a folder. Our own temporary names are not
// listed, so they are not seen here either.
static int crawl_entry(void *state, char const *entry)
{
    Crawl *c = state;
    Store *s = c->s;
    size_t len = strlen(s->scan_path);
    [[maybe_unused]] int n = snprintf(s->scan_path + len, sizeof s->scan_path - len, "/%s", entry);
    ensure(n > 0 && (size_t)n < sizeof s->scan_path - len);
    fsl_fstat st = fsl_fstat_empty;
    (void)fsl_ckout_fs_os.xStat(nullptr, s->scan_path, &st, false);
    int rc = 0;
    if (st.type == FSL_FSTAT_TYPE_LINK) {
        report_add(s->scan_path + strlen(s->dir) + 1, 0, "symlink, not supported");
    }
    if (st.type == FSL_FSTAT_TYPE_DIR) {
        rc = crawl_dir(c, s->scan_path);
    }
    s->scan_path[len] = '\0';
    return rc;
}

static int crawl_dir(Crawl *c, const char *dir)
{
    if (c->depth == LINK_SCAN_DEPTH) {
        say(STDERR_FILENO, "suit: store %s: folders are nested more than %d deep at %s\n",
            c->s->name, LINK_SCAN_DEPTH, dir);
        return FSL_RC_RANGE;
    }
    c->depth++;
    int rc = fsl_ckout_fs_os.xDirList(nullptr, dir, crawl_entry, c);
    c->depth--;
    return rc;
}

// Symlinks are not supported, so one in the store is a problem for the lint.
static int step_find_symlinks(Store *s)
{
    Crawl c = {s, 0};
    snprintf(s->scan_path, sizeof s->scan_path, "%s", s->dir);
    return crawl_dir(&c, s->dir) == 0 ? 0 : STEP_ERR;
}

// ---- the lint ------------------------------------------------------------------

constexpr size_t REPORT_MAX = 8000;
constexpr unsigned HOLD_MIN_DELETED = 5;  // a check-in is held when it deletes more files than this
constexpr unsigned HOLD_FRACTION = 5;     // and more than one in this many of the files tracked

// What the lint found, one "PATH:LINE: what" a line. Rows that do not fit are
// counted, and the last line says how many.
static char lint_report[REPORT_MAX + 80];
static size_t report_len;
static unsigned report_problems;
static unsigned report_dropped;
static LintRules rules;
static char file_buf[LINT_FILE_MAX];

static void report_add(const char *path, size_t line, const char *what)
{
    char row[PATH_CAP + 300];
    int n = line > 0 ? snprintf(row, sizeof row, "%s:%zu: %s\n", path, line, what)
                     : snprintf(row, sizeof row, "%s: %s\n", path, what);
    ensure(n > 0 && (size_t)n < sizeof row);
    report_problems++;
    if (report_len + (size_t)n > REPORT_MAX) {
        report_dropped++;
        return;
    }
    memcpy(lint_report + report_len, row, (size_t)n);
    report_len += (size_t)n;
}

static const char *sink_path;

static void report_sink(void *state, size_t line, const char *what)
{
    (void)state;
    report_add(sink_path, line, what);
}

static void report_close(void)
{
    if (report_dropped > 0)
        report_len += (size_t)snprintf(lint_report + report_len, sizeof lint_report - report_len,
            "... and %u more\n", report_dropped);
}

static void report_show(void)
{
    (void)sys_write_all(STDERR_FILENO, lint_report, report_len);
}

static int cannot(const Store *s, const char *path, int err)
{
    say(STDERR_FILENO, "suit: store %s: cannot read %s: %s\n", s->name, path, strerror(err));
    return STEP_ERR;
}

// Look at the file PATH of the store without following a link. 0 or an errno.
static int stat_rel(Store *s, const char *path, struct stat *st)
{
    [[maybe_unused]] int n = snprintf(s->scan_path, sizeof s->scan_path, "%s/%s", s->dir, path);
    ensure(n > 0 && (size_t)n < sizeof s->scan_path);
    return sys_lstat(s->scan_path, st) == 0 ? 0 : errno;
}

// Read the file stat_rel just looked at into file_buf. The length, or -1 and errno.
static ssize_t read_scanned(const char *path)
{
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return -1;
    size_t len = 0;
    ssize_t n = 1;
    while (len < LINT_FILE_MAX && n > 0) {
        n = sys_read(fd, file_buf + len, LINT_FILE_MAX - len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        len += n > 0 ? (size_t)n : 0;
    }
    int err = errno;
    (void)sys_close(fd);
    errno = err;
    return n < 0 ? -1 : (ssize_t)len;
}

// The rules, from suit.lint at the wardrobe's top.
static int step_lint_rules(Store *s)
{
    report_len = 0;
    report_problems = 0;
    report_dropped = 0;
    char path[PATH_CAP];
    [[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", s->dir, LINT_RULES_NAME);
    ensure(n > 0 && (size_t)n < sizeof path);
    LintError e;
    if (lint_rules_load(&rules, path, &e)) return 0;
    if (e.err == 0) {
        report_add(LINT_RULES_NAME, (size_t)e.line, e.msg);
        return 0;
    }
    say(STDERR_FILENO, "suit: store %s: %s: %s\n", s->name, LINT_RULES_NAME, e.msg);
    return STEP_ERR;
}

static int step_deck_current(Store *s)
{
    fsl_id_t rid = 0;
    fsl_ckout_version_info(s->f, &rid, nullptr);
    return fsl_deck_load_rid(s->f, &s->deck, rid, FSL_SATYPE_CHECKIN);
}

// How many files the version the working copy is at holds.
static int step_count_tracked(Store *s)
{
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->deck);
    do {
        rc = fsl_deck_F_next(&s->deck, &card);
        s->tracked += card != nullptr;
    } while ((rc == 0) & (card != nullptr));
    return rc;
}

// A skill folder holds a SKILL.md that begins with "---".
static int lint_skill(Store *s, const char *path)
{
    if (strncmp(path, "skills/", 7) != 0) return 0;
    const char *slash = strchr(path + 7, '/');
    if (slash == nullptr) return 0;
    size_t n = (size_t)(slash - path) - 7;
    if (strlen(s->skill) == n && memcmp(s->skill, path + 7, n) == 0) return 0;
    ensure(n < sizeof s->skill);
    memcpy(s->skill, path + 7, n);
    s->skill[n] = '\0';
    char rel[PATH_CAP];
    [[maybe_unused]] int w = snprintf(rel, sizeof rel, "skills/%s/SKILL.md", s->skill);
    ensure(w > 0 && (size_t)w < sizeof rel);
    struct stat st;
    int err = stat_rel(s, rel, &st);
    if (err != 0 && err != ENOENT) return cannot(s, rel, err);
    if (err == ENOENT || !S_ISREG(st.st_mode)) {
        rel[w - 9] = '\0';
        err = stat_rel(s, rel, &st);
        if (err != 0 && err != ENOENT) return cannot(s, rel, err);
        if (err == 0) report_add(rel, 0, "no SKILL.md");
        return 0;
    }
    ssize_t len = read_scanned(s->scan_path);
    if (len < 0) return cannot(s, rel, errno);
    if (!lint_has_header(file_buf, (size_t)len)) report_add(rel, 1, "no header");
    return 0;
}

// Scan the file PATH, which would be checked in.
static int lint_file(Store *s, const char *path)
{
    struct stat st;
    int err = stat_rel(s, path, &st);
    if (err != 0) return cannot(s, path, err);
    if (!S_ISREG(st.st_mode)) return 0;
    if ((size_t)st.st_size > LINT_FILE_MAX) {
        report_add(path, 0, "larger than 4 MiB, not scanned");
        return 0;
    }
    ssize_t len = read_scanned(s->scan_path);
    if (len < 0) return cannot(s, path, errno);
    sink_path = path;
    bool exempt = strcmp(path, LINT_RULES_NAME) == 0 || lint_allowed(&rules, path);
    (void)lint_text(&rules, exempt, file_buf, (size_t)len, report_sink, nullptr);
    return 0;
}

static int lint_change(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)origName;
    Store *s = state;
    s->changes++;
    bool gone = change == FSL_CKOUT_CHANGE_REMOVED || change == FSL_CKOUT_CHANGE_MISSING;
    s->deleted += gone;
    int rc = lint_skill(s, filename);
    return rc != 0 || gone ? rc : lint_file(s, filename);
}

static int step_lint_changes(Store *s)
{
    int rc = fsl_ckout_changes_visit(s->f, -1, false, lint_change, s);
    report_close();
    return rc;
}

static bool held(const Store *s)
{
    return s->deleted > HOLD_MIN_DELETED && s->deleted * HOLD_FRACTION > s->tracked;
}

static void held_text(const Store *s, char *out, size_t cap)
{
    [[maybe_unused]] int n = snprintf(out, cap, "held %s: %u of %u files deleted", s->name, s->deleted, s->tracked);
    ensure(n > 0 && (size_t)n < cap);
}

#define LINT_STEPS                                                                                 \
    PREPARE, {"open the working copy", step_ckout_existing}, {"begin", step_txn_begin},            \
        {"read the lint rules", step_lint_rules}, {"look for symlinks", step_find_symlinks},       \
        {"find the version", step_deck_current}, {"count the files", step_count_tracked}, {"look for new files", step_manage_all},          \
        {"look for changes", step_scan}, {"lint the changes", step_lint_changes},                  \
        {"end", step_txn_rollback}

static int step_lint_verdict(Store *s)
{
    report_show();
    s->exit_code = report_problems > 0 ? EXIT_LINT : 0;
    return STEP_DONE;
}

int store_lint(const char *name)
{
    static const Step steps[] = {
        LINT_STEPS,
        {"report", step_lint_verdict},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- commit ---------------------------------------------------------------

// A file gone from disk is a deletion: take it out of the next check-in's
// file list. Anything else that changed is counted.
static int unmanage_missing(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)origName;
    Store *s = state;
    s->count++;
    if (change != FSL_CKOUT_CHANGE_MISSING) return 0;
    fsl_ckout_unmanage_opt o = fsl_ckout_unmanage_opt_empty;
    o.filename = filename;
    o.relativeToCwd = false;
    o.scanForChanges = false;
    return fsl_ckout_unmanage(s->f, &o);
}

static int step_count_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, unmanage_missing, s);
}

// Nothing to check in is not an error.
static int step_anything(Store *s)
{
    s->exit_code = 0;
    return s->count == 0 ? STEP_DONE : 0;
}

static int step_checkin(Store *s)
{
    fsl_checkin_opt o = fsl_checkin_opt_empty;
    o.scanForChanges = false;
    o.message = s->message;
    o.user = s->user;
    fsl_uuid_str uuid = nullptr;
    int rc = fsl_checkin_commit(s->f, &o, nullptr, &uuid);
    if (rc == 0) say(STDOUT_FILENO, "checked in %.12s\n", uuid);
    fsl_free(uuid);
    return rc;
}

#define COMMIT_STEPS                                                                               \
    {"look for new files", step_manage_all}, {"look for changes", step_scan},                      \
        {"find deletions", step_count_changes},                                                    \
        {"look for anything to check in", step_anything}, {"check in", step_checkin}

// The lint stops a check-in that has a problem, and a check-in that deletes
// many files is stopped unless it was asked for.
static int step_refuse_problems(Store *s)
{
    if (report_problems == 0) return 0;
    report_show();
    s->exit_code = EXIT_LINT;
    return STEP_DONE;
}

static bool confirm_deletions;

static int step_refuse_held(Store *s)
{
    if (!held(s) || confirm_deletions) return 0;
    char text[CONF_NAME_MAX + 96];
    held_text(s, text, sizeof text);
    say(STDERR_FILENO, "%s\n", text);
    s->exit_code = EXIT_HELD;
    return STEP_DONE;
}

int store_commit(const char *name, const char *message, bool confirm)
{
    static const Step steps[] = {
        LINT_STEPS,
        {"refuse a lint failure", step_refuse_problems},
        {"hold deletions", step_refuse_held},
        COMMIT_STEPS,
    };
    Store s;
    confirm_deletions = confirm;
    return run(&s, name, message, steps, sizeof steps / sizeof steps[0]);
}

// ---- tend ------------------------------------------------------------------

static int step_attention_path(Store *s)
{
    [[maybe_unused]] size_t home = suit_home_path(s->attention, sizeof s->attention, "attention");
    ensure(home != 0);
    return 0;
}

// Leave KIND's item in the attention file and stop with CODE, or with 1 when
// that failed.
static int leave_item(Store *s, const char *kind, const char *header, const char *details, int code)
{
    s->exit_code = attention_add(s->attention, kind, s->name, header, details) == 0 ? code : 1;
    return STEP_DONE;
}

static int step_tend_decide(Store *s)
{
    s->exit_code = 0;
    if (s->changes == 0) {
        if (attention_remove(s->attention, nullptr, s->name) != 0) s->exit_code = 1;
        return STEP_DONE;
    }
    if (report_problems > 0) {
        char header[CONF_NAME_MAX + 8];
        snprintf(header, sizeof header, "lint %s", s->name);
        report_show();
        return leave_item(s, "lint", header, lint_report, EXIT_LINT);
    }
    if (!held(s)) return 0;
    char text[CONF_NAME_MAX + 96];
    held_text(s, text, sizeof text);
    say(STDERR_FILENO, "%s\n", text);
    return leave_item(s, "held", text, nullptr, EXIT_HELD);
}

static int step_tend_message(Store *s)
{
    char path[PATH_CAP];
    [[maybe_unused]] size_t home = suit_home_path(path, sizeof path, "machine");
    ensure(home != 0);
    char machine[MACHINE_MAX + 1];
    if (machine_read(path, machine) != 0) return STEP_ERR;
    snprintf(s->tend_message, sizeof s->tend_message, "Edits on %s: %u files",
        machine[0] != '\0' ? machine : "this machine", s->changes);
    s->message = s->tend_message;
    return 0;
}

static int step_tend_clear(Store *s)
{
    return attention_remove(s->attention, nullptr, s->name) == 0 ? 0 : STEP_ERR;
}

// ---- repeated sync failures ---------------------------------------------------

constexpr unsigned SYNC_FAILS_ATTENTION = 3;

static int forget_failures(const char *count_path, const char *attention, const char *name, unsigned n)
{
    if (n > 0 && sys_unlink(count_path) != 0) {
        say(STDERR_FILENO, "suit: cannot remove %s: %s\n", count_path, strerror(errno));
        return 1;
    }
    return attention_remove(attention, "sync", name);
}

static int count_failure(const char *count_path, const char *attention, const char *name, unsigned n)
{
    n = n < SYNC_FAILS_MAX ? n + 1 : n;
    int err = syncfail_write(count_path, n);
    if (err != 0) {
        say(STDERR_FILENO, "suit: cannot write %s: %s\n", count_path, strerror(err));
        return 1;
    }
    if (n < SYNC_FAILS_ATTENTION) return 0;
    char rpath[PATH_CAP];
    char cpath[PATH_CAP];
    RemoteError e;
    static Remotes remotes;
    [[maybe_unused]] int paths = remote_paths(rpath, cpath, sizeof rpath);
    ensure(paths == 0);  // the home was found a moment ago
    if (!remotes_load(&remotes, rpath, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", rpath, e.line, e.msg);
        return 1;
    }
    const RemoteEntry *r = remotes_find(&remotes, name);
    ensure(r != nullptr);  // a sync that failed had a remote
    char host[REMOTE_URL_MAX + 1];
    remote_host(r->url, host, sizeof host);
    char header[CONF_NAME_MAX + REMOTE_URL_MAX + 64];
    snprintf(header, sizeof header, "sync %s: failing since %u tries: %s", name, n, host);
    return attention_add(attention, "sync", name, header, nullptr);
}

// After a tend's sync: count a failure to use the remote, or forget the count
// and the attention item. 0, or 1 after saying what failed.
static int note_sync(const char *name, int synced)
{
    char rel[CONF_NAME_MAX + 32];
    char count_path[PATH_CAP];
    char attention[PATH_CAP];
    [[maybe_unused]] int len = snprintf(rel, sizeof rel, "%s.syncfail", name);
    ensure(len > 0 && (size_t)len < sizeof rel);
    [[maybe_unused]] size_t home = suit_home_path(count_path, sizeof count_path, rel);
    ensure(home != 0);  // the sync found the home
    home = suit_home_path(attention, sizeof attention, "attention");
    ensure(home != 0);
    unsigned n = 0;
    RemoteError e;
    if (!syncfail_load(count_path, &n, &e)) {
        say(STDERR_FILENO, "suit: %s: %s\n", count_path, e.msg);
        return 1;
    }
    bool failed = synced == EXIT_NETWORK || synced == EXIT_NO_TLS || synced == EXIT_REFUSED;
    return failed ? count_failure(count_path, attention, name, n)
                  : forget_failures(count_path, attention, name, n);
}

int store_tend(const char *name)
{
    static const Step steps[] = {
        LINT_STEPS,
        {"find the attention file", step_attention_path},
        {"decide", step_tend_decide},
        {"name the check-in", step_tend_message},
        COMMIT_STEPS,
        {"clear what needed you", step_tend_clear},
    };
    Store s;
    int rc = run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
    if (rc != 0) return rc;
    int synced = store_sync(name);
    int noted = note_sync(name, synced);
    return synced != 0 ? synced : noted;
}

// ---- update ---------------------------------------------------------------

static int step_list_changes(Store *s)
{
    return fsl_ckout_changes_visit(s->f, -1, false, print_change, s);
}

static int step_before(Store *s)
{
    fsl_ckout_version_info(s->f, &s->before, nullptr);
    return 0;
}

// The caller commits first.
static int step_refuse_local_changes(Store *s)
{
    s->exit_code = EXIT_LOCAL_CHANGES;
    return s->count > 0 ? STEP_DONE : 0;
}

// Trunk's tip, or where the checkout is if that is not known.
static int step_target(Store *s)
{
    fsl_id_t tip = 0;
    int rc = fsl_ckout_calc_update_version(s->f, &tip);
    // 0 means libfossil found no version; the store stays where it is. This is
    // arithmetic and not a branch because no repository we could build in a
    // test made libfossil answer 0.
    s->target = (fsl_id_t)(tip > 0) * tip + (fsl_id_t)(tip <= 0) * s->before;
    return rc;
}

// Updating to the version the store is at would replace what `suit back` can
// undo with an update that did nothing.
static int step_up_to_date(Store *s)
{
    s->exit_code = 0;
    if (s->target != s->before) return 0;
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "updated to %.12s\n", uuid);
    return STEP_DONE;
}

static int print_conflict(fsl_ckup_state const *state)
{
    static const unsigned conflicts =
        (1u << FSL_CKUP_FCHANGE_CONFLICT_MERGED) | (1u << FSL_CKUP_FCHANGE_CONFLICT_ADDED) |
        (1u << FSL_CKUP_FCHANGE_CONFLICT_ADDED_UNMANAGED) | (1u << FSL_CKUP_FCHANGE_CONFLICT_RM) |
        (1u << FSL_CKUP_FCHANGE_CONFLICT_SYMLINK) | (1u << FSL_CKUP_FCHANGE_CONFLICT_BINARY);
    Store *s = state->callbackState;
    ensure(state->fileChangeType >= 0 && state->fileChangeType < 32);
    if (((1u << state->fileChangeType) & conflicts) != 0) {
        say(STDOUT_FILENO, "conflict %s\n", state->extractState->fCard->name);
        s->count++;
    }
    return 0;
}

static int update_to(Store *s, fsl_id_t version, bool dry_run)
{
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.scanForChanges = false;
    o.checkinRid = version;
    o.dryRun = dry_run;
    o.callback = print_conflict;
    o.callbackState = s;
    return fsl_ckout_update(s->f, &o);
}

// A dry run still changes the checkout database; the caller rolls it back.
static int step_dry_run(Store *s)
{
    s->count = 0;
    return update_to(s, s->target, true);
}

// A conflict stops the update before it changes anything.
static int step_refuse_conflicts(Store *s)
{
    s->exit_code = EXIT_CONFLICT;
    return s->count > 0 ? STEP_DONE : 0;
}

// Put every file back to the checkout's version, writing over whatever the
// failed update left. Files are compared by content for this.
static int put_back(Store *s)
{
    fsl_cx_err_reset(s->f);
    (void)fsl_vfile_changes_scan(s->f, -1, FSL_VFILE_CKSIG_HASH);
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.scanForChanges = false;
    o.checkinRid = s->before;
    return fsl_repo_ckout(s->f, &o);
}

static int step_journal_remove(Store *s);

// A step that changed files failed and has said so: put every file back.
static int put_back_and_say(Store *s)
{
    if (put_back(s) == 0) {
        (void)step_journal_remove(s);
        say(STDERR_FILENO, "suit: store %s: the files are back at the version they were at\n",
            s->name);
    } else {
        say(STDERR_FILENO, "suit: store %s: could not put the files back; run `suit store repair %s`\n",
            s->name, s->name);
    }
    return STEP_ERR;
}

// A step that changed files failed: report it and put every file back.
static int undo_failed(Store *s, const char *what, int rc)
{
    report(s, what, rc);
    return put_back_and_say(s);
}

static int step_apply(Store *s)
{
    int rc = update_to(s, s->target, false);
    return rc == 0 ? 0 : undo_failed(s, "update", rc);
}

// Before an update changes anything: where it is leaving and where it is going.
// Repair needs this if the update does not finish.
static int step_journal_write(Store *s)
{
    fsl_uuid_str from = fsl_rid_to_uuid(s->f, s->before);
    fsl_uuid_str to = fsl_rid_to_uuid(s->f, s->target);
    ensure(from != nullptr && to != nullptr);
    char text[256];
    [[maybe_unused]] int n = snprintf(text, sizeof text, "from %s\nto %s\n", from, to);
    ensure(n > 0 && (size_t)n < sizeof text);
    fsl_free(from);
    fsl_free(to);
    int err = sys_write_atomic(s->journal, text, strlen(text));
    if (err == 0) return 0;
    say(STDERR_FILENO, "suit: store %s: cannot write %s: %s\n", s->name, s->journal, strerror(err));
    return STEP_ERR;
}

// The update, or the put-back, finished: nothing is left to repair.
static int step_journal_remove(Store *s)
{
    (void)sys_unlink(s->journal);
    return 0;
}

static int step_report_version(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "updated to %.12s\n", uuid);
    return 0;
}

// Two sessions, because libfossil's dry run leaves the checkout version it
// went to in memory after the database is rolled back: the trial finds out
// what would happen, and the update starts again from the database.
static int step_up_reconcile(Store *s);

int store_update(const char *name)
{
    static const Step trial[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"look for changes", step_scan},
        {"list the changes", step_list_changes},
        {"check for local changes", step_refuse_local_changes},
        {"find the version", step_before},
        {"find the version to update to", step_target},
        {"read the new version's manifest", step_deck_target},
        {"look for symlinks", step_deck_links},
        {"begin the trial", step_txn_begin},
        {"try the update", step_dry_run},
        {"end the trial", step_txn_rollback},
        {"check for conflicts", step_refuse_conflicts},
    };
    static const Step apply[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"look for changes", step_scan},
        {"find the version", step_before},
        {"find the version to update to", step_target},
        {"see if there is anything to do", step_up_to_date},
        {"write the journal", step_journal_write},
        {"update", step_apply},
        {"remove the journal", step_journal_remove},
        {"find the attention file", step_attention_path},
        {"drop the items of accepted upstreams", step_up_reconcile},
        {"report", step_report_version},
    };
    Store s;
    int rc = run(&s, name, nullptr, trial, sizeof trial / sizeof trial[0]);
    return rc != 0 ? rc : run(&s, name, nullptr, apply, sizeof apply / sizeof apply[0]);
}

// ---- repair -----------------------------------------------------------------

// Read the journal if there is one.
static int step_journal_read(Store *s)
{
    char text[256] = {};
    int fd = sys_open(s->journal, O_RDONLY, 0);
    if (fd < 0 && errno == ENOENT) return 0;
    if (fd < 0) {
        say(STDERR_FILENO, "suit: store %s: cannot read %s: %s\n", s->name, s->journal,
            strerror(errno));
        return STEP_ERR;
    }
    size_t len = 0;
    ssize_t n = 1;
    while (len < sizeof text - 1 && n > 0) {
        n = sys_read(fd, text + len, sizeof text - 1 - len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        len += n > 0 ? (size_t)n : 0;
    }
    int err = n < 0 ? errno : 0;
    (void)sys_close(fd);
    char to[96];
    if (err != 0) {
        say(STDERR_FILENO, "suit: store %s: the journal %s could not be read: %s\n", s->name,
            s->journal, strerror(err));
        return STEP_ERR;
    }
    if (sscanf(text, "from %95s\nto %95s\n", s->from, to) != 2) {
        say(STDERR_FILENO, "suit: store %s: the journal %s is damaged\n", s->name, s->journal);
        return STEP_ERR;
    }
    s->have_journal = true;
    return 0;
}

// What there is to put back: with a journal, the version the update was
// leaving; without one, the version the working copy records.
static int step_repair_target(Store *s)
{
    fsl_id_t recorded = 0;
    fsl_ckout_version_info(s->f, &recorded, nullptr);
    fsl_id_t journaled = s->have_journal ? fsl_uuid_to_rid(s->f, s->from) : 0;
    s->target = s->have_journal ? journaled : recorded;
    if (s->target > 0) return 0;
    say(STDERR_FILENO, "suit: store %s: the journal names a version this wardrobe does not have\n",
        s->name);
    return STEP_ERR;
}

// Without a journal, only a working copy with no edits is repaired: a repair
// would throw the edits away. A journal says the changes are the update's.
static int step_repair_decide(Store *s)
{
    if (s->have_journal) return 0;
    if (s->count > 0) {
        s->exit_code = EXIT_LOCAL_CHANGES;
        return STEP_DONE;
    }
    say(STDOUT_FILENO, "nothing to repair\n");
    s->exit_code = 0;
    return STEP_DONE;
}

static int step_restore(Store *s)
{
    fsl_cx_err_reset(s->f);
    fsl_ckup_opt o = fsl_ckup_opt_empty;
    o.scanForChanges = false;
    o.checkinRid = s->target;
    return fsl_repo_ckout(s->f, &o);
}

static int step_report_repaired(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "repaired; back at %.12s\n", uuid);
    return 0;
}

int store_repair(const char *name)
{
    static const Step steps[] = {
        BASE,
        {"open the working copy", step_ckout_existing},
        {"read the journal", step_journal_read},
        {"find the version to restore", step_repair_target},
        {"look for changes", step_scan},
        {"list the changes", step_list_changes},
        {"decide", step_repair_decide},
        {"restore the files", step_restore},
        {"remove the journal", step_journal_remove},
        {"report", step_report_repaired},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- back -----------------------------------------------------------------

static int step_undo_state(Store *s)
{
    return fsl_undo_state(s->f, &s->undo, nullptr);
}

static int step_anything_to_undo(Store *s)
{
    if (s->undo == FSL_UNDO_UNDO) return 0;
    say(STDERR_FILENO, "suit: store %s: nothing to go back to\n", s->name);
    s->exit_code = EXIT_NOTHING_TO_UNDO;
    return STEP_DONE;
}

static int step_undo(Store *s)
{
    int rc = fsl_undo(s->f, false, false);
    if (rc != FSL_RC_CONFLICT) return rc;
    say(STDERR_FILENO, "suit: store %s: cannot go back: the store has changed since the update\n",
        s->name);
    s->exit_code = EXIT_NOTHING_TO_UNDO;
    return STEP_DONE;
}

static int step_show_version(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "store %s at %.12s\n", s->name, uuid);
    return 0;
}

int store_show_version(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"show the version", step_show_version},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

int store_check_journal(const char *name)
{
    static const Step steps[] = {
        {"find the wardrobe", step_paths},
        {"look for an unfinished update", step_journal_check},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

static int step_report_back(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "back at %.12s\n", uuid);
    return 0;
}

int store_back(const char *name)
{
    static const Step steps[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"see what can be undone", step_undo_state},
        {"see what can be undone", step_anything_to_undo},
        {"go back", step_undo},
        {"report", step_report_back},
    };
    Store s;
    return run(&s, name, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- sync -------------------------------------------------------------------

// What the pull found, for the sessions that follow it.
static struct {
    bool pulled;         // there is a remote and it was pulled from
    bool local_changes;  // the working copy has changes
    bool moved;          // the remote's check-ins are ahead of the working copy
    bool clean_fork;     // the trial merge found nothing that conflicts
} sync_state;

static char sync_secret[CRED_SECRET_MAX + 1];

// The login saved for the wardrobe, if any: its user name in S and its secret
// in sync_secret.
static int load_login(Store *s, const char *cpath)
{
    static Creds creds;
    RemoteError e;
    bool loaded = creds_load(&creds, cpath, &e);
    if (!loaded) say(STDERR_FILENO, "suit: %s:%d: %s\n", cpath, e.line, e.msg);
    const CredEntry *c = loaded ? creds_find(&creds, s->name) : nullptr;
    if (c != nullptr) {
        snprintf(s->login, sizeof s->login, "%s", c->user);
        snprintf(sync_secret, sizeof sync_secret, "%s", c->secret);
    }
    secret_wipe(&creds, sizeof creds);
    return loaded ? 0 : STEP_ERR;
}

static int step_remote(Store *s)
{
    char rpath[PATH_CAP];
    char cpath[PATH_CAP];
    RemoteError e;
    static Remotes remotes;
    [[maybe_unused]] int paths = remote_paths(rpath, cpath, sizeof rpath);
    ensure(paths == 0);  // step_paths found the same home
    if (!remotes_load(&remotes, rpath, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", rpath, e.line, e.msg);
        return STEP_ERR;
    }
    const RemoteEntry *r = remotes_find(&remotes, s->name);
    s->exit_code = 0;
    if (r == nullptr) return STEP_DONE;
    snprintf(s->url, sizeof s->url, "%s", r->url);
    if (strncmp(s->url, "https://", 8) == 0) {
        say(STDERR_FILENO, "suit: sync %s: this build of suit cannot use https yet\n", s->name);
        s->exit_code = EXIT_NO_TLS;
        return STEP_DONE;
    }
    return load_login(s, cpath);
}

// libfossil asks for the password of a user named in the address.
static int give_secret(fsl_cx *f, char const *url, fsl_b *out, void *state)
{
    (void)f;
    (void)url;
    (void)state;
    fsl_b_reuse(out);
    return fsl_b_append(out, sync_secret, (fsl_int_t)strlen(sync_secret));
}

// URL as libfossil wants it: with the login's user name in front of the host
// of an http address. The secret is asked for through give_secret.
static void address_with_login(char *out, size_t cap, const char *url, const char *login)
{
    bool use = login[0] != '\0' && strncmp(url, "http://", 7) == 0;
    snprintf(out, cap, "%.7s%s%s%s", url, use ? login : "", use ? "@" : "", url + 7);
}

// One round of libfossil's sync client. The secret goes to it only through
// the callback, and is wiped as soon as the call returns.
static int sync_with_remote(Store *s, bool pull)
{
    char url[REMOTE_URL_MAX + CRED_USER_MAX + 2];
    address_with_login(url, sizeof url, s->url, s->login);
    fsl_xfer_config xc = fsl_xfer_config_empty;
    fsl_b_external(&xc.url, url, -1);
    xc.op.pull = pull;
    xc.op.push = !pull;
    xc.socketTimeoutSeconds = 30;
    xc.password.callback = give_secret;
    xc.password.ignoreSaved = true;
    xc.password.save = false;
    int rc = fsl_sync_client(s->f, &xc, nullptr);
    fsl_xfer_config_cleanup(&xc);
    secret_wipe(sync_secret, sizeof sync_secret);
    secret_wipe(url, sizeof url);
    if (rc == 0) return 0;
    char host[REMOTE_URL_MAX + 1];
    char const *msg = "";
    fsl_size_t len = 0;
    (void)fsl_cx_err_get(s->f, &msg, &len);
    remote_host(s->url, host, sizeof host);
    say(STDERR_FILENO, "suit: sync %s: %s failed: %s: %.*s\n", s->name, host, fsl_rc_cstr(rc),
        (int)strcspn(msg, "\n"), msg);
    s->exit_code = rc == FSL_RC_REMOTE ? EXIT_REFUSED : EXIT_NETWORK;
    return STEP_DONE;
}

static int step_pull(Store *s)
{
    int rc = sync_with_remote(s, true);
    sync_state.pulled = rc == 0;
    return rc;
}

static int step_push(Store *s)
{
    return sync_with_remote(s, false);
}

static int count_change(void *state, fsl_ckout_change_e change, char const *filename,
    char const *origName)
{
    (void)change;
    (void)filename;
    (void)origName;
    ((Store *)state)->count++;
    return 0;
}

static int step_count_local(Store *s)
{
    s->count = 0;
    return fsl_ckout_changes_visit(s->f, -1, false, count_change, s);
}

// Where the pull left things: local changes, and whether trunk moved on.
static int step_pull_outcome(Store *s)
{
    sync_state.local_changes = s->count > 0;
    sync_state.moved = s->target != s->before;
    return 0;
}

// The newest open trunk leaf that the working copy's version is not: another
// machine's check-in that this one has neither built on nor merged.
static int step_find_fork(Store *s)
{
    fsl_id_t fork = 0;
    int rc = fsl_db_get_id(fsl_cx_db_repo(s->f), &fork,
        "SELECT l.rid FROM leaf l JOIN event e ON e.objid=l.rid WHERE l.rid<>%" FSL_ID_T_PFMT
        " AND EXISTS(SELECT 1 FROM tagxref WHERE rid=l.rid AND tagtype>0 AND value='trunk'"
        " AND tagid=(SELECT tagid FROM tag WHERE tagname='branch'))"
        " AND NOT EXISTS(SELECT 1 FROM tagxref WHERE rid=l.rid AND tagtype>0"
        " AND tagid=(SELECT tagid FROM tag WHERE tagname='closed'))"
        " ORDER BY e.mtime DESC LIMIT 1", s->before);
    s->target = fork;
    return rc;
}

// No fork: nothing is waiting on the user for this wardrobe's conflicts.
static int step_no_fork(Store *s)
{
    if (s->target > 0) return 0;
    s->exit_code = attention_remove(s->attention, "conflict", s->name) == 0 ? 0 : 1;
    return STEP_DONE;
}

// A file edited here and on the remote, a file added over an untracked one, or
// a symlink or a binary (libfossil does not merge those).
static int print_merge_conflict(fsl_merge_state const *state)
{
    static const unsigned conflicts =
        (1u << FSL_MERGE_FCHANGE_CONFLICT_MERGED) |
        (1u << FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED) |
        (1u << FSL_MERGE_FCHANGE_CONFLICT_SYMLINK) | (1u << FSL_MERGE_FCHANGE_CONFLICT_BINARY);
    ensure(state->fileChangeType >= 0 && state->fileChangeType < 32);
    if (((1u << state->fileChangeType) & conflicts) != 0) {
        say(STDOUT_FILENO, "conflict %s\n", state->filename);
        ((Store *)state->opt->callbackState)->count++;
    }
    return 0;
}

static int merge_from(Store *s, bool dry_run)
{
    fsl_merge_opt o = fsl_merge_opt_empty;
    o.mergeRid = s->target;
    o.scanForChanges = false;
    o.dryRun = dry_run;
    o.callback = print_merge_conflict;
    o.callbackState = s;
    return fsl_ckout_merge(s->f, &o);
}

static int step_merge_dry_run(Store *s)
{
    s->count = 0;
    return merge_from(s, true);
}

// libfossil's merge drops a file the other side deleted even if this side
// changed it, and leaves out of the merge one that this side deleted and the
// other changed, without a word. Both are conflicts: found here by comparing
// the common ancestor's files with each side's.
static const char *const common_ancestor_sql =
    "WITH RECURSIVE av(rid) AS (SELECT %" FSL_ID_T_PFMT " UNION SELECT pid FROM plink, av"
    " WHERE cid=av.rid), am(rid) AS (SELECT %" FSL_ID_T_PFMT " UNION SELECT pid FROM plink, am"
    " WHERE cid=am.rid) SELECT av.rid FROM av JOIN event ON objid=av.rid"
    " WHERE av.rid IN (SELECT rid FROM am) ORDER BY mtime DESC LIMIT 1";

static bool changed_only_there(const fsl_card_F *base, const fsl_card_F *here, const fsl_card_F *there)
{
    return here == nullptr && there != nullptr && strcmp(there->uuid, base->uuid) != 0;
}

static int step_find_base(Store *s)
{
    return fsl_db_get_id(fsl_cx_db_repo(s->f), &s->base, common_ancestor_sql, s->before, s->target);
}

static int step_deck_base(Store *s)
{
    return fsl_deck_load_rid(s->f, &s->base_deck, s->base, FSL_SATYPE_CHECKIN);
}

static int step_deck_here(Store *s)
{
    return fsl_deck_load_rid(s->f, &s->here_deck, s->before, FSL_SATYPE_CHECKIN);
}

// s->deck holds the version merged in.
static int step_merge_deleted(Store *s)
{
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->base_deck);
    do {
        rc = fsl_deck_F_next(&s->base_deck, &card);
        fsl_card_F const *here = card != nullptr ? fsl_deck_F_search(&s->here_deck, card->name) : nullptr;
        fsl_card_F const *there = card != nullptr ? fsl_deck_F_search(&s->deck, card->name) : nullptr;
        if (card != nullptr &&
            (changed_only_there(card, here, there) || changed_only_there(card, there, here))) {
            say(STDOUT_FILENO, "conflict %s\n", card->name);
            s->count++;
        }
    } while ((rc == 0) & (card != nullptr));
    return rc;
}

// A conflict leaves the working copy as it is, says so in the attention file,
// and stops with EXIT_CONFLICT; otherwise the merge goes ahead.
static int step_merge_decide(Store *s)
{
    sync_state.clean_fork = s->count == 0;
    if (s->count == 0) return attention_remove(s->attention, "conflict", s->name) == 0 ? 0 : STEP_ERR;
    char header[CONF_NAME_MAX + 80];
    snprintf(header, sizeof header, "conflict %s: %u files changed both here and on the remote",
        s->name, s->count);
    return leave_item(s, "conflict", header, nullptr, EXIT_CONFLICT);
}

static int step_merge_message(Store *s)
{
    char path[PATH_CAP];
    [[maybe_unused]] size_t home = suit_home_path(path, sizeof path, "machine");
    ensure(home != 0);
    char machine[MACHINE_MAX + 1];
    if (machine_read(path, machine) != 0) return STEP_ERR;
    snprintf(s->tend_message, sizeof s->tend_message, "Merge edits from %s",
        machine[0] != '\0' ? machine : "this machine");
    s->message = s->tend_message;
    return 0;
}

// libfossil will not check in a merge that changes no file (both machines
// deleted the same file, say), so the files go back to the version here and the
// fork stays open until a later merge changes something.
static int step_merge_checkin(Store *s)
{
    int rc = step_checkin(s);
    return rc == FSL_RC_NOOP ? put_back(s) : rc;
}

static int step_merge_apply(Store *s)
{
    int rc = merge_from(s, false);
    return rc == 0 ? 0 : undo_failed(s, "merge", rc);
}

int store_sync(const char *name)
{
    static const Step pull[] = {
        PREPARE,
        {"find the remote", step_remote},
        {"open the working copy", step_ckout_existing},
        {"look for changes", step_scan},
        {"count the changes", step_count_local},
        {"find the version", step_before},
        {"pull", step_pull},
        {"find the version to update to", step_target},
        {"see where trunk is", step_pull_outcome},
    };
    static const Step trial[] = {
        PREPARE,
        {"find the attention file", step_attention_path},
        {"open the working copy", step_ckout_existing},
        {"find the version", step_before},
        {"look for a fork", step_find_fork},
        {"clear what a fork needed", step_no_fork},
        {"read the other version's manifest", step_deck_target},
        {"look for symlinks", step_deck_links},
        {"look for changes", step_scan},
        {"begin the trial", step_txn_begin},
        {"try the merge", step_merge_dry_run},
        {"find the common ancestor", step_find_base},
        {"read the common ancestor's manifest", step_deck_base},
        {"read this version's manifest", step_deck_here},
        {"look for deleted files", step_merge_deleted},
        {"end the trial", step_txn_rollback},
        {"decide", step_merge_decide},
    };
    static const Step merge[] = {
        PREPARE,
        {"open the working copy", step_ckout_existing},
        {"find the version", step_before},
        {"look for a fork", step_find_fork},
        {"name the check-in", step_merge_message},
        {"write the journal", step_journal_write},
        {"look for changes", step_scan},
        {"merge", step_merge_apply},
        {"look for changes", step_scan},
        {"check in the merge", step_merge_checkin},
        {"remove the journal", step_journal_remove},
    };
    static const Step push[] = {
        PREPARE,
        {"find the remote", step_remote},
        {"open the working copy", step_ckout_existing},
        {"push", step_push},
    };
    Store s;
    memset(&sync_state, 0, sizeof sync_state);
    int rc = run(&s, name, nullptr, pull, sizeof pull / sizeof pull[0]);
    if (rc == 0 && sync_state.pulled && sync_state.local_changes) {
        say(STDERR_FILENO, "local changes: run suit commit or wait for suit tend\n");
        rc = EXIT_LOCAL_CHANGES;
    } else if (rc == 0 && sync_state.pulled && sync_state.moved) {
        rc = store_update(name);
    }
    if (rc != 0 || !sync_state.pulled) {
        secret_wipe(sync_secret, sizeof sync_secret);
        return rc;
    }
    rc = run(&s, name, nullptr, trial, sizeof trial / sizeof trial[0]);
    if (rc == 0 && sync_state.clean_fork) rc = run(&s, name, nullptr, merge, sizeof merge / sizeof merge[0]);
    int pushed = rc == 0 || rc == EXIT_CONFLICT ? run(&s, name, nullptr, push, sizeof push / sizeof push[0]) : 0;
    secret_wipe(sync_secret, sizeof sync_secret);
    return pushed != 0 ? pushed : rc;
}

// ---- clone --------------------------------------------------------------------

static void remove_tree(char *path);

static int remove_entry(void *state, const char *entry)
{
    char path[PATH_CAP];
    [[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", (char *)state, entry);
    ensure(n > 0 && (size_t)n < sizeof path);
    struct stat st;
    if (sys_lstat(path, &st) == 0 && S_ISDIR(st.st_mode)) remove_tree(path);
    else (void)sys_unlink(path);
    return 0;
}

// Take PATH and all it holds away, as far as that can be done.
static void remove_tree(char *path)
{
    (void)sys_listdir(path, remove_entry, path);
    (void)sys_rmdir(path);
}

static int clone_check(const char *name, const char *url)
{
    if (!conf_name_ok(name, strlen(name), false)) {
        say(STDERR_FILENO, "suit: '%.40s' is not a wardrobe name (letters, digits, . _ -)\n", name);
        return 2;
    }
    const char *why = remote_url_check(url, strlen(url));
    if (why != nullptr) {
        say(STDERR_FILENO, "suit: clone %s: %s\n", name, why);
        return 2;
    }
    if (strncmp(url, "https://", 8) != 0) return 0;
    say(STDERR_FILENO, "suit: clone %s: this build of suit cannot use https yet\n", name);
    return EXIT_NO_TLS;
}

// Clone URL into the repository file TO, using the login saved for NAME.
static int clone_fetch(const char *name, const char *url, const char *to)
{
    Store s;
    memset(&s, 0, sizeof s);
    snprintf(s.name, sizeof s.name, "%s", name);
    char rpath[PATH_CAP];
    char cpath[PATH_CAP];
    [[maybe_unused]] int paths = remote_paths(rpath, cpath, sizeof rpath);
    ensure(paths == 0);  // store_clone found the same home
    if (load_login(&s, cpath) != 0) return 1;
    char full[REMOTE_URL_MAX + CRED_USER_MAX + 2];
    address_with_login(full, sizeof full, url, s.login);
    fsl_clone_config cc = fsl_clone_config_empty;
    cc.repo.filename = to;
    cc.repo.allowOverwrite = true;
    cc.repo.commitMessage = nullptr;
    fsl_b_external(&cc.xfer.url, full, -1);
    cc.xfer.op.clone = 3;
    cc.xfer.socketTimeoutSeconds = 30;
    cc.xfer.password.callback = give_secret;
    cc.xfer.password.ignoreSaved = true;
    cc.xfer.password.save = false;
    fsl_error err = fsl_error_empty;
    int rc = fsl_clone(&cc, &err);
    fsl_clone_config_cleanup(&cc);
    secret_wipe(sync_secret, sizeof sync_secret);
    secret_wipe(full, sizeof full);
    if (rc == 0) return 0;
    char host[REMOTE_URL_MAX + 1];
    char const *msg = "";
    fsl_size_t len = 0;
    (void)fsl_error_get(&err, &msg, &len);
    remote_host(url, host, sizeof host);
    say(STDERR_FILENO, "suit: clone %s: %s failed: %s: %.*s\n", name, host, fsl_rc_cstr(rc),
        (int)strcspn(msg, "\n"), msg);
    fsl_error_clear(&err);
    return rc == FSL_RC_REMOTE ? EXIT_REFUSED : EXIT_NETWORK;
}

static bool exists(const char *path)
{
    struct stat st;
    return sys_stat(path, &st) == 0;
}

int store_clone(const char *name, const char *url)
{
    int rc = clone_check(name, url);
    if (rc != 0) return rc;
    char rel[CONF_NAME_MAX + 32];
    char repo[PATH_CAP];
    char tmp[PATH_CAP];
    char dir[PATH_CAP];
    [[maybe_unused]] int n = snprintf(rel, sizeof rel, "wardrobes/%s.fossil", name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    size_t home = suit_home_path(repo, sizeof repo, rel);
    if (home == 0) return 1;
    n = snprintf(rel, sizeof rel, "store/%s", name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    [[maybe_unused]] size_t dir_home = suit_home_path(dir, sizeof dir, rel);
    ensure(dir_home != 0);
    n = snprintf(tmp, sizeof tmp, "%s.clone", repo);
    ensure(n > 0 && (size_t)n < sizeof tmp);
    if (exists(repo) || exists(dir)) {
        say(STDERR_FILENO, "suit: clone %s: there is already a wardrobe or a store of that name here\n", name);
        return EXIT_EXISTS;
    }
    char path[PATH_CAP];
    memcpy(path, repo, home);
    path[home] = '\0';
    rc = make_dir(path);
    snprintf(path + home, sizeof path - home, "/wardrobes");
    rc = rc != 0 ? rc : make_dir(path);
    if (rc != 0) return 1;
    rc = clone_fetch(name, url, tmp);
    if (rc == 0 && sys_rename(tmp, repo) != 0) {
        say(STDERR_FILENO, "suit: clone %s: cannot move %s into place: %s\n", name, tmp, strerror(errno));
        rc = 1;
    }
    if (rc != 0) {
        (void)sys_unlink(tmp);
        return rc;
    }
    rc = store_open(name);
    rc = rc != 0 ? rc : cmd_remote(name, url);
    if (rc != 0) {
        remove_tree(dir);
        (void)sys_unlink(repo);
        return rc;
    }
    say(STDOUT_FILENO, "cloned %s\n", name);
    return 0;
}

// ---- tend every wardrobe --------------------------------------------------------

constexpr size_t WARDROBES_MAX = 1024;

typedef struct {
    size_t n;
    char names[WARDROBES_MAX][CONF_NAME_MAX + 1];
} Wardrobes;

static int collect_wardrobe(void *state, const char *entry)
{
    Wardrobes *w = state;
    size_t len = strlen(entry);
    size_t base = len > 7 ? len - 7 : 0;
    bool wardrobe = base > 0 && base <= CONF_NAME_MAX && strcmp(entry + base, ".fossil") == 0 &&
        conf_name_ok(entry, base, false);
    if (!wardrobe) return 0;
    if (w->n == WARDROBES_MAX) return 1;
    memcpy(w->names[w->n], entry, base);
    w->names[w->n][base] = '\0';
    w->n++;
    return 0;
}

static int compare_names(const void *a, const void *b)
{
    return strcmp(a, b);
}

int store_tend_all(void)
{
    static Wardrobes w;
    w.n = 0;
    char dir[PATH_CAP];
    if (suit_home_path(dir, sizeof dir, "wardrobes") == 0) return 1;
    int rc = sys_listdir(dir, collect_wardrobe, &w);
    if (rc < 0 && errno == ENOENT) return 0;
    if (rc != 0) {
        if (rc > 0) say(STDERR_FILENO, "suit: tend: more than %zu wardrobes\n", WARDROBES_MAX);
        else say(STDERR_FILENO, "suit: tend: cannot list %s: %s\n", dir, strerror(errno));
        return 1;
    }
    qsort(w.names, w.n, sizeof w.names[0], compare_names);
    int worst = 0;
    for (size_t i = 0; i < w.n; i++) {
        rc = store_tend(w.names[i]);
        if (rc != 0) say(STDERR_FILENO, "suit: tend %s: did not end clean, exit %d\n", w.names[i], rc);
        worst = rc > worst ? rc : worst;
    }
    return worst;
}

// ---- upstreams ---------------------------------------------------------------------

constexpr size_t CHANGES_MAX = 8192;
constexpr size_t CHANGES_POOL = 4194304;

typedef struct {
    char kind;     // 'a' add, 'c' change, 'r' remove, 'x' a conflict that --theirs and --mine settle, 'u' one they do not
    uint32_t off;  // the path, in up.pool
} Change;

// What the upstream commands share between their sessions.
static struct {
    const UpstreamSpec *spec;
    const UpstreamFiles *files;
    const UpstreamSettle *settle;
    const char *upstream;
    bool *taken;
    UpstreamState *state;
    char *pin_out;
    size_t pin_cap;
    char branch[CONF_NAME_MAX + 16];
    char pin[UPSTREAM_PIN_MAX + 1];  // the pin in the comment of the branch's tip
    char text[CONF_NAME_MAX + UPSTREAM_PIN_MAX + 32];
    fsl_id_t root;   // trunk's first check-in
    fsl_id_t base;   // the base of the merge, or 0 for the common ancestor
    fsl_id_t tip;    // the branch's tip, 0 when nothing was taken
    fsl_id_t m;      // the accept being undone: its check-in
    fsl_id_t p;      // and trunk just before it
    unsigned skip;   // accepts newer than M that an undo already reversed
    bool merged;     // the tip is part of the version the working copy is at
    bool go;         // the trial found nothing in the way
    char skill[UPSTREAM_NAME_MAX + 1];
    bool skill_md;
    uint32_t nchanges;
    size_t used;
    Change changes[CHANGES_MAX];
    char pool[CHANGES_POOL];
    bool flag[UPSTREAM_FILES_MAX];
} up;

static void up_change(char kind, const char *path)
{
    size_t len = strlen(path) + 1;
    ensure(up.nchanges < CHANGES_MAX && up.used + len <= CHANGES_POOL);
    memcpy(up.pool + up.used, path, len);
    up.changes[up.nchanges].kind = kind;
    up.changes[up.nchanges++].off = (uint32_t)up.used;
    up.used += len;
}

static const char *change_path(const Change *c)
{
    return up.pool + c->off;
}

// Whole means the hash of a check-in, a space, a pin and a newline, and nothing after.
static bool up_record_whole(const char *text)
{
    size_t hex = strspn(text, "0123456789abcdef");
    bool space = text[hex] == ' ';
    size_t pin = strcspn(text + hex + space, "\n");
    return space && hex - 40 <= 24 && pin > 0 && strcmp(text + hex + space + pin, "\n") == 0;
}

// The check-in of this upstream's branch that the record TEXT names, or 0 when
// the record is not whole or names none. TEXT is cut after the hash.
static int up_named(Store *s, char *text, fsl_id_t *rid)
{
    bool whole = up_record_whole(text);
    text[strspn(text, "0123456789abcdef")] = '\0';
    *rid = 0;
    return whole ? fsl_db_get_id(fsl_cx_db_repo(s->f), rid,
        "SELECT b.rid FROM blob b JOIN tagxref x ON x.rid=b.rid WHERE b.uuid=%Q"
        " AND x.tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND x.tagtype>0 AND x.value=%Q",
        text, up.branch) : 0;
}

static int step_up_names(Store *s)
{
    (void)s;
    [[maybe_unused]] int n = snprintf(up.branch, sizeof up.branch, "upstream-%s", up.upstream);
    ensure(n > 0 && (size_t)n < sizeof up.branch);
    return 0;
}

// The branch's newest check-in; 0 when the branch has none.
static int step_up_tip(Store *s)
{
    up.tip = 0;
    return fsl_db_get_id(fsl_cx_db_repo(s->f), &up.tip,
        "SELECT x.rid FROM tagxref x JOIN event e ON e.objid=x.rid"
        " WHERE x.tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND x.tagtype>0"
        " AND x.value=%Q ORDER BY e.mtime DESC LIMIT 1", up.branch);
}

// Trunk's first check-in: the empty one every wardrobe starts with.
static int step_up_root(Store *s)
{
    up.root = 0;
    int rc = fsl_db_get_id(fsl_cx_db_repo(s->f), &up.root,
        "SELECT x.rid FROM tagxref x JOIN event e ON e.objid=x.rid"
        " WHERE x.tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND x.tagtype>0"
        " AND x.value='trunk' AND NOT EXISTS(SELECT 1 FROM plink WHERE cid=x.rid)"
        " ORDER BY e.mtime LIMIT 1");
    ensure(rc != 0 || up.root > 0);
    return rc;
}

// With no branch yet, an empty deck: it holds no file.
static int step_up_deck_tip(Store *s)
{
    if (up.tip > 0) return fsl_deck_load_rid(s->f, &s->here_deck, up.tip, FSL_SATYPE_CHECKIN);
    fsl_deck_init(s->f, &s->here_deck, FSL_SATYPE_CHECKIN);
    return 0;
}

// ---- take ----------------------------------------------------------------------------

static void up_clash(uint32_t i, const char *why, const char *other)
{
    say(STDERR_FILENO, "suit: upstream %s: %s %s%s\n", up.upstream, up.files->f[i].name, why, other);
    up.flag[i] = true;
}

// A file of the take that another upstream's branch already has.
static int up_other_branch(fsl_stmt *st, void *state)
{
    Store *s = state;
    const char *branch = fsl_stmt_g_text(st, 0, nullptr);
    fsl_deck d = fsl_deck_empty;
    int rc = fsl_deck_load_rid(s->f, &d, fsl_stmt_g_id(st, 1), FSL_SATYPE_CHECKIN);
    uint32_t i = 0;
    while ((rc == 0) & (i < up.files->n)) {
        if (fsl_deck_F_search(&d, up.files->f[i].name) != nullptr) {
            up_clash(i, "is also taken by upstream ", branch + strlen("upstream-"));
            s->count++;
        }
        i++;
    }
    fsl_deck_finalize(&d);
    return rc;
}

static int step_up_clash_others(Store *s)
{
    s->count = 0;
    return fsl_db_each(fsl_cx_db_repo(s->f), up_other_branch, s,
        "SELECT x.value, x.rid, max(e.mtime) FROM tagxref x JOIN event e ON e.objid=x.rid"
        " WHERE x.tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND x.tagtype>0"
        " AND x.value GLOB 'upstream-*' AND x.value<>%Q GROUP BY x.value", up.branch);
}

// The check-in of the branch that trunk's upstreams/NAME names, in up.base (0
// for none), its manifest in s->base_deck.
static int step_up_trunk_record(Store *s)
{
    char name[sizeof UPSTREAM_RECORD_DIR + CONF_NAME_MAX + 2];
    [[maybe_unused]] int n = snprintf(name, sizeof name, "%s/%s", UPSTREAM_RECORD_DIR, up.upstream);
    ensure(n > 0 && (size_t)n < sizeof name);
    fsl_card_F const *card = fsl_deck_F_search(&s->deck, name);
    char text[128 + UPSTREAM_PIN_MAX + 8] = {0};
    if (card != nullptr) {
        fsl_b content = fsl_b_empty;
        [[maybe_unused]] int got = fsl_content_get(s->f, fsl_uuid_to_rid(s->f, card->uuid), &content);
        ensure(got == 0);
        memcpy(text, content.mem, content.used < sizeof text ? content.used : sizeof text - 1);
        fsl_b_clear(&content);
    }
    int rc = up_named(s, text, &up.base);
    return ((rc != 0) | (up.base == 0)) ? rc : fsl_deck_load_rid(s->f, &s->base_deck, up.base, FSL_SATYPE_CHECKIN);
}

// A file trunk has that this upstream did not supply is the user's own: neither
// the branch's tip has it nor the check-in trunk's record names, which an undo
// may have put back.
static int step_up_clash_trunk(Store *s)
{
    uint32_t i = 0;
    do {
        const char *name = up.files->f[i].name;
        bool own = fsl_deck_F_search(&s->deck, name) != nullptr && fsl_deck_F_search(&s->here_deck, name) == nullptr &&
            (up.base == 0 || fsl_deck_F_search(&s->base_deck, name) == nullptr);
        if (own && !up.flag[i]) {
            up_clash(i, "is a file of your own; ", "the take would write over it");
            s->count++;
        }
        i++;
    } while (i < up.files->n);
    fsl_deck_finalize(&s->base_deck);
    s->exit_code = 1;
    return s->count > 0 ? STEP_DONE : 0;
}

static int step_up_deck_init(Store *s)
{
    fsl_deck_init(s->f, &s->base_deck, FSL_SATYPE_CHECKIN);
    return fsl_deck_D_set(&s->base_deck, fsl_db_julian_now(fsl_cx_db_repo(s->f)));
}

static int step_up_deck_user(Store *s)
{
    return fsl_deck_U_set(&s->base_deck, s->user);
}

static int step_up_deck_comment(Store *s)
{
    [[maybe_unused]] int n = snprintf(up.text, sizeof up.text, "upstream %s at %s", up.upstream, up.spec->pin);
    ensure(n > 0 && (size_t)n < sizeof up.text);
    return fsl_deck_C_set(&s->base_deck, up.text, -1);
}

static int step_up_deck_parent(Store *s)
{
    return fsl_deck_P_add_rid(&s->base_deck, up.tip > 0 ? up.tip : up.root);
}

// The rule of the lint for a skill folder, looked at while the take reads its
// files in byte order, so that a folder's files come together.
static bool up_skill(const char *name)
{
    const char *folder = name + 7;
    const char *slash = strncmp(name, "skills/", 7) == 0 ? strchr(folder, '/') : nullptr;
    if (slash == nullptr) return false;
    size_t n = (size_t)(slash - folder);
    if (strlen(up.skill) != n || memcmp(up.skill, folder, n) != 0) {
        if (up.skill[0] != '\0' && !up.skill_md) {
            char rel[UPSTREAM_NAME_MAX + 8];
            snprintf(rel, sizeof rel, "skills/%s", up.skill);
            report_add(rel, 0, "no SKILL.md");
        }
        memcpy(up.skill, folder, n);
        up.skill[n] = '\0';
        up.skill_md = false;
    }
    bool md = strcmp(slash + 1, "SKILL.md") == 0;
    up.skill_md |= md;
    return md;
}

// Read the file I of the take, lint it, and put it in the new check-in.
static int up_file(Store *s, uint32_t i)
{
    const UpstreamFiles *u = up.files;
    const char *name = u->f[i].name;
    bool md = up_skill(name);
    if (u->f[i].size > LINT_FILE_MAX) {
        report_add(name, 0, "larger than 4 MiB, not scanned");
        return 0;
    }
    char path[sizeof u->root + UPSTREAM_REL_MAX + 2];
    [[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", u->root, name + u->into_len);
    ensure(n > 0 && (size_t)n < sizeof path);
    ssize_t len = read_scanned(path);
    if (len < 0) return cannot(s, path, errno);
    sink_path = name;
    (void)lint_text(&rules, lint_allowed(&rules, name), file_buf, (size_t)len, report_sink, nullptr);
    if (md && !lint_has_header(file_buf, (size_t)len)) report_add(name, 1, "no header");
    fsl_b content = fsl_b_empty;
    fsl_b_external(&content, file_buf, (fsl_int_t)len);
    return fsl_deck_F_set_content(&s->base_deck, name, &content,
        u->f[i].exec ? FSL_FILE_PERM_EXE : FSL_FILE_PERM_REGULAR, nullptr);
}

static int step_up_files(Store *s)
{
    uint32_t i = 0;
    int rc;
    do {
        rc = up_file(s, i);
        i++;
    } while ((rc == 0) & (i < up.files->n));
    return rc;
}

// A finding stops the take; the transaction is rolled back when the session ends.
static int step_up_verdict(Store *s)
{
    if (up.skill[0] != '\0' && !up.skill_md) {
        char rel[UPSTREAM_NAME_MAX + 8];
        snprintf(rel, sizeof rel, "skills/%s", up.skill);
        report_add(rel, 0, "no SKILL.md");
    }
    report_close();
    if (report_problems == 0) return 0;
    report_show();
    s->exit_code = EXIT_LINT;
    return STEP_DONE;
}

// The branch's tree, file by file, against the new one.
static int step_up_compare(Store *s)
{
    fsl_card_F const *card = nullptr;
    unsigned same = 0;
    unsigned fresh = 0;
    unsigned old = 0;
    int rc;
    (void)fsl_deck_F_rewind(&s->base_deck);
    do {
        rc = fsl_deck_F_next(&s->base_deck, &card);
        fsl_card_F const *was = card != nullptr ? fsl_deck_F_search(&s->here_deck, card->name) : nullptr;
        same += was != nullptr && strcmp(was->uuid, card->uuid) == 0 && was->perm == card->perm;
        fresh += card != nullptr;
    } while ((rc == 0) & (card != nullptr));
    (void)fsl_deck_F_rewind(&s->here_deck);
    do {
        rc = fsl_deck_F_next(&s->here_deck, &card);
        old += card != nullptr;
    } while ((rc == 0) & (card != nullptr));
    if (same != fresh || fresh != old) return rc;
    say(STDOUT_FILENO, "upstream %s: no change\n", up.upstream);
    s->exit_code = 0;
    return STEP_DONE;
}

// The first check-in starts the branch: trunk's name for it is cancelled.
static int step_up_tag_branch(Store *s)
{
    return up.tip > 0 ? 0 : fsl_deck_branch_set(&s->base_deck, up.branch);
}

static int up_cancel_tag(fsl_stmt *st, void *state)
{
    Store *s = state;
    return fsl_deck_T_add(&s->base_deck, FSL_TAGTYPE_CANCEL, nullptr, fsl_stmt_g_text(st, 0, nullptr),
        "cancelled by branch.");
}

static int step_up_tag_cancel(Store *s)
{
    if (up.tip > 0) return 0;
    return fsl_db_each(fsl_cx_db_repo(s->f), up_cancel_tag, s,
        "SELECT tagname FROM tagxref, tag WHERE tagxref.rid=%" FSL_ID_T_PFMT
        " AND tagxref.tagid=tag.tagid AND tagtype>0 AND tagname GLOB 'sym-*' ORDER BY tagname", up.root);
}

static int step_up_save(Store *s)
{
    return fsl_deck_save(&s->base_deck, false);
}

// Offer the check-in and its files to the next push.
static int step_up_unsent(Store *s)
{
    return fsl_db_exec(fsl_cx_db_repo(s->f),
        "INSERT OR IGNORE INTO unsent SELECT fid FROM mlink WHERE mid=%" FSL_ID_T_PFMT " AND fid>0",
        s->base_deck.rid);
}

static int step_up_item(Store *s)
{
    char header[CONF_NAME_MAX + 48];
    snprintf(header, sizeof header, "upstream %s: update waiting for review", up.upstream);
    return attention_add(s->attention, ATTENTION_UPSTREAM, up.upstream, header, nullptr) == 0 ? 0 : STEP_ERR;
}

static int step_txn_commit(Store *s)
{
    return fsl_cx_txn_end_v2(s->f, true, false);
}

static int step_up_taken(Store *s)
{
    fsl_uuid_str uuid = fsl_rid_to_uuid(s->f, s->base_deck.rid);
    ensure(uuid != nullptr);
    say(STDOUT_FILENO, "upstream %s at %s: checked in %.12s\n", up.upstream, up.spec->pin, uuid);
    fsl_free(uuid);
    if (!up.spec->auto_accept) say(STDOUT_FILENO, "upstream %s: update waiting for review\n", up.upstream);
    *up.taken = true;
    return 0;
}

int store_upstream_take(const char *wardrobe, const UpstreamSpec *spec, const UpstreamFiles *f, bool *taken)
{
    static const Step steps[] = {
        PREPARE,
        {"find the attention file", step_attention_path},
        {"open the wardrobe", step_repo},
        {"find trunk", step_trunk},
        {"read trunk's manifest", step_deck_trunk},
        {"find the branch", step_up_names},
        {"find the branch's tip", step_up_tip},
        {"find trunk's first check-in", step_up_root},
        {"read the branch's manifest", step_up_deck_tip},
        {"look for files of another upstream", step_up_clash_others},
        {"read trunk's record", step_up_trunk_record},
        {"look for files of your own", step_up_clash_trunk},
        {"begin", step_txn_begin},
        {"read the lint rules", step_lint_rules},
        {"start the check-in", step_up_deck_init},
        {"name the user", step_up_deck_user},
        {"write the comment", step_up_deck_comment},
        {"name the parent", step_up_deck_parent},
        {"read the files", step_up_files},
        {"lint the files", step_up_verdict},
        {"look for a change", step_up_compare},
        {"start the branch", step_up_tag_branch},
        {"leave trunk's branch", step_up_tag_cancel},
        {"save the check-in", step_up_save},
        {"offer it to the next push", step_up_unsent},
        {"note it for review", step_up_item},
        {"end", step_txn_commit},
        {"report", step_up_taken},
    };
    Store s;
    memset(&up, 0, sizeof up);
    up.spec = spec;
    up.files = f;
    up.upstream = spec->name;
    up.taken = taken;
    *taken = false;
    return run(&s, wardrobe, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- accept and diff ---------------------------------------------------------------------

// The working copy's upstreams/NAME in TEXT, empty when there is none.
static int up_record_text(Store *s, char *text, size_t cap)
{
    char file[PATH_CAP];
    [[maybe_unused]] int n = snprintf(file, sizeof file, "%s/%s/%s", s->dir, UPSTREAM_RECORD_DIR, up.upstream);
    ensure(n > 0 && (size_t)n < sizeof file);
    memset(text, 0, cap);
    int fd = sys_open(file, O_RDONLY, 0);
    ssize_t got = fd >= 0 ? sys_read(fd, text, cap - 1) : 0;
    int err = fd < 0 ? errno : got < 0 ? errno : 0;
    if (fd >= 0) (void)sys_close(fd);
    if (err != 0 && err != ENOENT) {
        say(STDERR_FILENO, "suit: store %s: cannot read %s: %s\n", s->name, file, strerror(err));
        return STEP_ERR;
    }
    return 0;
}

// Whether the working copy's upstreams/NAME names the branch's tip: the hash
// and a space come first. A missing or malformed file means never accepted.
static int step_up_merged(Store *s)
{
    up.merged = false;
    if (up.tip == 0) return 0;
    char text[128 + UPSTREAM_PIN_MAX + 8];
    int rc = up_record_text(s, text, sizeof text);
    if (rc != 0) return rc;
    fsl_uuid_str uuid = fsl_rid_to_uuid(s->f, up.tip);
    ensure(uuid != nullptr);
    size_t len = strlen(uuid);
    up.merged = strncmp(text, uuid, len) == 0 && text[len] == ' ';
    fsl_free(uuid);
    return 0;
}

// An update of the working copy may have brought in an accept made on another
// machine: for each upstream branch whose tip the working copy's upstreams/NAME
// records, the item of that upstream is stale.
static int up_reconcile_one(fsl_stmt *st, void *state)
{
    Store *s = state;
    snprintf(up.text, sizeof up.text, "%s", fsl_stmt_g_text(st, 0, nullptr) + strlen("upstream-"));
    up.upstream = up.text;
    up.tip = fsl_stmt_g_id(st, 1);
    int rc = step_up_merged(s);
    if (rc != 0 || !up.merged) return rc;
    return attention_remove(s->attention, ATTENTION_UPSTREAM, up.upstream) == 0 ? 0 : STEP_ERR;
}

// Each branch's newest check-in, for the branches named like an upstream.
static int step_up_reconcile(Store *s)
{
    return fsl_db_each(fsl_cx_db_repo(s->f), up_reconcile_one, s,
        "SELECT x.value, x.rid FROM tagxref x JOIN event e ON e.objid=x.rid"
        " WHERE x.tagid=(SELECT tagid FROM tag WHERE tagname='branch') AND x.tagtype>0"
        " AND x.value GLOB 'upstream-?*' AND x.value NOT GLOB 'upstream-*[^A-Za-z0-9._-]*'"
        " AND length(x.value)<=%d AND e.mtime=(SELECT max(e2.mtime) FROM tagxref x2 JOIN event e2"
        " ON e2.objid=x2.rid WHERE x2.tagid=x.tagid AND x2.tagtype>0 AND x2.value=x.value)",
        (int)(CONF_NAME_MAX + strlen("upstream-")));
}

// The merge is made at trunk's tip, so that its check-in builds on trunk.
static int step_up_at_trunk(Store *s)
{
    if (s->before == s->trunk) return 0;
    say(STDERR_FILENO, "suit: upstream %s: the working copy of %s is not at trunk's tip; run suit store update %s first\n",
        up.upstream, s->name, s->name);
    s->exit_code = 1;
    return STEP_DONE;
}

static int step_up_has_branch(Store *s)
{
    if (up.tip > 0) return 0;
    say(STDERR_FILENO, "suit: upstream %s: nothing has been taken yet; run suit upstream %s take FOLDER\n",
        up.upstream, up.upstream);
    s->exit_code = 1;
    return STEP_DONE;
}

// Nothing to merge. An item left from before is stale, so it goes.
static int step_up_nothing(Store *s)
{
    if (!up.merged) return 0;
    say(STDOUT_FILENO, "upstream %s: nothing to accept\n", up.upstream);
    s->exit_code = attention_remove(s->attention, ATTENTION_UPSTREAM, up.upstream) == 0 ? 0 : 1;
    return STEP_DONE;
}

static int step_up_refuse_local(Store *s)
{
    if (s->count == 0) return 0;
    say(STDERR_FILENO, "local changes: run suit commit or wait for suit tend\n");
    s->exit_code = EXIT_LOCAL_CHANGES;
    return STEP_DONE;
}

static int step_up_target(Store *s)
{
    s->target = up.tip;
    return 0;
}

// What the merge would do to each file, by the letters of Change.kind. Every
// kind that can be reported has one.
static int collect_merge(fsl_merge_state const *state)
{
    static const char kinds[FSL_MERGE_FCHANGE_count] = {
        [FSL_MERGE_FCHANGE_NONE] = 'c',
        [FSL_MERGE_FCHANGE_ADDED] = 'a',
        [FSL_MERGE_FCHANGE_COPIED] = 'c',
        [FSL_MERGE_FCHANGE_RM] = 'r',
        [FSL_MERGE_FCHANGE_MERGED] = 'c',
        [FSL_MERGE_FCHANGE_CONFLICT_MERGED] = 'x',
        [FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED] = 'u',
        [FSL_MERGE_FCHANGE_CONFLICT_SYMLINK] = 'u',
        [FSL_MERGE_FCHANGE_CONFLICT_BINARY] = 'x',
        [FSL_MERGE_FCHANGE_RENAMED] = 'c',
    };
    ensure(state->fileChangeType >= 0 && state->fileChangeType < FSL_MERGE_FCHANGE_count);
    up_change(kinds[state->fileChangeType], state->filename);
    return 0;
}

static int up_merge(Store *s, bool dry_run)
{
    fsl_merge_opt o = fsl_merge_opt_empty;
    o.mergeRid = s->target;
    o.baselineRid = up.base;
    o.scanForChanges = false;
    o.dryRun = dry_run;
    o.callback = dry_run ? collect_merge : nullptr;
    return fsl_ckout_merge(s->f, &o);
}

static int step_up_dry_run(Store *s)
{
    up.nchanges = 0;
    up.used = 0;
    return up_merge(s, true);
}

static Change *up_find(const char *path)
{
    uint32_t i = 0;
    while (i < up.nchanges && strcmp(change_path(&up.changes[i]), path) != 0) i++;
    return i < up.nchanges ? &up.changes[i] : nullptr;
}

// The merge dropped, or left out, a file: that is a conflict, not a removal or nothing.
static void up_conflict(const char *path)
{
    Change *c = up_find(path);
    if (c == nullptr) up_change('x', path);
    else c->kind = 'x';
}

// libfossil drops a file the upstream deleted even if trunk changed it, and
// leaves out one trunk deleted and the upstream changed: conflicts both.
// s->deck holds the upstream's version.
static int step_up_deleted(Store *s)
{
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->base_deck);
    do {
        rc = fsl_deck_F_next(&s->base_deck, &card);
        fsl_card_F const *here = card != nullptr ? fsl_deck_F_search(&s->here_deck, card->name) : nullptr;
        fsl_card_F const *there = card != nullptr ? fsl_deck_F_search(&s->deck, card->name) : nullptr;
        if (card != nullptr &&
            (changed_only_there(card, here, there) || changed_only_there(card, there, here)))
            up_conflict(card->name);
    } while ((rc == 0) & (card != nullptr));
    return rc;
}

static int compare_changes(const void *a, const void *b)
{
    return strcmp(change_path(a), change_path(b));
}

static int step_up_sort(Store *s)
{
    (void)s;
    qsort(up.changes, up.nchanges, sizeof up.changes[0], compare_changes);
    return 0;
}

static bool listed(const char *const *list, uint32_t n, const char *path)
{
    uint32_t i = 0;
    while (i < n && strcmp(list[i], path) != 0) i++;
    return i < n;
}


// Leave the upstream's item in the attention file and stop with CODE, or with 1
// when that failed.
static int up_leave(Store *s, const char *header, int code)
{
    s->exit_code = attention_add(s->attention, ATTENTION_UPSTREAM, up.upstream, header, nullptr) == 0 ? code : 1;
    return STEP_DONE;
}

// Every conflict is settled, or the update waits, with the working copy as it is.
static int step_up_decide(Store *s)
{
    const UpstreamSettle *t = up.settle;
    for (uint32_t i = 0; i < t->ntheirs + t->nmine; i++) {
        const char *path = i < t->ntheirs ? t->theirs[i] : t->mine[i - t->ntheirs];
        const Change *c = up_find(path);
        if (c == nullptr || c->kind != 'x') {
            say(STDERR_FILENO, "suit: upstream %s: %s is not a conflict that --theirs or --mine can settle\n",
                up.upstream, path);
            s->exit_code = 2;
            return STEP_DONE;
        }
    }
    unsigned left = 0;
    for (uint32_t i = 0; i < up.nchanges; i++) {
        const char *path = change_path(&up.changes[i]);
        bool conflict = up.changes[i].kind == 'x' || up.changes[i].kind == 'u';
        if (conflict && !listed(t->theirs, t->ntheirs, path) && !listed(t->mine, t->nmine, path)) {
            say(STDOUT_FILENO, "conflict %s\n", path);
            left++;
        }
    }
    up.go = left == 0;
    if (up.go) return 0;
    char header[CONF_NAME_MAX + 48];
    snprintf(header, sizeof header, "upstream %s: %u files conflict", up.upstream, left);
    return up_leave(s, header, EXIT_CONFLICT);
}

static int step_up_diff_print(Store *s)
{
    for (uint32_t i = 0; i < up.nchanges; i++) {
        char kind = up.changes[i].kind;
        const char *word = kind == 'a' ? "add" : kind == 'c' ? "change" : kind == 'r' ? "remove" : "conflict";
        say(STDOUT_FILENO, "%s %s\n", word, change_path(&up.changes[i]));
    }
    s->exit_code = 0;
    return STEP_DONE;
}

// The base of the merge is the check-in of the branch whose content trunk
// reflects: the one upstreams/NAME names, or trunk's first check-in, the parent
// of the first take, when there is no record. Not the common ancestor: after an
// undo the tip of the accept that was undone is still an ancestor of trunk,
// and after an accept --mine the merge parent is no measure of what trunk holds.
// A record that is there but names no check-in of the branch leaves the base
// to the common ancestor.
static int step_up_base(Store *s)
{
    char text[128 + UPSTREAM_PIN_MAX + 8];
    int rc = up_record_text(s, text, sizeof text);
    if (rc != 0) return rc;
    bool none = text[0] == '\0';
    rc = up_named(s, text, &up.base);
    up.base = none ? up.root : up.base;
    s->base = up.base;
    if ((rc != 0) | (up.base > 0)) return rc;
    return step_find_base(s);
}

#define UP_TRIAL                                                                                   \
    PREPARE, {"find the attention file", step_attention_path},                                    \
        {"open the working copy", step_ckout_existing}, {"find the version", step_before},        \
        {"find trunk", step_trunk}, {"look at the version", step_up_at_trunk},                    \
        {"find the branch", step_up_names}, {"find the branch's tip", step_up_tip},               \
        {"look for what was taken", step_up_has_branch},                                          \
        {"look for what is merged", step_up_merged}, {"look for something to accept", step_up_nothing}, \
        {"look for changes", step_scan}, {"count the changes", step_count_local},                 \
        {"check for local changes", step_up_refuse_local}, {"find the tip to merge", step_up_target}, \
        {"find trunk's first check-in", step_up_root}, \
        {"read the upstream's manifest", step_deck_target}, {"look for symlinks", step_deck_links}, \
        {"find the base", step_up_base}, {"begin the trial", step_txn_begin},                     \
        {"try the merge", step_up_dry_run},                                                       \
        {"read the common ancestor's manifest", step_deck_base},                                  \
        {"read this version's manifest", step_deck_here},                                         \
        {"look for deleted files", step_up_deleted}, {"end the trial", step_txn_rollback},        \
        {"sort the files", step_up_sort}

// The pin the branch was taken at, from its tip's comment: the words after "upstream NAME at ".
static int step_up_pin(Store *s)
{
    char *text = nullptr;
    int rc = fsl_db_get_text(fsl_cx_db_repo(s->f), &text, nullptr,
        "SELECT comment FROM event WHERE objid=%" FSL_ID_T_PFMT, up.tip);
    size_t prefix = strlen("upstream ") + strlen(up.upstream) + strlen(" at ");
    const char *comment = text != nullptr ? text : "";
    snprintf(up.pin, sizeof up.pin, "%s", comment + (strncmp(comment, "upstream ", 9) == 0) * prefix);
    fsl_free(text);
    return rc;
}

static int step_up_message(Store *s)
{
    [[maybe_unused]] int n = snprintf(up.text, sizeof up.text, "Merge upstream %s at %s", up.upstream, up.pin);
    ensure(n > 0 && (size_t)n < sizeof up.text);
    s->message = up.text;
    return 0;
}

// The folders above FILE, down to the working copy's top (TOP bytes), that are empty.
static void up_prune(char *file, size_t top)
{
    for (char *slash = strrchr(file, '/'); (size_t)(slash - file) > top; slash = strrchr(file, '/')) {
        *slash = '\0';
        if (sys_rmdir(file) != 0) break;
    }
}

// A merge or a settling failed and has said so: every change goes, and a file
// the merge added is removed, with the folders it made while they are empty.
// A revert un-queues such a file but leaves it on the disk.
static int up_undo(Store *s)
{
    fsl_ckout_revert_opt revert = fsl_ckout_revert_opt_empty;
    revert.relativeToCwd = false;
    (void)fsl_ckout_revert(s->f, &revert);
    size_t top = strlen(s->dir);
    for (uint32_t i = 0; i < up.nchanges; i++) {
        if (up.changes[i].kind != 'a') continue;
        char file[PATH_CAP];
        [[maybe_unused]] int n = snprintf(file, sizeof file, "%s/%s", s->dir, change_path(&up.changes[i]));
        ensure(n > 0 && (size_t)n < sizeof file);
        (void)sys_unlink(file);
        up_prune(file, top);
    }
    char record[PATH_CAP];
    [[maybe_unused]] int r = snprintf(record, sizeof record, "%s/%s", s->dir, UPSTREAM_RECORD_DIR);
    ensure(r > 0 && (size_t)r < sizeof record);
    (void)sys_rmdir(record);  // made for the record, if it is empty
    return put_back_and_say(s);
}

// The file as the chosen version has it, in place of what the merge made of it.
static int up_settle_write(Store *s, const char *file, const fsl_card_F *card)
{
    fsl_b content = fsl_b_empty;
    [[maybe_unused]] int rc = fsl_content_get(s->f, fsl_uuid_to_rid(s->f, card->uuid), &content);
    ensure(rc == 0);
    int err = sys_write_atomic_exact(file, content.mem, content.used,
        card->perm == FSL_FILE_PERM_EXE ? 0755 : 0644);
    fsl_b_clear(&content);
    if (err != 0) {
        say(STDERR_FILENO, "suit: store %s: cannot write %s: %s\n", s->name, file, strerror(err));
        return up_undo(s);
    }
    fsl_ckout_manage_opt o = fsl_ckout_manage_opt_empty;
    o.filename = file;
    o.relativeToCwd = false;
    o.checkIgnoreGlobs = false;
    rc = fsl_ckout_manage(s->f, &o);
    ensure(rc == 0);
    return 0;
}

// A conflict the user settled: trunk's version, or the upstream's. A version
// without the file is what the merge already made.
static int up_settle_one(Store *s, const Change *c)
{
    if (c->kind != 'x') return 0;
    const char *path = change_path(c);
    fsl_deck *from = listed(up.settle->theirs, up.settle->ntheirs, path) ? &s->deck : &s->here_deck;
    fsl_card_F const *card = fsl_deck_F_search(from, path);
    if (card == nullptr) return 0;
    char file[PATH_CAP];
    [[maybe_unused]] int n = snprintf(file, sizeof file, "%s/%s", s->dir, path);
    ensure(n > 0 && (size_t)n < sizeof file);
    return up_settle_write(s, file, card);
}

static int step_up_settle(Store *s)
{
    uint32_t i = 0;
    int rc = 0;
    while ((rc == 0) & (i < up.nchanges)) rc = up_settle_one(s, &up.changes[i++]);
    return rc;
}

// The durable record of an accept, part of its check-in: upstreams/NAME holds
// the full hash of the accepted tip, a space, its pin and a newline.
static int step_up_record(Store *s)
{
    char dir[PATH_CAP];
    char file[PATH_CAP];
    [[maybe_unused]] int n = snprintf(dir, sizeof dir, "%s/%s", s->dir, UPSTREAM_RECORD_DIR);
    ensure(n > 0 && (size_t)n < sizeof dir);
    n = snprintf(file, sizeof file, "%s/%s", dir, up.upstream);
    ensure(n > 0 && (size_t)n < sizeof file);
    if (sys_mkdir(dir, 0755) != 0 && errno != EEXIST) {
        say(STDERR_FILENO, "suit: store %s: cannot create %s: %s\n", s->name, dir, strerror(errno));
        return up_undo(s);
    }
    fsl_uuid_str uuid = fsl_rid_to_uuid(s->f, up.tip);
    ensure(uuid != nullptr);
    char text[128 + UPSTREAM_PIN_MAX + 8];
    n = snprintf(text, sizeof text, "%s %s\n", uuid, up.pin);
    ensure(n > 0 && (size_t)n < sizeof text);
    fsl_free(uuid);
    int err = sys_write_atomic_mode(file, text, (size_t)n, 0644);
    if (err != 0) {
        say(STDERR_FILENO, "suit: store %s: cannot write %s: %s\n", s->name, file, strerror(err));
        return up_undo(s);
    }
    fsl_ckout_manage_opt o = fsl_ckout_manage_opt_empty;
    o.filename = file;
    o.relativeToCwd = false;
    o.checkIgnoreGlobs = false;
    [[maybe_unused]] int rc = fsl_ckout_manage(s->f, &o);
    ensure(rc == 0);
    return 0;
}

static int step_up_merge_apply(Store *s)
{
    int rc = up_merge(s, false);
    if (rc == 0) return 0;
    report(s, "merge", rc);
    return up_undo(s);
}

// The merge check-in always changes upstreams/NAME, so libfossil never sees an empty one.
static int step_up_checkin(Store *s)
{
    fsl_checkin_opt o = fsl_checkin_opt_empty;
    o.scanForChanges = false;
    o.message = s->message;
    o.user = s->user;
    return fsl_checkin_commit(s->f, &o, nullptr, nullptr);
}

static int step_up_merged_report(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "upstream %s: merged, checked in %.12s\n", up.upstream, uuid);
    return 0;
}

static int step_up_clear(Store *s)
{
    return attention_remove(s->attention, ATTENTION_UPSTREAM, up.upstream) == 0 ? 0 : STEP_ERR;
}

static int up_accept(const char *wardrobe, const char *upstream, const UpstreamSettle *settle, bool diff)
{
    static const Step accept[] = {UP_TRIAL, {"decide", step_up_decide}};
    static const Step list[] = {UP_TRIAL, {"list", step_up_diff_print}};
    static const Step merge[] = {
        PREPARE,
        {"find the attention file", step_attention_path},
        {"open the working copy", step_ckout_existing},
        {"find the version", step_before},
        {"find the branch", step_up_names},
        {"find the branch's tip", step_up_tip},
        {"find the pin", step_up_pin},
        {"name the check-in", step_up_message},
        {"find the tip to merge", step_up_target},
        {"read the upstream's manifest", step_deck_target},
        {"read this version's manifest", step_deck_here},
        {"write the journal", step_journal_write},
        {"look for changes", step_scan},
        {"merge", step_up_merge_apply},
        {"settle the conflicts", step_up_settle},
        {"record the accept", step_up_record},
        {"look for changes", step_scan},
        {"check in the merge", step_up_checkin},
        {"report", step_up_merged_report},
        {"remove the journal", step_journal_remove},
        {"clear the item", step_up_clear},
    };
    Store s;
    memset(&up, 0, sizeof up);
    up.upstream = upstream;
    up.settle = settle;
    const Step *trial = diff ? list : accept;
    size_t n = diff ? sizeof list / sizeof list[0] : sizeof accept / sizeof accept[0];
    int rc = run(&s, wardrobe, nullptr, trial, n);
    return rc == 0 && up.go ? run(&s, wardrobe, nullptr, merge, sizeof merge / sizeof merge[0]) : rc;
}

int store_upstream_accept(const char *wardrobe, const char *upstream, const UpstreamSettle *settle)
{
    return up_accept(wardrobe, upstream, settle, false);
}

int store_upstream_diff(const char *wardrobe, const char *upstream)
{
    static const UpstreamSettle none;
    return up_accept(wardrobe, upstream, &none, true);
}

// ---- undo ------------------------------------------------------------------------------

static int up_nothing_to_undo(Store *s)
{
    say(STDOUT_FILENO, "upstream %s: nothing to undo\n", up.upstream);
    s->exit_code = 0;
    return STEP_DONE;
}

// An accept is made of the record upstreams/NAME, whole.
static int step_up_undo_record(Store *s)
{
    char text[128 + UPSTREAM_PIN_MAX + 8];
    int rc = up_record_text(s, text, sizeof text);
    return rc != 0 || up_record_whole(text) ? rc : up_nothing_to_undo(s);
}

// Newest first: an undo hides the accept below it, and the first accept left is M.
static int up_undo_row(fsl_stmt *st, void *state)
{
    (void)state;
    const char *comment = fsl_stmt_g_text(st, 2, nullptr);
    if (comment[0] == 'U') {
        up.skip++;
        return 0;
    }
    if (up.skip > 0) {
        up.skip--;
        return 0;
    }
    up.m = fsl_stmt_g_id(st, 0);
    up.p = fsl_stmt_g_id(st, 1);
    snprintf(up.pin, sizeof up.pin, "%s", comment + strlen("Merge upstream ") + strlen(up.upstream) + strlen(" at "));
    return FSL_RC_BREAK;
}

// The accepts and undos of the upstream among trunk's ancestors, by their comments.
static int step_up_undo_find(Store *s)
{
    char merge[CONF_NAME_MAX + 32];
    char undo[CONF_NAME_MAX + 32];
    [[maybe_unused]] int n = snprintf(merge, sizeof merge, "Merge upstream %s at *", up.upstream);
    ensure(n > 0 && (size_t)n < sizeof merge);
    n = snprintf(undo, sizeof undo, "Undo upstream %s at *", up.upstream);
    ensure(n > 0 && (size_t)n < sizeof undo);
    int rc = fsl_db_each(fsl_cx_db_repo(s->f), up_undo_row, nullptr,
        "WITH RECURSIVE here(rid) AS (SELECT %" FSL_ID_T_PFMT " UNION SELECT pid FROM plink, here WHERE cid=here.rid)"
        " SELECT objid, (SELECT pid FROM plink WHERE cid=objid AND isprim), comment FROM here JOIN event ON objid=here.rid"
        " WHERE (comment GLOB %Q OR comment GLOB %Q) AND EXISTS(SELECT 1 FROM plink WHERE cid=objid AND isprim)"
        " ORDER BY mtime DESC, objid DESC", s->before, merge, undo);
    return ((rc != 0) | (up.m != 0)) ? rc : up_nothing_to_undo(s);
}

// The accept's check-in is the one to read, and trunk before it the one to go back to.
static int step_up_undo_versions(Store *s)
{
    s->target = up.m;
    s->base = up.p;
    return 0;
}

static bool up_same(const fsl_card_F *a, const fsl_card_F *b)
{
    return a == nullptr || b == nullptr ? a == b : strcmp(a->uuid, b->uuid) == 0 && a->perm == b->perm;
}

// A file the accept changed, with its content in M, P and at trunk's tip: put back as P has it when
// the tip still has M's, a conflict when it does not. 'a': P has it and trunk does not.
static void up_undo_one(const char *name, const fsl_card_F *m, const fsl_card_F *p, const fsl_card_F *t)
{
    if (up_same(m, p)) return;
    up_change(!up_same(t, m) ? 'x' : m == nullptr ? 'a' : 'c', name);
}

static int step_up_undo_plan(Store *s)
{
    up.nchanges = 0;
    up.used = 0;
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->deck);
    do {
        rc = fsl_deck_F_next(&s->deck, &card);
        if (card != nullptr)
            up_undo_one(card->name, card, fsl_deck_F_search(&s->base_deck, card->name),
                fsl_deck_F_search(&s->here_deck, card->name));
    } while ((rc == 0) & (card != nullptr));
    ensure(rc == 0);
    (void)fsl_deck_F_rewind(&s->base_deck);
    do {
        rc = fsl_deck_F_next(&s->base_deck, &card);
        if (card != nullptr && fsl_deck_F_search(&s->deck, card->name) == nullptr)
            up_undo_one(card->name, nullptr, card, fsl_deck_F_search(&s->here_deck, card->name));
    } while ((rc == 0) & (card != nullptr));
    return rc;
}

// A file to be brought back, where an untracked file of the user's already is, is a conflict.
static int step_up_undo_untracked(Store *s)
{
    for (uint32_t i = 0; i < up.nchanges; i++) {
        if (up.changes[i].kind != 'a') continue;
        char file[PATH_CAP];
        [[maybe_unused]] int n = snprintf(file, sizeof file, "%s/%s", s->dir, change_path(&up.changes[i]));
        ensure(n > 0 && (size_t)n < sizeof file);
        struct stat st;
        if (sys_lstat(file, &st) == 0) {
            up.changes[i].kind = 'x';
        } else if (errno != ENOENT) {
            say(STDERR_FILENO, "suit: store %s: cannot read %s: %s\n", s->name, file, strerror(errno));
            return STEP_ERR;
        }
    }
    return 0;
}

static int step_up_undo_decide(Store *s)
{
    unsigned left = 0;
    for (uint32_t i = 0; i < up.nchanges; i++) {
        if (up.changes[i].kind != 'x') continue;
        say(STDOUT_FILENO, "conflict %s\n", change_path(&up.changes[i]));
        left++;
    }
    if (left == 0) return 0;
    say(STDERR_FILENO, "suit: upstream %s: %u files conflict; undo changed nothing\n", up.upstream, left);
    s->exit_code = EXIT_CONFLICT;
    return STEP_DONE;
}

static int step_up_undo_message(Store *s)
{
    [[maybe_unused]] int n = snprintf(up.text, sizeof up.text, "Undo upstream %s at %s", up.upstream, up.pin);
    ensure(n > 0 && (size_t)n < sizeof up.text);
    s->message = up.text;
    return 0;
}

// The file as P has it, or gone when P had none.
static int up_undo_apply_one(Store *s, const Change *c)
{
    const char *path = change_path(c);
    char file[PATH_CAP];
    [[maybe_unused]] int n = snprintf(file, sizeof file, "%s/%s", s->dir, path);
    ensure(n > 0 && (size_t)n < sizeof file);
    fsl_card_F const *card = fsl_deck_F_search(&s->base_deck, path);
    if (card != nullptr) return up_settle_write(s, file, card);
    if (sys_unlink(file) != 0) {
        say(STDERR_FILENO, "suit: store %s: cannot remove %s: %s\n", s->name, file, strerror(errno));
        return up_undo(s);
    }
    up_prune(file, strlen(s->dir));
    return 0;
}

static int step_up_undo_apply(Store *s)
{
    uint32_t i = 0;
    int rc = 0;
    while ((rc == 0) & (i < up.nchanges)) rc = up_undo_apply_one(s, &up.changes[i++]);
    return rc;
}

static int step_up_undo_report(Store *s)
{
    fsl_uuid_cstr uuid = nullptr;
    fsl_ckout_version_info(s->f, nullptr, &uuid);
    say(STDOUT_FILENO, "upstream %s: undone, checked in %.12s\n", up.upstream, uuid);
    say(STDOUT_FILENO, "upstream %s: update waiting for review\n", up.upstream);
    return 0;
}

int store_upstream_undo(const char *wardrobe, const char *upstream)
{
    static const Step steps[] = {
        PREPARE,
        {"find the attention file", step_attention_path},
        {"open the working copy", step_ckout_existing},
        {"find the version", step_before},
        {"look for changes", step_scan},
        {"count the changes", step_count_local},
        {"check for local changes", step_up_refuse_local},
        {"find trunk", step_trunk},
        {"look at the version", step_up_at_trunk},
        {"read the record", step_up_undo_record},
        {"find the accept", step_up_undo_find},
        {"find the versions", step_up_undo_versions},
        {"read the accept's manifest", step_deck_target},
        {"read the manifest before it", step_deck_base},
        {"read this version's manifest", step_deck_here},
        {"list the files to put back", step_up_undo_plan},
        {"sort the files", step_up_sort},
        {"look for untracked files", step_up_undo_untracked},
        {"look for conflicts", step_up_undo_decide},
        {"name the check-in", step_up_undo_message},
        {"write the journal", step_journal_write},
        {"put the files back", step_up_undo_apply},
        {"look for changes", step_scan},
        {"find deletions", step_count_changes},
        {"check in the undo", step_up_checkin},
        {"report", step_up_undo_report},
        {"remove the journal", step_journal_remove},
        {"leave the item", step_up_item},
    };
    Store s;
    memset(&up, 0, sizeof up);
    up.upstream = upstream;
    return run(&s, wardrobe, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- where an upstream stands ----------------------------------------------------------

static int step_up_state(Store *s)
{
    char header[CONF_NAME_MAX + 64];
    int rc = attention_header(s->attention, ATTENTION_UPSTREAM, up.upstream, header, sizeof header);
    bool conflict = strstr(header, " files conflict") != nullptr;
    *up.state = up.tip == 0 ? UPSTREAM_NEVER_TAKEN : up.merged ? UPSTREAM_CURRENT :
        conflict ? UPSTREAM_CONFLICT : UPSTREAM_WAITING;
    snprintf(up.pin_out, up.pin_cap, "%s", up.pin);
    return rc == 0 ? 0 : STEP_ERR;
}

int store_upstream_state(const char *wardrobe, const char *upstream, UpstreamState *state, char *pin, size_t cap)
{
    static const Step steps[] = {
        PREPARE,
        {"find the attention file", step_attention_path},
        {"open the working copy", step_ckout_existing},
        {"find the version", step_before},
        {"find the branch", step_up_names},
        {"find the branch's tip", step_up_tip},
        {"look for what is merged", step_up_merged},
        {"find the pin", step_up_pin},
        {"look at the item", step_up_state},
    };
    Store s;
    memset(&up, 0, sizeof up);
    up.upstream = upstream;
    up.state = state;
    up.pin_out = pin;
    up.pin_cap = cap;
    return run(&s, wardrobe, nullptr, steps, sizeof steps / sizeof steps[0]);
}

// ---- what an accepted upstream holds ---------------------------------------------------------

// What store_upstream_entries shares between its steps.
static struct {
    const char *into;
    UpstreamEntrySink sink;
    void *state;
    fsl_id_t accepted;  // the check-in the record names, 0 for none
} ent;

// The check-in of the branch that the working copy's upstreams/NAME names; none for a record
// that is missing, not whole, or names a check-in that is not on the branch.
static int step_ent_record(Store *s)
{
    char text[128 + UPSTREAM_PIN_MAX + 8];
    int rc = up_record_text(s, text, sizeof text);
    if (rc != 0) return rc;
    ent.accepted = 0;
    return up_named(s, text, &ent.accepted);
}

static int step_ent_deck(Store *s)
{
    return ent.accepted == 0 ? 0 : fsl_deck_load_rid(s->f, &s->deck, ent.accepted, FSL_SATYPE_CHECKIN);
}

// The files are in byte order of path, so the entries under INTO come together.
static int step_ent_list(Store *s)
{
    if (ent.accepted == 0) return 0;
    size_t into_len = strlen(ent.into);
    char last[UPSTREAM_NAME_MAX + 1] = "";
    fsl_card_F const *card = nullptr;
    int rc;
    (void)fsl_deck_F_rewind(&s->deck);
    do {
        rc = fsl_deck_F_next(&s->deck, &card);
        bool under = card != nullptr && strncmp(card->name, ent.into, into_len) == 0 && card->name[into_len] == '/';
        if (!under) continue;
        const char *entry = card->name + into_len + 1;
        size_t len = strcspn(entry, "/");
        ensure(len > 0 && len < sizeof last);  // a name in a deck is not empty, and at most UPSTREAM_REL_MAX bytes
        if (strlen(last) == len && strncmp(last, entry, len) == 0) continue;
        memcpy(last, entry, len);
        last[len] = '\0';
        ent.sink(ent.state, last);
    } while ((rc == 0) & (card != nullptr));
    return rc;
}

int store_upstream_entries(const char *wardrobe, const char *upstream, const char *into, UpstreamEntrySink sink, void *state)
{
    static const Step steps[] = {
        {"find the wardrobe", step_paths},
        {"find the wardrobe", step_wardrobe_exists},
        {"start libfossil", step_init},
        {"open the working copy", step_ckout_existing},
        {"find the branch", step_up_names},
        {"read the record", step_ent_record},
        {"read the accepted check-in", step_ent_deck},
        {"list its entries", step_ent_list},
    };
    Store s;
    memset(&up, 0, sizeof up);
    up.upstream = upstream;
    ent.into = into;
    ent.sink = sink;
    ent.state = state;
    return run(&s, wardrobe, nullptr, steps, sizeof steps / sizeof steps[0]);
}