Skip to content
suit Artifact [2486e59404]
Login

Artifact [2486e59404]

Artifact 2486e5940431f4ede8340c2f982ad329fcf0b55c8214f75cd04048cc498ad7f8:


#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 "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;
}

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]);
    return rc != 0 ? rc : store_sync(name);
}

// ---- 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: report it and put every file back.
static int undo_failed(Store *s, const char *what, int rc)
{
    report(s, what, rc);
    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;
}

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.
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},
        {"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];

static int step_remote(Store *s)
{
    char rpath[PATH_CAP];
    char cpath[PATH_CAP];
    RemoteError e;
    static Remotes remotes;
    static Creds creds;
    [[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;
    }
    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;
}

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

// 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];
    bool login = s->login[0] != '\0' && strncmp(s->url, "http://", 7) == 0;
    snprintf(url, sizeof url, "%.7s%s%s%s", s->url, login ? s->login : "", login ? "@" : "", s->url + 7);
    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;
}