Skip to content
suit Artifact [fb23f1965e]
Login

Artifact [fb23f1965e]

Artifact fb23f1965e41b000e9093b10ebb9f1d60a394919513851f60d66c7574d5c36d5:


#include "assets.h"
#include "commands.h"
#include "conf.h"
#include "curate.h"
#include "place.h"
#include "platform.h"
#include "resolve.h"
#include "store.h"
#include "wardrobes.h"

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

// `suit curate apply FILE [--yes]` (docs/curate.md, "Applying the choices"). The choices are worked out
// on the text of each wardrobe's suit.conf, in memory: every step changes the text and parses and checks the
// whole set again, so what is decided next is decided on what the earlier steps made. Nothing is written
// until the whole plan is made, and then only with --yes.

static_assert((int)AK_SKILL == 0 && (int)AK_AGENT == 1 && (int)AK_COMMAND == 2);

constexpr uint32_t NO = 0xffffffffu;
constexpr uint32_t SEC_WORDS = (CONF_SECTION_MAX + 63) / 64;
// A little room beyond the limit of a file, for what one step adds before the parser can say it is too big.
constexpr size_t TEXT_CAP = CONF_FILE_MAX + 2 * CONF_LINE_MAX + 1024;
constexpr size_t WORDS_MAX = 2100;  // a line of at most 4096 bytes holds fewer words
constexpr size_t WKEY_MAX = 2 * CONF_WEAR_MAX;

typedef uint64_t Bits[SEC_WORDS];

static bool bit_get(const uint64_t *b, uint32_t i)
{
    return (b[i / 64] >> (i % 64) & 1) != 0;
}

static void bit_set(uint64_t *b, uint32_t i)
{
    b[i / 64] |= 1ull << (i % 64);
}

static bool bits_any(const uint64_t *b)
{
    uint64_t any = 0;
    for (uint32_t i = 0; i < SEC_WORDS; i++) any |= b[i];
    return any != 0;
}

typedef struct {
    CurateChoice c;
    int line;
    uint32_t ward;
    uint32_t aidx;  // in the assets of its kind; NO if it is not there and the line is skipped
    bool effective;
    Bits listed;  // the outfits (sections of `before`) that list it
    Bits reach;   // the wears (sections of `before`) that reach it, outfits named attic excepted
    Bits after;   // the same wears, in the set after the changes (sections of `cur`)
} Choice;

static Choice choices[CURATE_ASSETS_MAX];
static uint32_t nchoices;
static uint32_t choice_of[AK_COMMAND + 1][ASSET_MAX];
static char file_buf[CHOICES_FILE_MAX + 1];
static const char *file_arg;

static Wards wards;
static Assets assets;
static Conf before;  // the set as it is on disk
static Conf cur;     // the set as the changes made so far leave it
static Conf part;
static char orig[WARDROBE_MAX][TEXT_CAP];
static size_t orig_len[WARDROBE_MAX];
static char text[WARDROBE_MAX][TEXT_CAP];
static size_t text_len[WARDROBE_MAX];
static unsigned gen[WARDROBE_MAX];  // how many times a wardrobe's text was changed
static unsigned counts[3][WARDROBE_MAX];  // the choices that changed a wardrobe, by act
static bool expanded[CONF_SECTION_MAX][3];  // `before`'s outfit and kind whose `*` or pattern was made a list
static Bits user_outfits;
// The outfits made in this run and the wardrobe each is in; and which wardrobes need which checked in first:
// dep[u][v] means v has a wear that names an outfit made in u.
typedef struct {
    char name[CONF_NAME_MAX + 1];
    uint32_t ward;
} Made;
static Made made[CONF_OUTFIT_MAX];
static uint32_t nmade;
static bool dep[WARDROBE_MAX][WARDROBE_MAX];  // the outfits of `before` that a user wear reaches
static int fail_rc;
static Out out;

static const char *const kind_word[AK_COMMAND + 1] = {"skill", "agent", "command"};
static const char *const kind_key[AK_COMMAND + 1] = {"skills", "agents", "commands"};

__attribute__((format(printf, 1, 2))) static void emit(const char *fmt, ...)
{
    char line[2 * CONF_LINE_MAX + 256];
    va_list ap;
    va_start(ap, fmt);
    [[maybe_unused]] int n = vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    ensure(n > 0 && (size_t)n < sizeof line);  // a path and the words around it
    out_str(&out, line);
}

// ---- looking in a Conf -------------------------------------------------------------------------------

static const Entry *find_entry(const Conf *c, const Section *s, const char *key)
{
    for (uint32_t i = 0; i < s->count; i++)
        if (strcmp(c->entries[s->first + i].key, key) == 0) return &c->entries[s->first + i];
    return nullptr;
}

static uint32_t find_outfit(const Conf *c, const char *name, size_t len)
{
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        if (s->kind == KIND_OUTFIT && strlen(s->arg[0]) == len && memcmp(s->arg[0], name, len) == 0) return i;
    }
    return NO;
}

// The wear section SCOPE and TARGET with no machine limit.
static uint32_t find_wear(const Conf *c, const char *scope, const char *target)
{
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        if (s->kind == KIND_WEAR && strcmp(s->arg[0], scope) == 0 && strcmp(s->arg[1], target) == 0 && s->arg[2][0] == '\0')
            return i;
    }
    return NO;
}

static void wear_text(const Section *s, char *out_text, size_t cap)
{
    [[maybe_unused]] int n = snprintf(out_text, cap, "%s%s%s%s%s", s->arg[0], s->arg[1][0] != '\0' ? " " : "", s->arg[1],
        s->arg[2][0] != '\0' ? " machine=" : "", s->arg[2]);
    ensure(n > 0 && (size_t)n < cap);  // a header is one line
}

// Mark the outfits the list VAL names.
static void seed_names(const Conf *c, const char *val, Bits seen)
{
    const char *w;
    size_t len;
    while (conf_list_next(&val, &w, &len)) {
        uint32_t o = find_outfit(c, w, len);
        ensure(o != NO);  // the config was checked
        bit_set(seen, o);
    }
}

static void seed_wear(const Conf *c, uint32_t wear, Bits seen)
{
    const Entry *en = find_entry(c, &c->sections[wear], "outfits");
    if (en != nullptr) seed_names(c, en->val, seen);
}

// Add what the marked outfits include, and so on.
static void spread(const Conf *c, Bits seen)
{
    bool grew;
    do {
        grew = false;
        for (uint32_t i = 0; i < c->nsections; i++) {
            if (c->sections[i].kind != KIND_OUTFIT || !bit_get(seen, i)) continue;
            const Entry *inc = find_entry(c, &c->sections[i], "include");
            if (inc == nullptr) continue;
            const char *v = inc->val;
            const char *w;
            size_t len;
            while (conf_list_next(&v, &w, &len)) {
                uint32_t o = find_outfit(c, w, len);
                ensure(o != NO);
                if (!bit_get(seen, o)) {
                    bit_set(seen, o);
                    grew = true;
                }
            }
        }
    } while (grew);
}

// Whether the wears of SCOPE and TARGET with no machine limit reach OUTFIT, which exists.
static bool plain_reaches(const Conf *c, const char *scope, const char *target, const char *outfit)
{
    Bits seen = {};
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        if (s->kind == KIND_WEAR && strcmp(s->arg[0], scope) == 0 && strcmp(s->arg[1], target) == 0 && s->arg[2][0] == '\0')
            seed_wear(c, i, seen);
    }
    spread(c, seen);
    uint32_t o = find_outfit(c, outfit, strlen(outfit));
    ensure(o != NO);
    return bit_get(seen, o);
}

// Whether a plain wear of the project PROJECT names OUTFIT itself.
static bool personal_names(const Conf *c, const char *project, const char *outfit)
{
    uint32_t wi = find_wear(c, "personal", project);
    if (wi == NO) return false;
    const Entry *en = find_entry(c, &c->sections[wi], "outfits");
    if (en == nullptr) return false;
    const char *v = en->val;
    const char *w;
    size_t len;
    while (conf_list_next(&v, &w, &len))
        if (strlen(outfit) == len && memcmp(outfit, w, len) == 0) return true;
    return false;
}

// ---- the text of the wardrobes ---------------------------------------------------------------------------

// Parse every wardrobe's text and check the set as one. False after a message.
static bool rebuild(Conf *dst, char (*t)[TEXT_CAP], const size_t *len)
{
    ConfError e;
    conf_merge_init(dst);
    for (uint32_t i = 0; i < wards.n; i++) {
        if (!conf_parse_part(&part, t[i], len[i], &e)) {
            say(STDERR_FILENO, "%s:%d: %s\n", wards.w[i].conf, e.line, e.msg);
            return false;
        }
        if (!conf_merge(dst, &part, i, &wards, &e)) {
            say(STDERR_FILENO, "%s:%d: %s\n", wards.w[e.ward].conf, e.line, e.msg);
            return false;
        }
    }
    if (conf_check(dst, &e)) return true;
    say(STDERR_FILENO, "%s:%d: %s\n", wards.w[e.ward].conf, e.line, e.msg);
    return false;
}

// WARD's text was changed: parse and check the set again.
static bool changed(uint32_t ward)
{
    gen[ward]++;
    if (rebuild(&cur, text, text_len)) return true;
    say(STDERR_FILENO, "suit: the changes make the config of the wardrobes invalid; nothing is changed\n");
    fail_rc = 1;
    return false;
}

static bool finish_edit(EditResult r, uint32_t ward, const char *what)
{
    if (r == EDIT_LONG) {
        say(STDERR_FILENO, "suit: %s would have a line of more than %zu bytes; split it by hand and run this again\n", what,
            CONF_LINE_MAX);
        fail_rc = 2;
        return false;
    }
    ensure(r == EDIT_OK);  // TEXT_CAP has room for what one step adds
    return changed(ward);
}

// Split the list VAL into words in BUF (CONF_LINE_MAX + 1 bytes); the number of words.
static size_t split_list(const char *val, char *buf, const char **words)
{
    size_t n = 0;
    const char *v = val;
    const char *w;
    size_t len;
    while (conf_list_next(&v, &w, &len)) {
        memcpy(buf, w, len);
        buf[len] = '\0';
        words[n++] = buf;
        buf += len + 1;
    }
    return n;
}

// The place of WORD in the WORDS, where the list is in byte order and WORD goes in order; else the end.
static size_t insert_at(const char *const *words, size_t n, const char *word)
{
    for (size_t i = 1; i < n; i++)
        if (strcmp(words[i - 1], words[i]) >= 0) return n;
    size_t at = 0;
    while (at < n && strcmp(words[at], word) < 0) at++;
    return at;
}

// Add WORD to the list KEY of section SI of `cur`, in the text of its wardrobe; make the entry if it has none.
// WHAT names the section in a message.
static bool add_word(uint32_t si, const char *key, const char *word, const char *what)
{
    const Section *s = &cur.sections[si];
    uint32_t w = s->ward;
    const Entry *en = find_entry(&cur, s, key);
    if (en == nullptr) {
        char line[CONF_NAME_MAX + 32];
        [[maybe_unused]] int n = snprintf(line, sizeof line, "%s = %s", key, word);
        ensure(n > 0 && (size_t)n < sizeof line);
        int after = s->count > 0 ? cur.entries[s->first + s->count - 1].line : s->line;
        return finish_edit(curate_edit_insert(text[w], &text_len[w], TEXT_CAP, after, line), w, what);
    }
    char buf[CONF_LINE_MAX + 1];
    const char *words[WORDS_MAX + 1];
    size_t n = split_list(en->val, buf, words);
    for (size_t i = 0; i < n; i++)
        if (glob_match(words[i], word)) return true;  // it is there already
    size_t at = insert_at(words, n, word);
    memmove(words + at + 1, words + at, (n - at) * sizeof words[0]);
    words[at] = word;
    return finish_edit(curate_edit_value(text[w], &text_len[w], TEXT_CAP, en->line, words, n + 1), w, what);
}

// ---- one choice -----------------------------------------------------------------------------------------

static bool other_ward(const Choice *ch, const char *outfit, uint32_t where)
{
    say(STDERR_FILENO,
        "%s:%d: the outfit %s is defined in wardrobe %s, and an outfit lists only the assets of its own wardrobe: the %s %s of wardrobe %s "
        "cannot go in it\n",
        file_arg, ch->line, outfit, wards.w[where].name, kind_word[ch->c.kind], ch->c.name, ch->c.ward);
    fail_rc = 2;
    return false;
}

// The outfit NAME exists, in the wardrobe of the asset of CH.
static bool ensure_outfit(const Choice *ch, const char *name)
{
    uint32_t si = find_outfit(&cur, name, strlen(name));
    if (si != NO) {
        if (cur.sections[si].ward == ch->ward) return true;
        return other_ward(ch, name, cur.sections[si].ward);
    }
    char header[CONF_NAME_MAX + 16];
    [[maybe_unused]] int n = snprintf(header, sizeof header, "[outfit %s]", name);
    ensure(n > 0 && (size_t)n < sizeof header);
    emit("  outfit %s: create in %s\n", name, wards.w[ch->ward].name);
    if (!finish_edit(curate_edit_append(text[ch->ward], &text_len[ch->ward], TEXT_CAP, header, nullptr), ch->ward, name)) return false;
    ensure(nmade < CONF_OUTFIT_MAX);  // the set would have been refused
    memcpy(made[nmade].name, name, strlen(name) + 1);
    made[nmade++].ward = ch->ward;
    return true;
}

static bool name_too_long(const Choice *ch, const char *what)
{
    say(STDERR_FILENO, "%s:%d: the name of wardrobe %s is too long for a curation outfit (%s.%s is over %zu bytes)\n", file_arg, ch->line,
        ch->c.ward, what, ch->c.ward, CONF_NAME_MAX);
    fail_rc = 2;
    return false;
}

// The outfit of the asset of CH that is called BASE here (attic, kept): BASE.WARDROBE if it is there; else a plain
// BASE of this wardrobe, made by hand; else BASE.WARDROBE, to be made. False after a message if that name is too long.
static bool home_outfit(const Choice *ch, const char *base, char *name)
{
    if (curate_home_outfit(base, ch->c.ward, name) == 0) return name_too_long(ch, base);
    if (find_outfit(&cur, name, strlen(name)) != NO) return true;
    uint32_t plain = find_outfit(&cur, base, strlen(base));
    if (plain != NO && cur.sections[plain].ward == ch->ward) memcpy(name, base, strlen(base) + 1);
    return true;
}

// The wear in the wardrobe WARD now names OUTFIT: if it was made in another wardrobe, that one is checked in first.
static void note_ref(uint32_t ward, const char *outfit)
{
    for (uint32_t i = 0; i < nmade; i++)
        if (strcmp(made[i].name, outfit) == 0 && made[i].ward != ward) dep[made[i].ward][ward] = true;
}

static bool add_to(const Choice *ch, const char *outfit)
{
    uint32_t si = find_outfit(&cur, outfit, strlen(outfit));
    ensure(si != NO);  // ensure_outfit made it
    char what[CONF_NAME_MAX + 16];
    snprintf(what, sizeof what, "outfit %s", outfit);
    emit("  outfit %s: add %s\n", outfit, ch->c.name);
    return add_word(si, kind_key[ch->c.kind], ch->c.name, what);
}

static void note_expanded(const char *outfit, int kind)
{
    uint32_t b = find_outfit(&before, outfit, strlen(outfit));
    ensure(b != NO);
    expanded[b][kind] = true;
}

// Take the asset of CH out of the outfit OUTFIT, which lists it. A `*` or a pattern that reaches it is
// made the explicit list of the names it reaches, byte-ordered, less this one.
static bool remove_from(const Choice *ch, const char *outfit)
{
    uint32_t si = find_outfit(&cur, outfit, strlen(outfit));
    ensure(si != NO);
    const Section *s = &cur.sections[si];
    const Entry *en = find_entry(&cur, s, kind_key[ch->c.kind]);
    ensure(en != nullptr);  // it lists the asset, so it has the key
    char buf[CONF_LINE_MAX + 1];
    const char *in[WORDS_MAX + 1];
    const char *words[WORDS_MAX + 1];
    size_t nin = split_list(en->val, buf, in);
    size_t n = 0;
    size_t bytes = 0;
    bool grew = false;
    const NameList *have = &assets.list[ch->c.kind];
    char what[CONF_NAME_MAX + 16];
    snprintf(what, sizeof what, "outfit %s", outfit);
    for (size_t i = 0; i < nin; i++) {
        bool glob = strchr(in[i], '*') != nullptr;
        if (!glob || !glob_match(in[i], ch->c.name)) {
            if (!glob && strcmp(in[i], ch->c.name) == 0) continue;
            bytes += strlen(in[i]) + 1;  // a line that was whole holds these
            words[n++] = in[i];
            continue;
        }
        grew = true;
        for (uint32_t a = 0; a < have->n; a++) {
            if (have->ward[a] != s->ward || !glob_match(in[i], have->name[a]) || strcmp(have->name[a], ch->c.name) == 0) continue;
            if (!conf_name_ok(have->name[a], strlen(have->name[a]), false)) {
                say(STDERR_FILENO, "suit: outfit %s: `%s = %s` reaches the name '%s', which a list cannot hold; rename it first\n",
                    outfit, kind_key[ch->c.kind], in[i], have->name[a]);
                fail_rc = 2;
                return false;
            }
            bool seen = false;
            for (size_t j = 0; j < n; j++) seen |= strcmp(words[j], have->name[a]) == 0;
            for (size_t j = i + 1; j < nin; j++) seen |= strcmp(in[j], have->name[a]) == 0;
            if (seen) continue;
            bytes += strlen(have->name[a]) + 1;
            if (bytes > CONF_LINE_MAX + 1) return finish_edit(EDIT_LONG, s->ward, what);
            words[n++] = have->name[a];
        }
    }
    if (grew) note_expanded(outfit, ch->c.kind);
    emit("  outfit %s: remove %s\n", outfit, ch->c.name);
    return finish_edit(curate_edit_value(text[s->ward], &text_len[s->ward], TEXT_CAP, en->line, words, n), s->ward, what);
}

// The wear SCOPE and TARGET (a plain one) reaches OUTFIT: add it to its `outfits`, or make the wear, in
// the wardrobe that holds `[wear user]` if the wear is a personal one, else in the wardrobe of CH.
static bool ensure_wear(const Choice *ch, const char *scope, const char *target, const char *outfit)
{
    if (plain_reaches(&cur, scope, target, outfit)) return true;
    uint32_t wi = find_wear(&cur, scope, target);
    char shown[CHOICE_PROJECT_MAX + 16];
    snprintf(shown, sizeof shown, "%s%s%s", scope, target[0] != '\0' ? " " : "", target);
    if (wi == NO) {
        uint32_t home = ch->ward;
        uint32_t user = find_wear(&cur, "user", "");
        if (target[0] != '\0' && user != NO) home = cur.sections[user].ward;
        char header[CHOICE_PROJECT_MAX + 32];
        [[maybe_unused]] int n = snprintf(header, sizeof header, "[wear %s]", shown);
        ensure(n > 0 && (size_t)n < sizeof header);
        emit("  wear %s: create in %s\n", shown, wards.w[home].name);
        if (!finish_edit(curate_edit_append(text[home], &text_len[home], TEXT_CAP, header, nullptr), home, shown)) return false;
        wi = find_wear(&cur, scope, target);
        ensure(wi != NO);
    }
    emit("  wear %s: add outfit %s\n", shown, outfit);
    char what[CHOICE_PROJECT_MAX + 32];
    snprintf(what, sizeof what, "wear %s", shown);
    uint32_t wear_ward = cur.sections[wi].ward;
    if (!add_word(wi, "outfits", outfit, what)) return false;
    note_ref(wear_ward, outfit);
    return true;
}

static bool do_keep(const Choice *ch)
{
    char kept[CONF_NAME_MAX + 1];
    if (!home_outfit(ch, "kept", kept)) return false;
    if (!ensure_outfit(ch, kept)) return false;
    for (uint32_t s = 0; s < before.nsections; s++) {
        if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || !curate_is_attic(before.sections[s].arg[0])) continue;
        if (!remove_from(ch, before.sections[s].arg[0])) return false;
    }
    return add_to(ch, kept) && ensure_wear(ch, "user", "", kept);
}

static bool do_retire(const Choice *ch)
{
    bool in_attic = false;
    for (uint32_t s = 0; s < before.nsections; s++)
        in_attic |= before.sections[s].kind == KIND_OUTFIT && bit_get(ch->listed, s) && curate_is_attic(before.sections[s].arg[0]);
    char attic[CONF_NAME_MAX + 1];
    if (!home_outfit(ch, "attic", attic)) return false;
    if (!in_attic && !ensure_outfit(ch, attic)) return false;
    for (uint32_t s = 0; s < before.nsections; s++) {
        if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || curate_is_attic(before.sections[s].arg[0])) continue;
        if (!remove_from(ch, before.sections[s].arg[0])) return false;
    }
    return in_attic || add_to(ch, attic);
}

// The outfit of the project of CH: the first of the names personal-SLUG, personal-SLUG-2, ... that is not
// there, or is there and is worn by this project's own wear.
static bool pick_personal(const Choice *ch, char *name)
{
    for (unsigned k = 1;; k++) {
        if (curate_personal_outfit(ch->c.ward, ch->c.project, k, name) == 0) return name_too_long(ch, "personal");
        uint32_t si = find_outfit(&cur, name, strlen(name));
        if (si == NO) return true;
        if (!personal_names(&cur, ch->c.project, name)) continue;
        if (cur.sections[si].ward == ch->ward) return true;
        return other_ward(ch, name, cur.sections[si].ward);
    }
}

static bool do_personal(const Choice *ch)
{
    char outfit[CONF_NAME_MAX + 1];
    if (!pick_personal(ch, outfit) || !ensure_outfit(ch, outfit)) return false;
    for (uint32_t s = 0; s < before.nsections; s++) {
        if (before.sections[s].kind != KIND_OUTFIT || !bit_get(ch->listed, s) || !bit_get(user_outfits, s)) continue;
        if (!remove_from(ch, before.sections[s].arg[0])) return false;
    }
    return add_to(ch, outfit) && ensure_wear(ch, "personal", ch->c.project, outfit);
}

static void describe(const Choice *ch, char *line, size_t cap)
{
    static const char *const act_word[] = {"keep", "personal", "retire"};
    [[maybe_unused]] int n = snprintf(line, cap, "%s %s %s %s%s%s", act_word[ch->c.act], kind_word[ch->c.kind], ch->c.ward, ch->c.name,
        ch->c.act == CHOICE_PERSONAL ? " " : "", ch->c.project);
    ensure(n > 0 && (size_t)n < cap);
}

static bool run_choice(const Choice *ch)
{
    unsigned before_gen[WARDROBE_MAX];
    memcpy(before_gen, gen, sizeof gen);
    char line[CHOICE_PROJECT_MAX + 2 * CONF_NAME_MAX + 64];
    describe(ch, line, sizeof line);
    emit("%s\n", line);
    bool ok = ch->c.act == CHOICE_KEEP ? do_keep(ch) : ch->c.act == CHOICE_RETIRE ? do_retire(ch) : do_personal(ch);
    if (!ok) return false;
    for (uint32_t v = 0; v < wards.n; v++)
        if (gen[v] != before_gen[v]) counts[ch->c.act][v]++;
    return true;
}

// ---- state: which choices change something ----------------------------------------------------------------

static void on_reach(void *state, const Section *wear, const Section *outfit, AssetKind kind, uint32_t index)
{
    bool after = *(const bool *)state;
    uint32_t ci = choice_of[kind][index];
    if (ci == NO) return;
    Choice *ch = &choices[ci];
    const Conf *c = after ? &cur : &before;
    if (wear == nullptr) {
        if (!after) bit_set(ch->listed, (uint32_t)(outfit - c->sections));
        return;
    }
    if (curate_is_attic(outfit->arg[0])) return;
    bit_set(after ? ch->after : ch->reach, (uint32_t)(wear - c->sections));
}

static void evaluate(Choice *ch)
{
    bool listed = bits_any(ch->listed);
    bool worn = bits_any(ch->reach);
    bool user = false;
    bool mine = false;   // a personal wear of this project reaches it
    bool other = false;  // some other wear does
    for (uint32_t s = 0; s < before.nsections; s++) {
        if (!bit_get(ch->reach, s)) continue;
        const Section *w = &before.sections[s];
        if (strcmp(w->arg[0], "user") == 0) user = true;
        else if (ch->c.act == CHOICE_PERSONAL && strcmp(w->arg[0], "personal") == 0 && strcmp(w->arg[1], ch->c.project) == 0) mine = true;
        else other = true;
    }
    if (ch->c.act == CHOICE_KEEP) ch->effective = !worn;
    else if (ch->c.act == CHOICE_RETIRE) ch->effective = !listed || worn;
    else ch->effective = user || other || !mine;
}

// ---- the choices file ---------------------------------------------------------------------------------------

// 0, 1 (errno set), or 2 for a file that is over LIMIT bytes.
static int read_file(const char *path, char *buf, size_t limit, size_t *len)
{
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return 1;
    size_t n = 0;
    for (;;) {
        ssize_t r = sys_read(fd, buf + n, limit + 1 - n);
        if (r < 0 && errno == EINTR) continue;
        if (r < 0) {
            int err = errno;
            (void)sys_close(fd);
            errno = err;
            return 1;
        }
        if (r == 0) break;
        n += (size_t)r;
        if (n > limit) break;
    }
    (void)sys_close(fd);
    *len = n;
    return n > limit ? 2 : 0;
}

// Read and parse the choices file. 0, 1 if it cannot be read, 2 if it is refused (every problem is said).
static int parse_choices(const char *path)
{
    size_t len = 0;
    int rc = read_file(path, file_buf, CHOICES_FILE_MAX, &len);
    if (rc == 1) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", path, strerror(errno));
        return 1;
    }
    if (rc == 2) {
        say(STDERR_FILENO, "%s:0: the file is over %zu bytes\n", path, CHOICES_FILE_MAX);
        return 2;
    }
    unsigned errors = 0;
    bool over = false;
    int ln = 0;
    for (size_t pos = 0; pos < len;) {
        const char *nl = memchr(file_buf + pos, '\n', len - pos);
        size_t end = nl != nullptr ? (size_t)(nl - file_buf) : len;
        const char *line = file_buf + pos;
        size_t n = end - pos;
        pos = end + 1;
        ln++;
        if (ln == 1) {
            if (!curate_choices_header(line, n)) {
                say(STDERR_FILENO, "%s:1: not a suit choices file: the first line must be `# suit choices 1`\n", path);
                errors++;
            }
            continue;
        }
        CurateChoice c;
        char msg[256];
        ChoiceLine kind = curate_choice_parse(line, n, &c, msg, sizeof msg);
        if (kind == CHOICE_NONE) continue;
        if (kind == CHOICE_BAD) {
            say(STDERR_FILENO, "%s:%d: %s\n", path, ln, msg);
            errors++;
            continue;
        }
        if (kind == CHOICE_FOLDER) {
            say(STDERR_FILENO, "%s:%d: warning: %s: skipped\n", path, ln, msg);
            continue;
        }
        if (nchoices == CURATE_ASSETS_MAX) {
            if (!over) say(STDERR_FILENO, "%s:%d: more than %u choices\n", path, ln, CURATE_ASSETS_MAX);
            over = true;
            errors++;
            continue;
        }
        bool dup = false;
        for (uint32_t j = 0; j < nchoices; j++) {
            const CurateChoice *o = &choices[j].c;
            if (o->kind != c.kind || strcmp(o->ward, c.ward) != 0 || strcmp(o->name, c.name) != 0) continue;
            say(STDERR_FILENO, "%s:%d: the %s %s of wardrobe %s is also chosen on line %d\n", path, ln, kind_word[c.kind], c.name, c.ward,
                choices[j].line);
            errors++;
            dup = true;
            break;
        }
        if (dup) continue;
        choices[nchoices] = (Choice){.c = c, .line = ln, .aidx = NO};
        nchoices++;
    }
    if (ln == 0) {
        say(STDERR_FILENO, "%s:1: not a suit choices file: the first line must be `# suit choices 1`\n", path);
        errors++;
    }
    return errors > 0 ? 2 : 0;
}

// Find the asset of each choice; a line whose wardrobe or asset is not there is a warning and is left out.
static uint32_t find_assets(void)
{
    memset(choice_of, 0xff, sizeof choice_of);
    uint32_t skipped = 0;
    for (uint32_t i = 0; i < nchoices; i++) {
        Choice *ch = &choices[i];
        uint32_t w = NO;
        for (uint32_t v = 0; v < wards.n; v++)
            if (strcmp(wards.w[v].name, ch->c.ward) == 0) w = v;
        const NameList *l = &assets.list[ch->c.kind];
        uint32_t a = NO;
        for (uint32_t k = 0; w != NO && k < l->n; k++)
            if (l->ward[k] == w && strcmp(l->name[k], ch->c.name) == 0) a = k;
        if (a == NO) {
            say(STDERR_FILENO, "%s:%d: warning: no %s %s in wardrobe %s: skipped\n", file_arg, ch->line, kind_word[ch->c.kind], ch->c.name,
                ch->c.ward);
            skipped++;
            continue;
        }
        ch->ward = w;
        ch->aidx = a;
        choice_of[ch->c.kind][a] = i;
    }
    return skipped;
}

// ---- what the plan says about the placements and the wears --------------------------------------------------------

typedef struct {
    const char *project;  // nullptr for the User scope
    char sign;
    const char *dest;
    const char *src;
} Diff;

static Plan plan_before;
static Plan plan_after;
static Diff diffs[2 * PLACE_MAX];

static int diff_cmp(const void *pa, const void *pb)
{
    const Diff *a = pa;
    const Diff *b = pb;
    const char *pa_s = a->project != nullptr ? a->project : "";
    const char *pb_s = b->project != nullptr ? b->project : "";
    int c = (a->project != nullptr) - (b->project != nullptr);
    c = c != 0 ? c : strcmp(pa_s, pb_s);
    return c != 0 ? c : strcmp(a->dest, b->dest);
}

static void print_placements(void)
{
    if (commands_resolve(&before, &wards, &assets, &plan_before) != 0 || commands_resolve(&cur, &wards, &assets, &plan_after) != 0) {
        emit("placements: not shown, the config does not place\n");
        return;
    }
    uint32_t nd = 0;
    uint32_t i = 0;
    uint32_t j = 0;
    while (i < plan_before.n || j < plan_after.n) {
        int c = i == plan_before.n ? 1 : j == plan_after.n ? -1 : strcmp(plan_before.p[i].dest, plan_after.p[j].dest);
        const Placement *b = &plan_before.p[i];
        const Placement *a = &plan_after.p[j];
        if (c < 0) diffs[nd++] = (Diff){b->project, '-', b->dest, nullptr};
        else if (c > 0) diffs[nd++] = (Diff){a->project, '+', a->dest, a->src};
        else if (strcmp(a->src, b->src) != 0) diffs[nd++] = (Diff){a->project, '+', a->dest, a->src};
        if (c <= 0) i++;
        if (c >= 0) j++;
    }
    if (nd == 0) {
        emit("placements: none change\n");
        return;
    }
    qsort(diffs, nd, sizeof diffs[0], diff_cmp);
    emit("placements:\n");
    for (uint32_t d = 0; d < nd; d++) {
        const Diff *x = &diffs[d];
        bool first = d == 0 || (diffs[d - 1].project == nullptr) != (x->project == nullptr) ||
            (x->project != nullptr && strcmp(diffs[d - 1].project, x->project) != 0);
        if (first && x->project == nullptr) emit("  user\n");
        if (first && x->project != nullptr) emit("  personal %s\n", x->project);
        if (x->sign == '+') emit("    + link %s -> %s\n", x->dest, x->src);
        else emit("    - link %s\n", x->dest);
    }
}

static char wkey[WKEY_MAX][CONF_LINE_MAX + 16];
static uint32_t nwkey;
static uint32_t key_before[CONF_SECTION_MAX];
static uint32_t key_after[CONF_SECTION_MAX];
static uint32_t key_gone[WKEY_MAX];
static uint32_t key_came[WKEY_MAX];

static uint32_t key_of(const Section *wear)
{
    char t[CONF_LINE_MAX + 16];
    wear_text(wear, t, sizeof t);
    for (uint32_t k = 0; k < nwkey; k++)
        if (strcmp(wkey[k], t) == 0) return k;
    ensure(nwkey < WKEY_MAX);  // at most 256 wears in each set
    memcpy(wkey[nwkey], t, strlen(t) + 1);
    return nwkey++;
}

// For each wear that reaches more or fewer of the chosen assets than before.
static void print_wears(void)
{
    for (uint32_t s = 0; s < before.nsections; s++)
        if (before.sections[s].kind == KIND_WEAR) key_before[s] = key_of(&before.sections[s]);
    for (uint32_t s = 0; s < cur.nsections; s++)
        if (cur.sections[s].kind == KIND_WEAR) key_after[s] = key_of(&cur.sections[s]);
    for (uint32_t ci = 0; ci < nchoices; ci++) {
        const Choice *ch = &choices[ci];
        if (!ch->effective) continue;
        Bits kb = {};
        Bits ka = {};
        for (uint32_t s = 0; s < before.nsections; s++)
            if (bit_get(ch->reach, s)) bit_set(kb, key_before[s]);
        for (uint32_t s = 0; s < cur.nsections; s++)
            if (bit_get(ch->after, s)) bit_set(ka, key_after[s]);
        for (uint32_t k = 0; k < nwkey; k++) {
            if (bit_get(kb, k) && !bit_get(ka, k)) key_gone[k]++;
            if (bit_get(ka, k) && !bit_get(kb, k)) key_came[k]++;
        }
    }
    bool any = false;
    for (uint32_t k = 0; k < nwkey; k++) {
        if (key_gone[k] == 0 && key_came[k] == 0) continue;
        if (!any) emit("wears:\n");
        any = true;
        emit("  wear %s: %u leave, %u arrive\n", wkey[k], key_gone[k], key_came[k]);
    }
    if (!any) emit("wears: none change\n");
}

static void print_expansions(void)
{
    for (uint32_t b = 0; b < before.nsections; b++) {
        for (int k = 0; k < 3; k++) {
            if (!expanded[b][k]) continue;
            const Section *s = &before.sections[b];
            const Entry *was = find_entry(&before, s, kind_key[k]);
            uint32_t ci = find_outfit(&cur, s->arg[0], strlen(s->arg[0]));
            const Entry *now = find_entry(&cur, &cur.sections[ci], kind_key[k]);
            unsigned names = 0;
            const char *v = now != nullptr ? now->val : "";
            const char *w;
            size_t len;
            while (conf_list_next(&v, &w, &len)) names++;
            emit("outfit %s: `%s = %s` becomes an explicit list of %u names\n", s->arg[0], kind_key[k], was->val, names);
        }
    }
}

// ---- the check-in comment ------------------------------------------------------------------------------------

static void comment_of(uint32_t w, char *comment, size_t cap)
{
    static const char *const act_word[] = {"kept", "limited", "retired"};
    static const ChoiceAct order[] = {CHOICE_KEEP, CHOICE_PERSONAL, CHOICE_RETIRE};
    size_t at = (size_t)snprintf(comment, cap, "Curate:");
    const char *sep = " ";
    for (int i = 0; i < 3; i++) {
        if (counts[order[i]][w] == 0) continue;
        at += (size_t)snprintf(comment + at, cap - at, "%s%u %s", sep, counts[order[i]][w], act_word[i]);
        sep = ", ";
    }
    ensure(at < cap);
}

static bool differs(uint32_t w)
{
    return text_len[w] != orig_len[w] || memcmp(text[w], orig[w], text_len[w]) != 0;
}

// ---- making the changes ---------------------------------------------------------------------------------------------

static void say_progress(const bool *done, const bool *todo)
{
    char have[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
    char left[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
    for (uint32_t w = 0; w < wards.n; w++) {
        if (!todo[w]) continue;
        char *to = done[w] ? have : left;
        size_t at = strlen(to);
        snprintf(to + at, sizeof have - at, "%s%s", at > 0 ? ", " : "", wards.w[w].name);
    }
    // The wardrobe that failed is one of those not changed, so that list is never empty.
    say(STDERR_FILENO, "suit: wardrobes changed: %s; not changed: %s\n", have[0] != '\0' ? have : "none", left);
}

// The order to check the changed wardrobes in: a wardrobe that made an outfit before any that names it in a wear, and in
// byte order of name among the rest. False after a message if each of some wardrobes needs another first.
static bool order_wards(const bool *todo, uint32_t *order, uint32_t count)
{
    bool pending[WARDROBE_MAX];
    memcpy(pending, todo, sizeof pending);
    for (uint32_t n = 0; n < count; n++) {
        uint32_t pick = NO;
        for (uint32_t w = 0; w < wards.n && pick == NO; w++) {
            if (!pending[w]) continue;
            bool ready = true;
            for (uint32_t u = 0; u < wards.n; u++) ready &= !(pending[u] && dep[u][w]);
            if (ready) pick = w;
        }
        if (pick == NO) {
            char left[WARDROBE_MAX * (CONF_NAME_MAX + 2) + 8] = "";
            for (uint32_t w = 0; w < wards.n; w++) {
                if (!pending[w]) continue;
                size_t at = strlen(left);
                snprintf(left + at, sizeof left - at, "%s%s", at > 0 ? ", " : "", wards.w[w].name);
            }
            say(STDERR_FILENO,
                "suit: the wardrobes %s each name an outfit that another of them makes, so none can be checked in first; apply the choices of one wardrobe, then the other's\n",
                left);
            fail_rc = 2;
            return false;
        }
        pending[pick] = false;
        order[n] = pick;
    }
    return true;
}

// Write each changed wardrobe's suit.conf and check it in, in ORDER.
static int write_wardrobes(const bool *todo, const uint32_t *order, uint32_t count)
{
    for (uint32_t k = 0; k < count; k++) {
        uint32_t w = order[k];
        int rc = store_check_journal(wards.w[w].name);
        if (rc != 0) return rc;
        unsigned n = 0;
        rc = store_changes(wards.w[w].name, &n);
        if (rc != 0) return rc;
        if (n > 0) {
            say(STDERR_FILENO, "suit: wardrobe %s has local changes: run `suit commit %s -m TEXT` or `suit tend %s` first\n", wards.w[w].name,
                wards.w[w].name, wards.w[w].name);
            return EXIT_LOCAL_CHANGES;
        }
    }
    bool done[WARDROBE_MAX] = {};
    for (uint32_t k = 0; k < count; k++) {
        uint32_t w = order[k];
        int err = sys_write_atomic(wards.w[w].conf, text[w], text_len[w]);
        if (err != 0) {
            say(STDERR_FILENO, "suit: cannot write %s: %s\n", wards.w[w].conf, strerror(err));
            say_progress(done, todo);
            return 1;
        }
        char comment[128];
        comment_of(w, comment, sizeof comment);
        int rc = store_commit(wards.w[w].name, comment, false);
        if (rc != 0) {
            // Put the file back, so that the working copy is as it was and not left with an edit nobody checked in.
            err = sys_write_atomic(wards.w[w].conf, orig[w], orig_len[w]);
            if (err != 0)
                say(STDERR_FILENO, "suit: cannot put %s back as it was: %s\n", wards.w[w].conf, strerror(err));
            say(STDERR_FILENO, "suit: the check-in of wardrobe %s failed (exit %d)\n", wards.w[w].name, rc);
            say_progress(done, todo);
            return 1;
        }
        done[w] = true;
        say(STDOUT_FILENO, "wardrobe %s: %s\n", wards.w[w].name, comment);
    }
    return 0;
}

// ---- the command ----------------------------------------------------------------------------------------------------------

static int usage_error(void)
{
    say(STDERR_FILENO, "usage: suit curate apply FILE [--yes]\n");
    return 2;
}

// Load the wardrobes, their configs and the assets. 0, or the exit status after a message.
static int load_all(const char *suit_home)
{
    int rc = wardrobes_find(&wards, suit_home);
    if (rc != 0) return rc;
    for (uint32_t w = 0; w < wards.n; w++) {
        rc = read_file(wards.w[w].conf, orig[w], CONF_FILE_MAX, &orig_len[w]);
        if (rc == 1) {
            say(STDERR_FILENO, "suit: cannot read %s: %s\n", wards.w[w].conf, strerror(errno));
            return 1;
        }
        if (rc == 2) {
            say(STDERR_FILENO, "%s:0: file is over %zu bytes\n", wards.w[w].conf, CONF_FILE_MAX);
            return 2;
        }
        memcpy(text[w], orig[w], orig_len[w]);
        text_len[w] = orig_len[w];
    }
    if (!rebuild(&before, orig, orig_len)) return 2;
    [[maybe_unused]] bool same = rebuild(&cur, text, text_len);  // the same text again
    ensure(same);
    return assets_load(&wards, &assets);
}

// Whether a wear reaches the outfit attic: the first, as text, or nullptr.
static const char *attic_worn(char *shown, size_t cap)
{
    for (uint32_t s = 0; s < before.nsections; s++) {
        if (before.sections[s].kind != KIND_WEAR) continue;
        Bits seen = {};
        seed_wear(&before, s, seen);
        spread(&before, seen);
        for (uint32_t o = 0; o < before.nsections; o++) {
            if (before.sections[o].kind != KIND_OUTFIT || !curate_is_attic(before.sections[o].arg[0]) || !bit_get(seen, o)) continue;
            wear_text(&before.sections[s], shown, cap);
            return shown;
        }
    }
    return nullptr;
}

static int apply(bool yes)
{
    char suit_home[COMMANDS_PATH_CAP];
    char lock_path[COMMANDS_PATH_CAP];
    int rc = commands_home(suit_home, lock_path);
    if (rc != 0) return rc;
    if (yes) {
        rc = place_lock(lock_path);
        if (rc != 0) return rc;
    }
    rc = parse_choices(file_arg);
    rc = rc != 0 ? rc : load_all(suit_home);
    if (rc != 0) {
        if (yes) place_unlock(lock_path);
        return rc;
    }
    uint32_t skipped = find_assets();
    bool phase = false;
    resolve_reach(&before, &assets, on_reach, &phase);
    for (uint32_t s = 0; s < before.nsections; s++)
        if (before.sections[s].kind == KIND_WEAR && strcmp(before.sections[s].arg[0], "user") == 0) seed_wear(&before, s, user_outfits);
    spread(&before, user_outfits);
    uint32_t effective = 0;
    uint32_t retiring = 0;
    for (uint32_t i = 0; i < nchoices; i++) {
        if (choices[i].aidx == NO) continue;
        evaluate(&choices[i]);
        if (choices[i].effective) effective++;
        if (choices[i].effective && choices[i].c.act == CHOICE_RETIRE) retiring++;
    }
    char shown[CONF_LINE_MAX + 16];
    const char *worn = retiring > 0 ? attic_worn(shown, sizeof shown) : nullptr;
    if (worn != nullptr) {
        say(STDERR_FILENO, "suit: an attic outfit is worn by [wear %s], so nothing can be retired into it; take it out of that wear first\n",
            worn);
        if (yes) place_unlock(lock_path);
        return 2;
    }
    out_init(&out, STDOUT_FILENO);
    emit("plan: %u choices, %u change something, %u already true, %u skipped\n", nchoices, effective,
        nchoices - effective - skipped, skipped);
    bool ok = true;
    for (uint32_t i = 0; ok && i < nchoices; i++)
        if (choices[i].aidx != NO && choices[i].effective) ok = run_choice(&choices[i]);
    bool todo[WARDROBE_MAX] = {};
    uint32_t nchanged = 0;
    if (ok) {
        for (uint32_t w = 0; w < wards.n; w++) {
            todo[w] = differs(w);
            if (todo[w]) nchanged++;
        }
        if (nchanged == 0) emit("nothing to change\n");
    }
    uint32_t order[WARDROBE_MAX];
    if (ok && nchanged > 0) ok = order_wards(todo, order, nchanged);
    if (ok && nchanged > 0) {
        phase = true;
        resolve_reach(&cur, &assets, on_reach, &phase);
        print_expansions();
        print_placements();
        print_wears();
        emit("check-ins, in this order:\n");
        for (uint32_t k = 0; k < nchanged; k++) {
            uint32_t w = order[k];
            char comment[128];
            comment_of(w, comment, sizeof comment);
            emit("  %s: %s\n", wards.w[w].name, comment);
        }
    }
    bool flushed = out_finish(&out);
    if (!ok) {
        if (yes) place_unlock(lock_path);
        return fail_rc;
    }
    if (!flushed) {
        say(STDERR_FILENO, "suit: cannot write the plan: %s\n", strerror(errno));
        rc = 1;
    } else if (!yes) {
        rc = 0;
        if (nchanged > 0) say(STDOUT_FILENO, "nothing was changed; run again with --yes to make these changes\n");
    } else {
        rc = nchanged > 0 ? write_wardrobes(todo, order, nchanged) : 0;
        if (rc == 0 && nchanged > 0)
            say(STDOUT_FILENO, "nothing was applied to your folders: the next `suit run` places what the new config says\n");
    }
    if (yes) place_unlock(lock_path);
    return rc;
}

int cmd_curate_apply(int argc, char **argv)
{
    bool yes = false;
    file_arg = nullptr;
    for (int i = 0; i < argc; i++) {
        if (strcmp(argv[i], "--yes") == 0 && !yes) yes = true;
        else if (file_arg == nullptr && argv[i][0] != '-') file_arg = argv[i];
        else return usage_error();
    }
    if (file_arg == nullptr) return usage_error();
    return apply(yes);
}