Skip to content
suit Artifact [f5f682fe96]
Login

Artifact [f5f682fe96]

Artifact f5f682fe96c74859216a711d9c78516bdfdc15e84f5ce8ec8940710111e1cd26:


// Unit tests for the config parser's API. The shell tests in run.sh cover the
// command line; these cover the parser directly, including the limits.

// nftw() and its flags are declared by glibc only when X/Open is asked for.
// macOS declares them by default, and defining this there would hide BSD
// names the tests use.
#if defined(__linux__) && !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 700
#endif

#include "anchors.h"
#include "conf.h"
#include "curate.h"
#include "exclude.h"
#include "platform.h"
#include "install.h"
#include "join.h"
#include "ledger.h"
#include "lint.h"
#include "need.h"
#include "place.h"
#include "project.h"
#include "resolve.h"
#include "stamp.h"
#include "store_fs.h"
#include "tally.h"
#include "tls.h"
#include "usage.h"

#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static Conf conf;
static int checks;
static int failures;

#define CHECK(cond)                                                          \
    do {                                                                     \
        checks++;                                                            \
        if (!(cond)) {                                                       \
            failures++;                                                      \
            printf("FAIL unit %s:%d: %s\n", __FILE__, __LINE__, #cond);      \
        }                                                                    \
    } while (0)

static bool parse(const char *text, ConfError *e)
{
    return conf_parse(&conf, text, strlen(text), e);
}

static void expect_error(const char *text, int line, const char *part)
{
    ConfError e;
    bool ok = parse(text, &e);
    CHECK(!ok);
    CHECK(e.line == line);
    CHECK(strstr(e.msg, part) != nullptr);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  wanted line %d with '%s', got line %d '%s'\n", line, part, e.line,
            ok ? "(parsed)" : e.msg);
}

static void test_valid(void)
{
    ConfError e;
    CHECK(parse("", &e));
    CHECK(conf.nsections == 0);
    CHECK(parse("# only a comment\n\n   \n", &e));
    CHECK(parse("[harness a]", &e));  // no trailing newline
    CHECK(conf.nsections == 1);
    CHECK(parse("[harness a]\r\nrecord = x\r\n", &e));
    CHECK(strcmp(conf.entries[0].val, "x") == 0);
}

static void test_comments(void)
{
    ConfError e;
    CHECK(parse("[harness a]\nrecord = x # note\nevent E = a#b\n", &e));
    CHECK(strcmp(conf.entries[0].val, "x") == 0);
    CHECK(strcmp(conf.entries[1].val, "a#b") == 0);
    CHECK(parse("  # indented\n[harness a] # header\n", &e));
}

static void test_lists(void)
{
    ConfError e;
    CHECK(parse("[outfit a]\nskills =   x\t y   z*  \n", &e));
    const char *cur = conf.entries[0].val;
    const char *w;
    size_t n;
    CHECK(conf_list_next(&cur, &w, &n) && n == 1 && w[0] == 'x');
    CHECK(conf_list_next(&cur, &w, &n) && n == 1 && w[0] == 'y');
    CHECK(conf_list_next(&cur, &w, &n) && n == 2 && memcmp(w, "z*", 2) == 0);
    CHECK(!conf_list_next(&cur, &w, &n));
}

static void test_errors(void)
{
    expect_error("[bogus x]\n", 1, "unknown section kind");
    expect_error("[harness a]\nnope = 1\n", 2, "unknown key");
    expect_error("[harness a]\n[harness a]\n", 2, "duplicate section");
    expect_error("[outfit a]\nonly = h\nonly = h\n", 3, "duplicate key");
    expect_error("record = x\n", 1, "before any section");
    expect_error("[harness a\n", 1, "malformed");
    expect_error("[outfit a]\ninclude = b\n[outfit b]\ninclude = a\n", 2 + 2,
        "include cycle: a -> b -> a");
    expect_error("[outfit a]\ninclude = a\n", 2, "include cycle: a -> a");
    expect_error("[outfit a]\ninclude = zz\n", 2, "unknown outfit");
    expect_error("[wear user]\noutfits = zz\n", 2, "unknown outfit");
    expect_error("[outfit a]\nonly = zz\n", 2, "unknown harness");
}

static void test_more_errors(void)
{
    expect_error("[harness bad/name]\n", 1, "invalid harness name");
    expect_error("[need h bad/name]\n", 1, "invalid need");
    expect_error("[harness a b c d e]\n", 1, "too many words");
    expect_error("[wear user machine=bad/name]\n", 1, "invalid machine name");
    expect_error("[wear user machine=]\n", 1, "invalid machine name");
    expect_error("[wear shared bad$target]\n", 1, "invalid target");
    expect_error("[wear]\n", 1, "needs a SCOPE");
    expect_error("[wear shared a b]\n", 1, "too many arguments");
    expect_error("[harness a]\nx\n", 2, "expected KEY = VALUE");
    expect_error("[harness a]\nevent E = a b\n", 2, "takes one word");
    expect_error("[outfit o]\nslotx = a\n", 2, "unknown key 'slotx'");
    expect_error("[outfit o]\nslot = a\n", 2, "unknown key 'slot'");
    expect_error("[outfit o]\nslot a$b = f\n", 2, "invalid key");
    expect_error("[outfit o]\nslot a b = f\n", 2, "invalid key");
    expect_error("[outfit o]\nfile ~/a b = f\n", 2, "invalid key");
    expect_error("[harness a]\nbogus.user = x\n", 2, "unknown key 'bogus.user'");
    expect_error("[harness a]\nskills.galaxy = x\n", 2, "unknown key");
    expect_error("[outfit o]\nskills = x yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy/z\n", 2,
        "invalid name 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'");
    expect_error("[outfit abc]\n[outfit o]\ninclude = ab\n", 3, "include of unknown outfit 'ab'");
    expect_error("[outfit a]\ninclude = b\n[outfit b]\ninclude = c\n[outfit c]\ninclude = b\n", 6,
        "include cycle: b -> c -> b");
    expect_error("[wear user]\npublish = yes\n", 2, "publish is allowed only on wear shared");
}

static void test_valid_names(void)
{
    ConfError e;
    CHECK(parse("[harness a_b]\nevent Some_Event.v2-x/y = z\n[outfit Z.9]\nskills = A_b-c.d* x\n", &e));
    CHECK(parse("[wear shared g.com/o/n_x-y:z@h~w]\noutfits = \n", &e) == false);
    CHECK(parse("[wear shared g.com/o/n_x-y:z@h~w]\n", &e));
    CHECK(parse("[outfit o]\nfile ~/a/b = x\nslot hook/Stop = y\n", &e));
}

static void test_upstream_keys(void)
{
    ConfError e;
    CHECK(parse("[upstream u]\ninto = skills\n", &e));
    CHECK(conf.nentries == 1 && strcmp(conf.entries[0].key, "into") == 0 && strcmp(conf.entries[0].val, "skills") == 0);
    CHECK(parse("[upstream u]\ninto = vendor/deep.er/x_y-z\n", &e));
    CHECK(parse("[upstream u]\nurl = x\npin = abc\ntrust = auto\npath = a b/c\n", &e));
    CHECK(conf.nentries == 4);  // the defaults are not entries: `into` is absent
    expect_error("[upstream u]\ninto = ../x\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = x/..\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = /x\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = x/\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = a//b\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = ./a\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = a/.b\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = a b\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = a:b\n", 2, "'into' must be a relative path of names");
    expect_error("[upstream u]\ninto = a\ninto = b\n", 3, "duplicate");
    char text[1024];
    char part[129];
    memset(part, 'a', 128);
    part[128] = '\0';
    snprintf(text, sizeof text, "[upstream u]\ninto = %s/%.127s\n", part, part);
    CHECK(parse(text, &e));  // 256 bytes
    snprintf(text, sizeof text, "[upstream u]\ninto = %s/%s\n", part, part);
    expect_error(text, 2, "at most 256 bytes");
    snprintf(text, sizeof text, "[upstream u]\ninto = %s%s\n", part, part);
    expect_error(text, 2, "'into' must be a relative path of names");  // a part over 128 bytes
}

static void test_long_cycle_message(void)
{
    char names[3][121];
    for (int i = 0; i < 3; i++) {
        memset(names[i], 'a' + i, 120);
        names[i][120] = '\0';
    }
    char text[2048];
    int n = snprintf(text, sizeof text,
        "[outfit %s]\ninclude = %s\n[outfit %s]\ninclude = %s\n[outfit %s]\ninclude = %s\n",
        names[0], names[1], names[1], names[2], names[2], names[0]);
    ConfError e;
    CHECK(!conf_parse(&conf, text, (size_t)n, &e));
    CHECK(e.line == 6);
    CHECK(strlen(e.msg) == sizeof e.msg - 1);
    CHECK(strncmp(e.msg, "include cycle: aaaa", 19) == 0);
}

static void test_header_names_and_spacing(void)
{
    ConfError e;
    char text[256];
    char name[130];
    memset(name, 'n', 129);
    name[129] = '\0';
    snprintf(text, sizeof text, "[harness %s]\n", name);
    CHECK(!conf_parse(&conf, text, strlen(text), &e) && e.line == 1);
    name[128] = '\0';
    snprintf(text, sizeof text, "[harness %s]\n", name);
    CHECK(parse(text, &e));
    expect_error("[need bad/h n]\n", 1, "invalid need");
    CHECK(parse("[  harness   a  ]\n", &e));
    CHECK(conf.nsections == 1 && strcmp(conf.sections[0].arg[0], "a") == 0);
}

static void test_wear_headers(void)
{
    ConfError e;
    CHECK(parse("[wear enterprise]\n[wear user]\n[wear user machine=m]\n", &e));
    CHECK(parse("[wear shared g/o/n]\n[wear personal g/o/n machine=m]\n", &e));
    expect_error("[wear shared]\n", 1, "needs a TARGET");
    expect_error("[wear personal]\n", 1, "needs a TARGET");
    expect_error("[wear enterprise g/o/n]\n", 1, "takes no TARGET");
    expect_error("[wear user g/o/n]\n", 1, "takes no TARGET");
    expect_error("[wear enterprise machine=m]\n", 1, "machine=");
    expect_error("[wear shared g/o/n machine=m]\n", 1, "machine=");
    expect_error("[wear galaxy]\n", 1, "unknown scope");
    expect_error("[wear user]\npublish = yes\n", 2, "publish");
}

static char *repeat_lines(const char *pre, const char *post, int n, size_t *len)
{
    char *s = malloc((size_t)n * 64 + 1);
    size_t off = 0;
    for (int i = 1; i <= n; i++)
        off += (size_t)snprintf(s + off, 64, "%s%d%s", pre, i, post);
    *len = off;
    return s;
}

static bool parse_n(const char *pre, const char *post, int n, ConfError *e)
{
    size_t len;
    char *s = repeat_lines(pre, post, n, &len);
    bool ok = conf_parse(&conf, s, len, e);
    free(s);
    return ok;
}

static void test_limits(void)
{
    ConfError e;
    CHECK(parse_n("[harness h", "]\n", 64, &e));
    CHECK(!parse_n("[harness h", "]\n", 65, &e) && e.line == 65);
    CHECK(parse_n("[outfit o", "]\n", 512, &e));
    CHECK(!parse_n("[outfit o", "]\n", 513, &e) && e.line == 513);
    CHECK(parse_n("[wear personal g/o/n", "]\n", 256, &e));
    CHECK(!parse_n("[wear personal g/o/n", "]\n", 257, &e) && e.line == 257);
    CHECK(parse_n("[upstream u", "]\n", 128, &e));
    CHECK(!parse_n("[upstream u", "]\n", 129, &e) && e.line == 129);

    // 256 needs, then 257. Needs name a harness, so lead with one.
    size_t len;
    char *s = repeat_lines("[need h n", "]\n", 257, &len);
    char *text = malloc(len + 32);
    int head = snprintf(text, 32, "[harness h]\n");
    memcpy(text + head, s, len);
    CHECK(!conf_parse(&conf, text, (size_t)head + len, &e) && e.line == 258);
    CHECK(strstr(e.msg, "too many need") != nullptr);
    free(s);
    free(text);

    // 8192 entries fit, the 8193rd does not.
    char *big = malloc(8200 * 16);
    size_t off = (size_t)snprintf(big, 32, "[harness h]\n");
    for (int i = 0; i < 8192; i++) off += (size_t)snprintf(big + off, 16, "record = r\n");
    CHECK(conf_parse(&conf, big, off, &e));
    off += (size_t)snprintf(big + off, 16, "record = r\n");
    CHECK(!conf_parse(&conf, big, off, &e) && e.line == 8194);
    free(big);
}

static void test_line_and_file(void)
{
    ConfError e;
    static char line[CONF_FILE_MAX + 64];

    memset(line, '#', CONF_LINE_MAX);
    line[CONF_LINE_MAX] = '\n';
    CHECK(conf_parse(&conf, line, CONF_LINE_MAX + 1, &e));
    memset(line, '#', CONF_LINE_MAX + 1);
    line[CONF_LINE_MAX + 1] = '\n';
    CHECK(!conf_parse(&conf, line, CONF_LINE_MAX + 2, &e) && e.line == 1);

    memset(line, '\n', CONF_FILE_MAX);
    CHECK(conf_parse(&conf, line, CONF_FILE_MAX, &e));
    CHECK(!conf_parse(&conf, line, CONF_FILE_MAX + 1, &e) && e.line == 0);

    CHECK(!conf_parse(&conf, "[harness a]\nrecord = x\0y\n", 24, &e) && e.line == 2);
}

static void test_dump_is_stable(void)
{
    ConfError e;
    CHECK(parse("[outfit b]\n[outfit a]\nskills = z y\n", &e));
    char path[] = "/tmp/suit-unit.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    CHECK(conf_dump(&conf, fd));
    char got[256] = {};
    CHECK(pread(fd, got, sizeof got - 1, 0) > 0);
    CHECK(strcmp(got, "outfit a\noutfit a skills = z y\noutfit b\n") == 0);

    // Entries equal in key and value keep their file order.
    CHECK(ftruncate(fd, 0) == 0 && lseek(fd, 0, SEEK_SET) == 0);
    CHECK(parse("[harness h]\nrecord = x\nrecord = x\nrecord = a\n", &e));
    CHECK(conf_dump(&conf, fd));
    memset(got, 0, sizeof got);
    CHECK(pread(fd, got, sizeof got - 1, 0) > 0);
    CHECK(strcmp(got, "harness h\nharness h record = a\nharness h record = x\nharness h record = x\n") == 0);
    close(fd);
    unlink(path);
}

// ---- platform -------------------------------------------------------------

// Run FN in a child with SUIT_FAULT=SPEC; returns the child's exit status.
static int in_child(const char *spec, int (*fn)(void))
{
    fflush(nullptr);
    pid_t pid = fork();
    if (pid == 0) {
        setenv("SUIT_FAULT", spec, 1);
        fault_reset();
        int rc = fn();
        fflush(nullptr);
        exit(rc);
    }
    int status = 0;
    waitpid(pid, &status, 0);
    return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

// Each of these makes one wrapper call and returns 0 if it failed with EIO.
static int fails_eio(bool failed) { return failed && errno == EIO ? 0 : 1; }
static int w_open(void) { return fails_eio(sys_open("/dev/null", O_RDONLY, 0) < 0); }
static int w_read(void) { char b[1]; return fails_eio(sys_read(0, b, 1) < 0); }
static int w_write(void) { return fails_eio(sys_write(1, "", 1) < 0); }
static int w_close(void) { return fails_eio(sys_close(-1) < 0 && errno == EIO); }
static int w_fsync(void) { return fails_eio(sys_fsync(1) < 0); }
static int w_fchmod(void) { return fails_eio(sys_fchmod(-1, 0600) < 0); }
static int w_stat(void) { struct stat st; return fails_eio(sys_stat("/", &st) < 0); }
static int w_fstatat(void) { struct stat st; return fails_eio(sys_fstatat(AT_FDCWD, "/", &st) < 0); }
static int w_rename(void) { return fails_eio(sys_rename("/nonexistent-a", "/nonexistent-b") < 0); }
static int w_mkdir(void) { return fails_eio(sys_mkdir("/", 0755) < 0); }
static int w_unlink(void) { return fails_eio(sys_unlink("/nonexistent-a") < 0); }
static int w_getenv(void) { return sys_getenv("PATH") == nullptr ? 0 : 1; }
static int w_lstat(void) { struct stat st; return fails_eio(sys_lstat("/", &st) < 0); }
static int w_readlink(void) { char b[8]; return fails_eio(sys_readlink("/", b, sizeof b) < 0); }
static int w_symlink(void) { return fails_eio(sys_symlink("x", "/nonexistent-a/y") < 0); }
static int w_rmdir(void) { return fails_eio(sys_rmdir("/nonexistent-a") < 0); }
static int w_getcwd(void) { char b[4096]; return sys_getcwd(b, sizeof b) == nullptr && errno == EIO ? 0 : 1; }
static int w_kill(void) { return fails_eio(sys_kill0(getpid()) < 0); }
static int none_cb(void *state, const char *name) { (void)state; (void)name; return 0; }
static int w_listdir(void) { return fails_eio(sys_listdir("/", none_cb, nullptr) < 0); }
static int w_spawn(void) { pid_t p; char *argv[] = {(char *)"true", nullptr}; return sys_spawn(&p, "/usr/bin/true", argv) == EIO ? 0 : 1; }
static int w_wait4(void) { int st; return fails_eio(sys_wait4(-1, &st, nullptr) < 0); }
static int w_clock(void) { uint64_t ns; return sys_now_ns(&ns) ? 1 : 0; }
static int w_wall(void) { int64_t s; return sys_wall_sec(&s) ? 1 : 0; }
static int w_self(void) { char b[4096]; return platform_self_path(b, sizeof b) ? 1 : 0; }

static void test_wrapper_faults(void)
{
    static const struct {
        const char *spec;
        int (*fn)(void);
    } cases[] = {
        {"open:1", w_open}, {"read:1", w_read}, {"write:1", w_write},
        {"close:1:EIO", w_close}, {"fsync:1", w_fsync}, {"fchmod:1", w_fchmod}, {"stat:1", w_stat},
        {"fstatat:1", w_fstatat}, {"rename:1", w_rename}, {"mkdir:1", w_mkdir},
        {"unlink:1", w_unlink}, {"getenv:1", w_getenv}, {"spawn:1", w_spawn},
        {"wait4:1", w_wait4}, {"clock_gettime:1", w_clock}, {"wall:1", w_wall}, {"self_path:1", w_self},
        {"lstat:1", w_lstat}, {"readlink:1", w_readlink}, {"symlink:1", w_symlink},
        {"rmdir:1", w_rmdir}, {"kill:1", w_kill}, {"listdir:1", w_listdir}, {"getcwd:1", w_getcwd},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        CHECK(in_child(cases[i].spec, cases[i].fn) == 0);
        if (in_child(cases[i].spec, cases[i].fn) != 0) printf("  case %s\n", cases[i].spec);
    }
}

static int second_call(void)  // the fault fires on call 2 only
{
    struct stat st;
    return sys_stat("/", &st) == 0 && sys_stat("/", &st) < 0 && sys_stat("/", &st) == 0 ? 0 : 1;
}

static void test_fault_counts_calls(void)
{
    CHECK(in_child("stat:2", second_call) == 0);
}

static void test_self_path(void)
{
    char big[4096];
    char tiny[2];
    CHECK(platform_self_path(big, sizeof big));
    CHECK(big[0] != '\0');
    CHECK(!platform_self_path(tiny, sizeof tiny));
}

static void test_say_and_out(void)
{
    char path[] = "/tmp/suit-unit-out.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    static char text[SAY_MAX * 2];
    memset(text, 'x', sizeof text - 1);
    say(fd, "%s", text);
    struct stat st;
    CHECK(fstat(fd, &st) == 0 && (size_t)st.st_size == SAY_MAX - 1);
    char last = 0;
    CHECK(pread(fd, &last, 1, (off_t)(SAY_MAX - 2)) == 1 && last == '\n');

    // A string bigger than the buffer, then a write error.
    CHECK(ftruncate(fd, 0) == 0 && lseek(fd, 0, SEEK_SET) == 0);
    Out o;
    out_init(&o, fd);
    out_str(&o, text);
    out_str(&o, "tail");
    CHECK(out_finish(&o));
    CHECK(fstat(fd, &st) == 0 && (size_t)st.st_size == sizeof text - 1 + 4);
    close(fd);
    unlink(path);

    out_init(&o, -1);
    out_str(&o, text);
    CHECK(!out_finish(&o) && errno == EBADF);
}

#ifndef SUIT_COVER
static int ensure_false(void)
{
    ensure(1 == 2);
    return 0;
}

static void test_ensure_aborts(void)
{
    fflush(stdout);
    pid_t pid = fork();
    if (pid == 0) {
        int null = open("/dev/null", O_WRONLY);
        if (null < 0 || dup2(null, STDERR_FILENO) < 0) exit(99);
        exit(ensure_false());
    }
    int status = 0;
    waitpid(pid, &status, 0);
    // ensure() must end the process abnormally. Natively that is SIGABRT;
    // a memory-safe runtime may end it with a different signal.
    if (!WIFSIGNALED(status)) {
        fprintf(stderr, "ensure child: exited=%d code=%d\n",
            WIFEXITED(status), WIFEXITED(status) ? WEXITSTATUS(status) : -1);
    }
    CHECK(WIFSIGNALED(status));
#ifndef __PIZLONATOR_WAS_HERE__
    CHECK(WTERMSIG(status) == SIGABRT);
#endif
}
#endif

static void test_stamp_too_large(void)
{
    char dir[] = "/tmp/suit-unit-home.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    setenv("SUIT_HOME", dir, 1);
    enum { N = 70000 };
    static char *paths[N];
    for (int i = 0; i < N; i++) paths[i] = (char *)"/suit-no-such-file-for-the-limit-test";
    CHECK(stamp_write(N, paths) == 1);
    char file[256];
    snprintf(file, sizeof file, "%s/stamp", dir);
    CHECK(access(file, F_OK) != 0);
    unsetenv("SUIT_HOME");
    rmdir(dir);
}

// ---- the store's file writer ------------------------------------------------

static fsl_cx *wcx;
static fsl_ckout_fs wfs;
static char wdir[64];
static char wfile[128];

static void writer_setup(void)
{
    snprintf(wdir, sizeof wdir, "/tmp/suit-unit-w.XXXXXX");
    CHECK(mkdtemp(wdir) != nullptr);
    snprintf(wfile, sizeof wfile, "%s/file", wdir);
    CHECK(fsl_cx_init(&wcx, nullptr) == 0);
    CHECK(store_fs_install(wcx) == 0);
    fsl_cx_ckout_fs_get(wcx, &wfs);
}

static bool has_temp_file(void)
{
    char cmd[256];
    snprintf(cmd, sizeof cmd, "ls %s/.suit-tmp.* >/dev/null 2>&1", wdir);
    return system(cmd) == 0;
}

static int write_new(void)
{
    return wfs.xWrite(wfs.state, wfile, "abc", 3) == 0 ? 0 : 1;
}

// A write that is made to fail fails, and leaves no temporary file and the old bytes.
static int write_fails(void)
{
    int rc = wfs.xWrite(wfs.state, wfile, "new", 3);
    char got[8] = {};
    FILE *f = fopen(wfile, "r");
    size_t n = f != nullptr ? fread(got, 1, sizeof got - 1, f) : 0;
    if (f != nullptr) fclose(f);
    return rc != 0 && !has_temp_file() && n == 3 && strcmp(got, "old") == 0 ? 0 : 1;
}

static void put(const char *path, const char *text, mode_t mode)
{
    FILE *f = fopen(path, "w");
    CHECK(f != nullptr);
    fputs(text, f);
    fclose(f);
    chmod(path, mode);
}

typedef struct {
    int count;
    int ours;
} Seen;

static int collect(void *state, char const *entry)
{
    Seen *seen = state;
    seen->count++;
    if (strncmp(entry, SUIT_TMP_PREFIX, strlen(SUIT_TMP_PREFIX)) == 0) seen->ours++;
    return 0;
}

static void test_writer(void)
{
    writer_setup();
    CHECK(write_new() == 0);
    char got[8] = {};
    FILE *f = fopen(wfile, "r");
    CHECK(f != nullptr && fread(got, 1, 7, f) == 3 && strcmp(got, "abc") == 0);
    fclose(f);
    struct stat st;
    CHECK(stat(wfile, &st) == 0 && (st.st_mode & 0111) == 0);

    // An executable file stays executable when it is replaced.
    put(wfile, "old", 0755);
    CHECK(wfs.xWrite(wfs.state, wfile, "new", 3) == 0);
    CHECK(stat(wfile, &st) == 0 && (st.st_mode & 0100) != 0 && st.st_size == 3);
    CHECK(!has_temp_file());

    // A call that fails leaves the old bytes and no temporary file.
    static const char *const specs[] = {"open:1", "write:1", "fsync:1", "close:1", "rename:1"};
    for (size_t i = 0; i < sizeof specs / sizeof specs[0]; i++) {
        put(wfile, "old", 0644);
        CHECK(in_child(specs[i], write_fails) == 0);
    }
    put(wfile, "old", 0644);
    CHECK(in_child("stat:1", write_new) == 0);  // no stat: treated as not executable
    CHECK(in_child("write:1:short", write_new) == 0);

    // The listing never shows our temporary names.
    put(wfile, "x", 0644);
    char tmp[160];
    snprintf(tmp, sizeof tmp, "%s/" SUIT_TMP_PREFIX "1.1", wdir);
    put(tmp, "x", 0644);
    Seen seen = {0, 0};
    CHECK(wfs.xDirList(wfs.state, wdir, collect, &seen) == 0);
    CHECK(seen.count == 1 && seen.ours == 0);
    unlink(tmp);
    unlink(wfile);
    rmdir(wdir);
    fsl_cx_finalize(wcx);
}

// ---- a rewritten file keeps its permission bits ----------------------------------

static mode_t mode_of(const char *path)
{
    struct stat st;
    CHECK(stat(path, &st) == 0);
    return st.st_mode & 07777;
}

static void test_write_keeps_mode(void)
{
    wcx = nullptr;
    writer_setup();
    static const mode_t modes[] = {0600, 0640, 0664, 0755};
    static const mode_t masks[] = {077, 000};
    mode_t saved = umask(0);
    for (size_t m = 0; m < sizeof modes / sizeof modes[0]; m++)
        for (size_t k = 0; k < sizeof masks / sizeof masks[0]; k++) {
            put(wfile, "old", modes[m]);
            umask(masks[k]);
            CHECK(write_new() == 0);
            CHECK(mode_of(wfile) == modes[m]);
            CHECK(!has_temp_file());
        }
    unlink(wfile);
    umask(077);
    CHECK(write_new() == 0 && mode_of(wfile) == 0600);
    unlink(wfile);
    umask(022);
    CHECK(write_new() == 0 && mode_of(wfile) == 0644);
    umask(saved);

    // A failed fchmod leaves the old bytes and mode and no temporary file.
    put(wfile, "old", 0640);
    CHECK(in_child("fchmod:1", write_fails) == 0);
    CHECK(mode_of(wfile) == 0640);
    unlink(wfile);
    rmdir(wdir);
    fsl_cx_finalize(wcx);
}

// ---- SUIT_FAULT lists and delays ----------------------------------------------

static int stat_twice(void)
{
    struct stat st;
    return sys_stat("/", &st) == 0 && sys_stat("/", &st) == 0 ? 0 : 1;
}

static int parse_dies(void)
{
    struct stat st;
    (void)sys_stat("/", &st);
    return 0;
}

static void test_fault_lists(void)
{
    CHECK(in_child("stat:1:delay", stat_twice) == 0);  // every call from the first
    CHECK(in_child("stat:2:delay", stat_twice) == 0);  // only from the second
    CHECK(in_child("read:1,write:1,stat:9", stat_twice) == 0);  // other names are left alone
    CHECK(in_child("open:1,open:2,open:3,open:4,open:5", parse_dies) == 99);
    char big[300];
    memset(big, 'x', sizeof big - 1);
    big[sizeof big - 1] = '\0';
    CHECK(in_child(big, parse_dies) == 99);
}

// ---- resolve ------------------------------------------------------------------

static Assets assets;
static Plan plan;

static void have(AssetKind kind, const char *name, const char *file)
{
    NameList *l = &assets.list[kind];
    l->name[l->n] = name;
    l->ward[l->n] = 0;
    l->file[l->n++] = file;
}

static void have_reset(void)
{
    for (int k = AK_SKILL; k <= AK_COMMAND; k++) assets.list[k].n = 0;
}

static const char *test_machine = "";
static Projects no_projects;  // static, so empty

// One wardrobe, mine, as placing took only that one.
static Wards one_ward(void)
{
    Wards w = {.n = 1};
    snprintf(w.w[0].name, sizeof w.w[0].name, "mine");
    snprintf(w.w[0].store, sizeof w.w[0].store, "/sh/store/mine");
    snprintf(w.w[0].conf, sizeof w.w[0].conf, "/sh/store/mine/suit.conf");
    return w;
}
static Wards test_wards;

static bool resolve_text(const char *text, ResolveError *e)
{
    ConfError ce;
    CHECK(parse(text, &ce));
    test_wards = one_ward();
    return resolve(&conf, &assets, "/home/u", "/sh", &test_wards, test_machine, &no_projects, &plan, e);
}

// The plan as text: "dest <- src [harness kind]" lines.
static void plan_text(char *out, size_t cap)
{
    out[0] = '\0';
    for (uint32_t i = 0; i < plan.n; i++) {
        size_t len = strlen(out);
        snprintf(out + len, cap - len, "%s <- %s [%s %s]\n", plan.p[i].dest, plan.p[i].src,
            plan.p[i].harness, asset_kind_name(plan.p[i].kind));
    }
}

static void test_glob(void)
{
    CHECK(glob_match("abc", "abc"));
    CHECK(!glob_match("abc", "abd"));
    CHECK(!glob_match("abc", "ab"));
    CHECK(!glob_match("ab", "abc"));
    CHECK(glob_match("*", "anything"));
    CHECK(glob_match("*", ""));
    CHECK(glob_match("vault-*", "vault-query"));
    CHECK(!glob_match("vault-*", "vault"));
    CHECK(glob_match("*-query", "vault-query"));
    CHECK(glob_match("a*c*e", "abcde"));
    CHECK(glob_match("a*b*c", "aXbXbXc"));  // backtracks
    CHECK(!glob_match("a*b*c", "aXbXbX"));
    CHECK(glob_match("a**b", "ab"));
    CHECK(!glob_match("", "x"));
}

static const char *const three =
    "[harness claude]\nskills.user = ~/.claude/skills\nagents.user = ~/.claude/agents\n"
    "commands.user = ~/.claude/commands\ninstructions.user = ~/.claude/CLAUDE.md\n"
    "[harness codex]\nskills.user = /abs/codex/skills\ninstructions.user = ~\n"
    "[outfit a]\nskills = s1 t*\nagents = ag\ncommands = cm\ninstructions = instructions/u.md\n"
    "[outfit b]\ninclude = a\nonly = claude\nskills = s2\nslot hook/Stop = files/h.sh\n"
    "file ~/.claude/x.json = files/x.json\n"
    "[wear user]\noutfits = b\n"
    "[wear user machine=m1]\noutfits = a\n";

// ---- merging the configs of several wardrobes ---------------------------------

static Conf part_a, part_b, combined;
static Wards merge_wards;

static void merge_names(void)
{
    merge_wards.n = 2;
    snprintf(merge_wards.w[0].name, sizeof merge_wards.w[0].name, "a");
    snprintf(merge_wards.w[0].conf, sizeof merge_wards.w[0].conf, "/w/a/suit.conf");
    snprintf(merge_wards.w[1].name, sizeof merge_wards.w[1].name, "b");
    snprintf(merge_wards.w[1].conf, sizeof merge_wards.w[1].conf, "/w/b/suit.conf");
}

// Parse TA and TB each on its own and merge them as wardrobes 0 and 1.
static bool merge_two(const char *ta, const char *tb, ConfError *e)
{
    merge_names();
    CHECK(conf_parse_part(&part_a, ta, strlen(ta), e));
    CHECK(conf_parse_part(&part_b, tb, strlen(tb), e));
    conf_merge_init(&combined);
    return conf_merge(&combined, &part_a, 0, &merge_wards, e) && conf_merge(&combined, &part_b, 1, &merge_wards, e);
}

static void test_merge(void)
{
    ConfError e;
    CHECK(merge_two("[harness h]\nskills.user = ~/s\n[outfit o]\nskills = *\n[wear user]\noutfits = o\n",
        "[outfit p]\ninclude = o\n[wear user machine=m]\noutfits = p\n[need h n]\nprompt = x\ndone = ~/n exists\n", &e));
    CHECK(combined.nsections == 6 && combined.nentries == 7);
    CHECK(combined.kind_count[KIND_OUTFIT] == 2 && combined.kind_count[KIND_WEAR] == 2);
    CHECK(combined.sections[0].ward == 0 && combined.sections[3].ward == 1 && combined.sections[5].ward == 1);
    CHECK(strcmp(combined.sections[3].arg[0], "p") == 0);
    CHECK(strcmp(combined.sections[4].arg[0], "user") == 0 && strcmp(combined.sections[4].arg[2], "m") == 0);
    CHECK(strcmp(combined.entries[combined.sections[3].first].val, "o") == 0);
    CHECK(combined.len == part_a.len + part_b.len);
    CHECK(conf_check(&combined, &e));  // p includes o, which is in the other file
    // Reorder and dump: the strings survived the copy.
    int fd = open("/dev/null", O_WRONLY);
    CHECK(fd >= 0 && conf_dump(&combined, fd));
    close(fd);

    // A name nothing defines is an error in the file that names it.
    CHECK(merge_two("[outfit o]\n", "[outfit p]\ninclude = ghost\n", &e));
    CHECK(!conf_check(&combined, &e) && e.ward == 1 && e.line == 2 && strstr(e.msg, "ghost") != nullptr);
    CHECK(merge_two("[outfit o]\n", "[need x n]\nprompt = x\ndone = ~/n exists\n", &e));
    CHECK(!conf_check(&combined, &e) && e.ward == 1 && e.line == 1 && strstr(e.msg, "unknown harness") != nullptr);
    // A cycle across the files is reported where it closes.
    CHECK(merge_two("[outfit a]\ninclude = b\n[outfit b]\n", "[outfit c]\ninclude = a\n[outfit d]\n", &e));
    CHECK(conf_check(&combined, &e));
    CHECK(merge_two("[outfit a]\ninclude = b\n", "[outfit b]\ninclude = a\n", &e));
    CHECK(!conf_check(&combined, &e) && e.ward == 1 && e.line == 2 && strstr(e.msg, "include cycle: a -> b -> a") != nullptr);

    // The same section in two files, for each shape of header.
    CHECK(!merge_two("[harness h]\n", "\n[harness h]\n", &e));
    CHECK(e.ward == 1 && e.line == 2 && strcmp(e.msg, "duplicate section [harness h]; first at /w/a/suit.conf:1") == 0);
    CHECK(!merge_two("[wear personal github.com/o/p machine=m]\n", "[wear personal github.com/o/p machine=m]\n", &e));
    CHECK(strcmp(e.msg, "duplicate section [wear personal github.com/o/p machine=m]; first at /w/a/suit.conf:1") == 0);
    CHECK(!merge_two("[wear user]\n", "[wear user]\n", &e) && strcmp(e.msg, "duplicate section [wear user]; first at /w/a/suit.conf:1") == 0);
    CHECK(!merge_two("[harness h]\n[need h n]\n", "[need h n]\n", &e) && e.line == 1 &&
        strcmp(e.msg, "duplicate section [need h n]; first at /w/a/suit.conf:2") == 0);
    CHECK(!merge_two("[upstream u]\n", "[upstream u]\n", &e) && strstr(e.msg, "[upstream u]") != nullptr);
    CHECK(merge_two("[wear user]\n", "[wear user machine=m]\n", &e));

    // The strings are in the combined set before its sections are compared: a stale buffer from an
    // earlier merge must not make a section a duplicate of itself.
    CHECK(merge_two("[outfit b]\n[outfit a]\n", "[outfit c]\n", &e));
    CHECK(merge_two("[outfit a]\n[outfit b]\n", "[outfit c]\n", &e) && combined.nsections == 3);

    // A merge that is refused part-way leaves the combined set as it was.
    {
        char before[2048], after[2048];
        CHECK(merge_two("[outfit a]\nskills = x\n[outfit b]\n", "[outfit c]\nskills = y\n[outfit a]\n", &e) == false);
        CHECK(combined.nsections == 2 && combined.nentries == 1 && combined.kind_count[KIND_OUTFIT] == 2);
        FILE *f = tmpfile();
        CHECK(f != nullptr && conf_dump(&combined, fileno(f)));
        rewind(f);
        size_t n = fread(before, 1, sizeof before - 1, f);
        before[n] = '\0';
        CHECK(strstr(before, "outfit a skills = x") != nullptr && strstr(before, "outfit c") == nullptr);
        CHECK(conf_check(&combined, &e));
        CHECK(!conf_merge(&combined, &part_b, 1, &merge_wards, &e));  // refused again
        rewind(f);
        CHECK(ftruncate(fileno(f), 0) == 0 && conf_dump(&combined, fileno(f)));
        rewind(f);
        n = fread(after, 1, sizeof after - 1, f);
        after[n] = '\0';
        CHECK(strcmp(before, after) == 0);
        fclose(f);
    }

    // The limits bound the combined set.
    static char text[16384];
    size_t off = 0;
    for (int i = 0; i < 64; i++) off += (size_t)snprintf(text + off, sizeof text - off, "[harness a%d]\n", i);
    CHECK(!merge_two(text, "[harness z]\n", &e) && e.ward == 1 && e.line == 1 &&
        strcmp(e.msg, "too many harness sections (limit 64)") == 0);
    static char entries[8200 * 16];
    off = (size_t)snprintf(entries, 32, "[harness h]\n");
    for (int i = 0; i < 8192; i++) off += (size_t)snprintf(entries + off, 16, "record = r\n");
    CHECK(!merge_two(entries, "[harness z]\nrecord = r\n", &e) && e.ward == 1 && e.line == 1 &&
        strcmp(e.msg, "too many entries (limit 8192)") == 0);
    CHECK(merge_two(entries, "[harness z]\n", &e));  // a section with no entry still fits
    static char big[CONF_FILE_MAX];
    for (size_t i = 0; i < sizeof big; i++) big[i] = i % 100 == 99 ? '\n' : '#';
    merge_names();
    CHECK(conf_parse_part(&part_a, big, sizeof big - 1, &e) && conf_parse_part(&part_b, "[outfit o]\n", 11, &e));
    conf_merge_init(&combined);
    CHECK(conf_merge(&combined, &part_a, 0, &merge_wards, &e));
    CHECK(!conf_merge(&combined, &part_b, 1, &merge_wards, &e) && e.ward == 1 && e.line == 0 &&
        strstr(e.msg, "together are over the limit of 1048576 bytes") != nullptr);
}

static void test_resolve(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    have(AK_SKILL, "s2", "s2");
    have(AK_SKILL, "t1", "t1");
    have(AK_SKILL, "unused", "unused");
    have(AK_AGENT, "ag", "ag.md");
    have(AK_COMMAND, "cm", "cm.md");
    ResolveError e;
    char got[4096];
    CHECK(resolve_text(three, &e));
    plan_text(got, sizeof got);
    const char *want =
        "/abs/codex/skills/s1 <- /sh/store/mine/skills/s1 [codex skills]\n"
        "/abs/codex/skills/t1 <- /sh/store/mine/skills/t1 [codex skills]\n"
        "/home/u <- /sh/store/mine/instructions/u.md [codex instructions]\n"
        "/home/u/.claude/CLAUDE.md <- /sh/store/mine/instructions/u.md [claude instructions]\n"
        "/home/u/.claude/agents/ag.md <- /sh/store/mine/agents/ag.md [claude agents]\n"
        "/home/u/.claude/commands/cm.md <- /sh/store/mine/commands/cm.md [claude commands]\n"
        "/home/u/.claude/skills/s1 <- /sh/store/mine/skills/s1 [claude skills]\n"
        "/home/u/.claude/skills/s2 <- /sh/store/mine/skills/s2 [claude skills]\n"
        "/home/u/.claude/skills/t1 <- /sh/store/mine/skills/t1 [claude skills]\n"
        "/home/u/.claude/x.json <- /sh/store/mine/files/x.json [- file]\n"
        "/sh/slots/hook/Stop <- /sh/store/mine/files/h.sh [- slot]\n";
    CHECK(strcmp(got, want) == 0);
    if (strcmp(got, want) != 0) printf("%s", got);
    // Only claude takes s2 (outfit b has only = claude) and nothing is for codex agents.
    CHECK(plan.nskips == 2);
    CHECK(strcmp(plan.skips[0], "skipped codex agents ag (no folder)") == 0);
    CHECK(strcmp(plan.skips[1], "skipped codex commands cm (no folder)") == 0);
}

// The machine limit: which wears apply, and which source wins or joins.
static void test_resolve_machine(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    ResolveError e;
    const char *head = "[harness h]\nskills.user = ~/s\ninstructions.user = ~/I.md\n";
    char text[2048];
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\nfile ~/f = files/a\n[outfit m]\nfile ~/f = files/b\nskills = s1\n", head);
    // The wear for m1 is ignored on another machine and when there is no name.
    test_machine = "other";
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/files/a") == 0);
    test_machine = "";
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/files/a") == 0);
    // On m1 its file wins and its skill is added.
    test_machine = "m1";
    CHECK(resolve_text(text, &e) && plan.n == 2 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].dest, "/home/u/f") == 0 && strcmp(plan.p[0].src, "/sh/store/mine/files/b") == 0);
    CHECK(plan.p[0].limited);

    // Two instruction files for one harness are joined; the plan has the winner only.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 1);
    CHECK(strcmp(plan.p[0].src, "/sh/joined/h") == 0 && strcmp(plan.joins[0].path, "/sh/joined/h") == 0);
    CHECK(strcmp(plan.joins[0].src[0], "/sh/store/mine/a.md") == 0);
    CHECK(strcmp(plan.joins[0].src[1], "/sh/store/mine/b.md") == 0);
    // The same file from both is one placement and no join.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = a.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/a.md") == 0);
    // ... but with a third, limited file the limited wins over the unlimited a.md.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m n\n"
        "[outfit u]\nfile ~/I.md = a.md\n[outfit m]\nfile ~/I.md = a.md\n[outfit n]\nfile ~/I.md = c.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/c.md") == 0);
    // An instruction file and a file for the same path: no join, the limited one wins.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\nfile ~/I.md = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/b.md") == 0);
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\nfile ~/I.md = a.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/b.md") == 0);

    // Two limited sources, or two unlimited ones, for one destination stay an error.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m n\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = b.md\n[outfit n]\ninstructions = c.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/b.md and /sh/store/mine/c.md") != nullptr);
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u v\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit v]\ninstructions = c.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/a.md and /sh/store/mine/c.md") != nullptr);

    // Instructions rank: shared, the harness's own, the machine's, the machine's own. All four are joined in that order.
    const char *ranks = "[harness h]\nskills.user = ~/s\ninstructions.user = ~/I.md\n[harness g]\nskills.user = ~/t\n"
        "instructions.user = ~/J.md\n[wear user]\noutfits = u x\n[wear user machine=m1]\noutfits = m y\n"
        "[outfit u]\ninstructions = a.md\n[outfit x]\nonly = h\ninstructions = b.md\n"
        "[outfit m]\ninstructions = c.md\n[outfit y]\nonly = h\ninstructions = d.md\n";
    CHECK(resolve_text(ranks, &e) && plan.n == 2 && plan.njoins == 2);
    // The plan is in destination order: I.md (harness h), then J.md (harness g).
    CHECK(strcmp(plan.joins[0].path, "/sh/joined/h") == 0 && plan.joins[0].n == 4);
    CHECK(strcmp(plan.joins[0].src[0], "/sh/store/mine/a.md") == 0 && strcmp(plan.joins[0].src[1], "/sh/store/mine/b.md") == 0);
    CHECK(strcmp(plan.joins[0].src[2], "/sh/store/mine/c.md") == 0 && strcmp(plan.joins[0].src[3], "/sh/store/mine/d.md") == 0);
    CHECK(strcmp(plan.joins[1].path, "/sh/joined/g") == 0 && plan.joins[1].n == 2);
    CHECK(strcmp(plan.joins[1].src[0], "/sh/store/mine/a.md") == 0 && strcmp(plan.joins[1].src[1], "/sh/store/mine/c.md") == 0);
    // Without a machine, shared and the extra only: the other harness links straight.
    test_machine = "other";
    CHECK(resolve_text(ranks, &e) && plan.n == 2 && plan.njoins == 1);
    CHECK(strcmp(plan.joins[0].path, "/sh/joined/h") == 0 && plan.joins[0].n == 2);
    CHECK(strcmp(plan.p[1].src, "/sh/store/mine/a.md") == 0);
    test_machine = "m1";
    // Two of one rank clash; the same file at two ranks is one source.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u x z\n[outfit u]\ninstructions = a.md\n[outfit x]\nonly = h\ninstructions = b.md\n"
        "[outfit z]\nonly = h\ninstructions = c.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/b.md and /sh/store/mine/c.md") != nullptr);
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u x\n[outfit u]\ninstructions = a.md\n[outfit x]\nonly = h\ninstructions = a.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    // Three of one rank: the first two are named.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u x z w\n[outfit u]\ninstructions = a.md\n[outfit x]\nonly = h\ninstructions = b.md\n"
        "[outfit z]\nonly = h\ninstructions = c.md\n[outfit w]\nonly = h\ninstructions = d.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/b.md and /sh/store/mine/c.md") != nullptr);
    test_machine = "";
}

// The join of up to four sources, in a scratch folder.
static void put_text(const char *dir, const char *name, const char *text)
{
    char path[128];
    snprintf(path, sizeof path, "%s/%s", dir, name);
    FILE *f = fopen(path, "w");
    CHECK(f != nullptr);
    fputs(text, f);
    fclose(f);
}

static void test_join_four(void)
{
    char dir[] = "/tmp/suit-unit-join.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    char names[5][128];
    const char *texts[5] = {"one\n", "two", "three\n", "four", "five\n"};
    for (int i = 0; i < 5; i++) {
        char leaf[16];
        snprintf(leaf, sizeof leaf, "s%d", i);
        put_text(dir, leaf, texts[i]);
        snprintf(names[i], sizeof names[i], "%s/%s", dir, leaf);
    }
    Join j = {.n = 4};
    snprintf(j.path, sizeof j.path, "%s/out", dir);
    for (int i = 0; i < 4; i++) j.src[i] = names[i];
    CHECK(join_current(&j) == 0);
    CHECK(join_write(&j) == 0);
    CHECK(join_current(&j) == 1);
    char got[128] = {};
    FILE *f = fopen(j.path, "r");
    CHECK(f != nullptr);
    CHECK(fread(got, 1, sizeof got - 1, f) == 21);
    fclose(f);
    CHECK(strcmp(got, "one\n\ntwo\n\nthree\n\nfour") == 0);
    // Any one source changed: the file is out of date.
    put_text(dir, "s3", "fourth");
    CHECK(join_current(&j) == 0);
    // Two sources, and a source that is gone.
    j.n = 2;
    j.src[1] = names[4];
    CHECK(join_write(&j) == 0 && join_current(&j) == 1);
    j.src[1] = "/suit-unit-no-such-source";
    CHECK(join_current(&j) == -1 && join_write(&j) == 1);
    char cmd[256];
    snprintf(cmd, sizeof cmd, "rm -r %s", dir);
    CHECK(system(cmd) == 0);
}

static void test_resolve_errors(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    have(AK_AGENT, "ag", "ag.md");
    ResolveError e;
    const char *head = "[harness h]\nskills.user = ~/s\nagents.user = ~/a\ninstructions.user = ~/I.md\n"
                       "[wear user]\noutfits = o\n";
    char text[2048];
    snprintf(text, sizeof text, "%s[outfit o]\nskills = s1 nope\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "outfit o: skills 'nope' matches nothing in the store") != nullptr);
    snprintf(text, sizeof text, "%s[outfit o]\nagents = zz*\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "outfit o: agents 'zz*' matches nothing") != nullptr);

    // Two outfits wanting one destination from different sources.
    snprintf(text, sizeof text, "%s[outfit o]\ninclude = p\ninstructions = a.md\n[outfit p]\ninstructions = b.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/a.md and /sh/store/mine/b.md") != nullptr);

    // The same source twice is one placement.
    snprintf(text, sizeof text, "%s[outfit o]\ninclude = p\nskills = s1\n[outfit p]\nskills = s1\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1);

    // A harness folder that is not absolute, and a path with a space.
    snprintf(text, sizeof text, "[harness h]\nskills.user = .claude/skills\n[wear user]\noutfits = o\n[outfit o]\nskills = s1\n");
    CHECK(!resolve_text(text, &e) && strstr(e.msg, ".claude/skills/s1 is not an absolute path") != nullptr);
    snprintf(text, sizeof text, "[harness h]\nskills.user = /a b\n[wear user]\noutfits = o\n[outfit o]\nskills = s1\n");
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "a space in") != nullptr);
    snprintf(text, sizeof text, "%s[outfit o]\nfile ~/f = a b\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "a space in") != nullptr);

    // A wear with no outfits and an outfit with nothing in it place nothing.
    CHECK(resolve_text("[wear user]\n[outfit o]\n", &e) && plan.n == 0 && plan.nskips == 0);
}

static void test_resolve_limits(void)
{
    // 2048 skills for 3 harnesses is more placements than there can be.
    static char names[ASSET_MAX][16];
    have_reset();
    for (uint32_t i = 0; i < ASSET_MAX; i++) {
        snprintf(names[i], sizeof names[i], "s%u", i);
        have(AK_SKILL, names[i], names[i]);
    }
    ResolveError e;
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[harness b]\nskills.user = /b\n[harness c]\nskills.user = /c\n"
                        "[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(strstr(e.msg, "more than 4096 placements") != nullptr);
    CHECK(resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(plan.n == ASSET_MAX);

    // Too many skipped lines: agents for a harness with no agent folder.
    static char agents[ASSET_MAX][16];
    have_reset();
    for (uint32_t i = 0; i < SKIP_MAX + 1; i++) {
        snprintf(agents[i], sizeof agents[i], "g%u", i);
        have(AK_AGENT, agents[i], agents[i]);
    }
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nagents = *\n", &e));
    CHECK(strstr(e.msg, "more than 1024 skipped lines") != nullptr);

    // More places supply one name than resolve_why keeps: one skill, two outfits, 33 harnesses.
    have_reset();
    have(AK_SKILL, "s1", "s1");
    static char many[16384];
    size_t used = 0;
    for (uint32_t i = 0; i <= SUPPLIER_MAX / 2; i++)
        used += (size_t)snprintf(many + used, sizeof many - used, "[harness h%u]\nskills.user = /h%u\n", i, i);
    snprintf(many + used, sizeof many - used, "[wear user]\noutfits = o p\n[outfit o]\nskills = s1\n[outfit p]\nskills = s1\n");
    ConfError ce;
    CHECK(parse(many, &ce));
    test_wards = one_ward();
    CHECK(!resolve_why(&conf, &assets, "/home/u", "/sh", &test_wards, test_machine, &no_projects, "s1", &plan, &e));
    CHECK(strstr(e.msg, "more than 64 places supply s1") != nullptr);
    CHECK(plan.nsuppliers == SUPPLIER_MAX);

    // Paths that do not fit in the plan: long names, many of them.
    static char longs[ASSET_MAX][130];
    have_reset();
    for (uint32_t i = 0; i < ASSET_MAX; i++) {
        memset(longs[i], 'x', 120);
        snprintf(longs[i] + 120, 10, "%07u", i);
        have(AK_SKILL, longs[i], longs[i]);
    }
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(strstr(e.msg, "the plan is larger than") != nullptr);
    have_reset();
}

// ---- ledger ---------------------------------------------------------------------

static Ledger ledger;

static void ledger_error(const char *text, int line, const char *part)
{
    LedgerError e;
    bool ok = ledger_parse(&ledger, text, strlen(text), &e);
    CHECK(!ok && ledger.n == 0 && e.line == line && strstr(e.msg, part) != nullptr);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  ledger wanted line %d '%s', got %d '%s'\n", line, part, e.line, ok ? "(parsed)" : e.msg);
}

static void test_exclude_line(void)
{
    char out[16];
    CHECK(exclude_line("a/b", out, sizeof out) && strcmp(out, "/a/b") == 0);
    CHECK(exclude_line("x[1]*?\\", out, sizeof out) && strcmp(out, "/x\\[1]\\*\\?\\\\") == 0);
    CHECK(exclude_line("", out, 2) && strcmp(out, "/") == 0);
    CHECK(!exclude_line("a", out, 1) && !exclude_line("a", out, 0));
    CHECK(exclude_line("abcdef", out, 8) && !exclude_line("abcdefg", out, 8));
    CHECK(exclude_line("ab*", out, 6) && !exclude_line("ab*", out, 5));
}

static void test_ledger(void)
{
    LedgerError e;
    CHECK(ledger_parse(&ledger, "", 0, &e) && ledger.n == 0);
    CHECK(ledger_parse(&ledger, "link /a /s/a\ndir /a\n", 20, &e) && ledger.n == 2);
    CHECK(ledger.e[0].kind == ENTRY_LINK && strcmp(ledger.e[0].src, "/s/a") == 0);
    CHECK(ledger.e[1].kind == ENTRY_DIR && ledger.e[1].src == nullptr);
    CHECK(ledger_find_link(&ledger, "/a") == &ledger.e[0] && ledger_find_link(&ledger, "/b") == nullptr);
    CHECK(ledger_find_link(&ledger, "/a") != nullptr);
    CHECK(ledger_parse(&ledger, "file /a\nlink /a /s\ndir /a\n", 26, &e) && ledger.n == 3);
    CHECK(ledger.e[0].kind == ENTRY_FILE && ledger.e[0].src == nullptr);
    ledger_error("link /a\n", 1, "link needs DEST and SOURCE");
    ledger_error("dir /a /b\n", 1, "dir takes only DEST");
    ledger_error("bogus /a\n", 1, "unknown record 'bogus'");
    ledger_error("link\n", 1, "expected");
    ledger_error("file /a /b\n", 1, "file takes only DEST");
    CHECK(ledger_parse(&ledger, "block /a\nblock /b created\n", 26, &e) && ledger.n == 2);
    CHECK(ledger.e[0].kind == ENTRY_BLOCK && ledger.e[0].src == nullptr);
    CHECK(ledger.e[1].kind == ENTRY_BLOCK && strcmp(ledger.e[1].src, "created") == 0);
    ledger_error("block /a made\n", 1, "block takes DEST");
    ledger_error("block /a created x\n", 1, "block takes DEST");
    ledger_error("block a\n", 1, "absolute");
    ledger_error("block /a\nblock /a created\n", 2, "duplicate block /a");
    ledger_error("file a\n", 1, "absolute");
    ledger_error("file /a\nfile /a\n", 2, "duplicate file /a");
    ledger_error("link a /b\n", 1, "absolute");
    ledger_error("link /a b\n", 1, "absolute");
    ledger_error("dir a\n", 1, "absolute");
    ledger_error("link /a /b /c\n", 1, "absolute");
    ledger_error("link /a /b\nlink /a /c\n", 2, "duplicate link /a");
    ledger_error("link /a /b\ndir /a\ndir /a\n", 3, "duplicate dir /a");
    ledger_error("link /a /b", 1, "no newline");
    ledger_error("link /a /b\nlink /c /d", 2, "no newline");
    char big[LEDGER_LINE_MAX + 100];
    memset(big, 'x', sizeof big);
    memcpy(big, "dir /", 5);
    big[LEDGER_LINE_MAX + 1] = '\n';
    LedgerError le;
    CHECK(!ledger_parse(&ledger, big, LEDGER_LINE_MAX + 2, &le) && le.line == 1 && strstr(le.msg, "limit is 8192") != nullptr);
    CHECK(!ledger_parse(&ledger, "dir /a\0b\n", 9, &le) && le.line == 1 && strstr(le.msg, "NUL") != nullptr);
    static char file[LEDGER_FILE_MAX + 16];
    memset(file, '\n', sizeof file);
    CHECK(!ledger_parse(&ledger, file, LEDGER_FILE_MAX + 1, &le) && le.line == 0 && strstr(le.msg, "limit is") != nullptr);

    // 4096 entries fit and the 4097th does not.
    static char many[LEDGER_ENTRY_MAX * 16 + 64];
    size_t off = 0;
    for (uint32_t i = 0; i <= LEDGER_ENTRY_MAX; i++) {
        off += (size_t)snprintf(many + off, 16, "dir /d%u\n", i);
        if (i == LEDGER_ENTRY_MAX - 1) CHECK(ledger_parse(&ledger, many, off, &le) && ledger.n == LEDGER_ENTRY_MAX);
    }
    CHECK(!ledger_parse(&ledger, many, off, &le) && le.line == (int)LEDGER_ENTRY_MAX + 1 && strstr(le.msg, "too many entries") != nullptr);

    // Written sorted, links before dirs, and the same entries read back.
    char path[] = "/tmp/suit-unit-ledger.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    close(fd);
    Ledger out;
    out.n = 0;
    out.e[out.n++] = (LedgerEntry){ENTRY_DIR, "/z", nullptr};
    out.e[out.n++] = (LedgerEntry){ENTRY_LINK, "/b", "/s/b"};
    out.e[out.n++] = (LedgerEntry){ENTRY_DIR, "/y", nullptr};
    out.e[out.n++] = (LedgerEntry){ENTRY_LINK, "/a", "/s/a"};
    out.e[out.n++] = (LedgerEntry){ENTRY_FILE, "/f", nullptr};
    CHECK(ledger_write(&out, path) == 0);
    CHECK(ledger_load(&ledger, path, &le) && ledger.n == 5);
    CHECK(strcmp(ledger.e[0].dest, "/a") == 0 && strcmp(ledger.e[1].dest, "/b") == 0 &&
          strcmp(ledger.e[2].dest, "/y") == 0 && strcmp(ledger.e[3].dest, "/z") == 0);
    CHECK(ledger.e[4].kind == ENTRY_FILE && strcmp(ledger.e[4].dest, "/f") == 0);
    // Too much to write.
    static char longpath[LEDGER_LINE_MAX];
    memset(longpath, 'p', sizeof longpath - 1);
    longpath[0] = '/';
    out.n = 0;
    for (int i = 0; i < 200; i++) out.e[out.n++] = (LedgerEntry){ENTRY_DIR, longpath, nullptr};
    CHECK(ledger_write(&out, path) == EFBIG);
    unlink(path);
}

// ---- place: limits that need no disk to reach -----------------------------------

static Actions actions;
static Plan big_plan;

static void test_place_limits(void)
{
    // Placements in folders that do not exist: two new folders each.
    static char dests[2100][64];
    big_plan.n = 0;
    for (int i = 0; i < 2100; i++) {
        snprintf(dests[i], sizeof dests[i], "/suit-no-such/d%d/e%d/link", i, i);
        big_plan.p[big_plan.n++] = (Placement){dests[i], "/s", "h", AK_SKILL, false, false, nullptr, KIND_NONE, nullptr, "mine"};
    }
    Ledger none;
    none.n = 0;
    CHECK(place_plan(&big_plan, &none, &actions) == 1);  // too many folders

    // Folder names too long for the list, fewer of them.
    static char longdests[300][1100];
    big_plan.n = 0;
    for (int i = 0; i < 300; i++) {
        memset(longdests[i], 'q', 1000);
        snprintf(longdests[i], 40, "/suit-no-such/%d", i);
        longdests[i][strlen(longdests[i])] = 'q';
        snprintf(longdests[i] + 1000, 90, "/%d/link", i);
        big_plan.p[big_plan.n++] = (Placement){longdests[i], "/s", "h", AK_SKILL, false, false, nullptr, KIND_NONE, nullptr, "mine"};
    }
    CHECK(place_plan(&big_plan, &none, &actions) == 1);
}

// ---- place: what a failed call or an odd disk does ---------------------------------

static int count_cb(void *state, const char *name)
{
    (void)name;
    ++*(int *)state;
    return 0;
}

static int stop_cb(void *state, const char *name)
{
    (void)state;
    (void)name;
    return 7;
}

static void test_listdir(void)
{
    char dir[] = "/tmp/suit-unit-list.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    char file[256];
    for (int i = 0; i < 2; i++) {
        snprintf(file, sizeof file, "%s/f%d", dir, i);
        int fd = open(file, O_WRONLY | O_CREAT, 0644);
        CHECK(fd >= 0);
        close(fd);
    }
    int n = 0;
    CHECK(sys_listdir(dir, count_cb, &n) == 0 && n == 2);
    CHECK(sys_listdir(dir, stop_cb, nullptr) == 7);  // the callback stops the walk
    CHECK(sys_listdir("/suit-no-such-folder", count_cb, &n) == -1 && errno == ENOENT);
    for (int i = 0; i < 2; i++) {
        snprintf(file, sizeof file, "%s/f%d", dir, i);
        unlink(file);
    }
    rmdir(dir);
}

static char pbase[160];
static int loud_fd = 2;
static Ledger pled;
static Ledger pchk;

#define EXPECT(cond)                                                                     \
    do {                                                                                 \
        if (!(cond)) {                                                                   \
            dprintf(loud_fd, "FAIL unit %s:%d: %s\n", __FILE__, __LINE__, #cond);        \
            return 1;                                                                    \
        }                                                                                \
    } while (0)

// PBASE/REL, in one of a ring of buffers so a case can hold many at once.
static const char *pp(const char *rel)
{
    static char ring[64][512];
    static unsigned next;
    char *s = ring[next++ % 64];
    snprintf(s, sizeof ring[0], "%s/%s", pbase, rel);
    return s;
}

static void must(int rc)
{
    if (rc != 0) {
        dprintf(loud_fd, "FAIL unit: scratch setup\n");
        _exit(97);
    }
}

static void pl_put(const char *rel, const char *text)
{
    int fd = open(pp(rel), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    must(fd < 0);
    must(write(fd, text, strlen(text)) < 0);
    close(fd);
}

static void sl(const char *target, const char *rel) { must(symlink(target, pp(rel))); }
static void md(const char *rel) { must(mkdir(pp(rel), 0755)); }
static bool there(const char *rel)
{
    struct stat st;
    return lstat(pp(rel), &st) == 0;
}

static pid_t dead_pid(void)
{
    pid_t pid = fork();
    if (pid == 0) _exit(0);
    int status;
    waitpid(pid, &status, 0);
    return pid;
}

static void reset(void)
{
    pled.n = 0;
    big_plan.n = 0;
    big_plan.nskips = 0;
    actions.n = 0;
    actions.ndirs = 0;
    actions.used = 0;
}

static void want(const char *dest, const char *src) { big_plan.p[big_plan.n++] = (Placement){dest, src, "h", AK_SKILL, false, false, nullptr, KIND_NONE, nullptr, "mine"}; }
static void lk(const char *dest, const char *src) { pled.e[pled.n++] = (LedgerEntry){ENTRY_LINK, dest, src}; }
static void dr(const char *dest) { pled.e[pled.n++] = (LedgerEntry){ENTRY_DIR, dest, nullptr}; }
static void act(ActKind kind, const char *dest, const char *src) { actions.a[actions.n++] = (Action){kind, dest, src, nullptr, nullptr, nullptr, nullptr}; }
static int pl_plan(void) { return place_plan(&big_plan, &pled, &actions); }
static int apply(void) { return place_apply(&pled, &actions, pp("ledger")); }
static int off(void) { return place_off(&pled, pp("ledger")); }

static bool ledger_has(uint32_t n)
{
    LedgerError le;
    return ledger_load(&pchk, pp("ledger"), &le) && pchk.n == n;
}

static int entries(void)
{
    int n = 0;
    return sys_listdir(pbase, count_cb, &n) == 0 ? n : -1;
}

static int c_plan_blocked(void)
{
    reset();
    pl_put("f", "x");
    want(pp("f/x/link"), "/s");  // a file where a folder should be
    EXPECT(pl_plan() == 0 && actions.n == 1 && actions.a[0].kind == ACT_CLASH && actions.ndirs == 0);
    return 0;
}

static int c_plan_lstat_fails(void)
{
    reset();
    want(pp("a/link"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_readlink_fails(void)
{
    reset();
    sl("/x", "l");
    want(pp("l"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_parent_stat_fails(void)
{
    reset();
    want(pp("m/n/link"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_link_not_ours(void)
{
    reset();
    sl("/other", "l");
    lk(pp("l"), "/old");  // the ledger says /old, the want is /new, the disk has /other
    want(pp("l"), "/new");
    EXPECT(pl_plan() == 0 && actions.n == 1 && actions.a[0].kind == ACT_CLASH);
    return 0;
}

static int c_plan_stale(void)
{
    reset();
    pl_put("file", "x");
    md("dir");
    sl("/else", "other");
    sl("/s", "mine");
    lk(pp("gone"), "/s");
    lk(pp("file"), "/s");
    lk(pp("dir"), "/s");
    lk(pp("other"), "/s");
    lk(pp("mine"), "/s");
    EXPECT(pl_plan() == 0 && actions.n == 5);
    EXPECT(actions.a[0].kind == ACT_CLASH && actions.a[1].kind == ACT_CLASH);  // dir, file
    EXPECT(actions.a[2].kind == ACT_DROP && actions.a[3].kind == ACT_REMOVE);  // gone, mine
    EXPECT(actions.a[4].kind == ACT_CLASH);                                    // other
    return 0;
}

static int c_plan_stale_lstat_fails(void)
{
    reset();
    lk(pp("x"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_missing(void)
{
    reset();
    pl_put("here", "x");
    lk(pp("gone"), "/s");
    lk(pp("here"), "/s");
    dr(pp("somedir"));
    EXPECT(place_missing(&pled, false) == 1 && place_missing(&pled, true) == 1);
    return 0;
}

static int c_missing_lstat_fails(void)
{
    reset();
    lk(pp("gone"), "/s");
    EXPECT(place_missing(&pled, false) == 0);  // not told to be gone, so not counted
    return 0;
}

static int c_lock_taken_over(void)
{
    char text[32];
    snprintf(text, sizeof text, "%d\n", (int)dead_pid());
    pl_put("lock", text);
    EXPECT(place_lock(pp("lock"), false) == 0);
    place_unlock(pp("lock"));
    return 0;
}

static int c_apply_limit(void)
{
    reset();
    for (uint32_t i = 0; i < LEDGER_ENTRY_MAX; i++) dr("/x");
    actions.dirs[actions.ndirs++] = "/y";
    EXPECT(apply() == 1 && !there("ledger"));
    return 0;
}

static int c_apply_mkdir_fails(void)
{
    reset();
    actions.dirs[actions.ndirs++] = pp("nd");
    EXPECT(apply() == 1 && !there("nd") && ledger_has(0));
    return 0;
}

static int c_apply_mkdir_exists(void)
{
    reset();
    actions.dirs[actions.ndirs++] = pp("nd");
    EXPECT(apply() == 0 && ledger_has(1));
    return 0;
}

static int c_apply_link_fails(void)
{
    reset();
    act(ACT_CREATE, pp("l"), "/s");
    EXPECT(apply() == 1 && !there("l") && ledger_has(0) && entries() == 1);
    return 0;
}

static int c_apply_remove_fails(void)
{
    reset();
    sl("/s", "l");
    lk(pp("l"), "/s");
    act(ACT_REMOVE, pp("l"), "/s");
    EXPECT(apply() == 1 && there("l") && ledger_has(1));
    return 0;
}

static int c_apply_first_ledger_fails(void)
{
    reset();
    act(ACT_CREATE, pp("l"), "/s");
    EXPECT(apply() == 1 && !there("l"));
    return 0;
}

static int c_apply_last_ledger_fails(void)
{
    reset();
    EXPECT(apply() == 1);
    return 0;
}

static int c_off_mixed(void)
{
    reset();
    pl_put("file", "x");
    sl("/x", "other");
    sl("/s", "mine");
    md("z");
    md("a");
    md("full");
    pl_put("full/f", "x");
    lk(pp("gone"), "/s");
    lk(pp("file"), "/s");
    lk(pp("other"), "/y");
    lk(pp("mine"), "/s");
    dr(pp("z"));
    dr(pp("a"));
    dr(pp("full"));
    dr(pp("nodir"));
    EXPECT(off() == 0 && ledger_has(0));
    EXPECT(!there("mine") && there("file") && there("other") && !there("z") && !there("a") && there("full"));
    return 0;
}

static int c_off_rmdir_exist(void)
{
    reset();
    md("d");
    dr(pp("d"));
    EXPECT(off() == 0 && there("d") && ledger_has(0));
    return 0;
}

static int c_off_rmdir_fails(void)
{
    reset();
    md("d1");
    md("d2");
    dr(pp("d1"));
    dr(pp("d2"));
    EXPECT(off() == 1 && there("d1") && there("d2") && ledger_has(2));
    return 0;
}

static int c_off_unlink_fails(void)
{
    reset();
    sl("/s", "mine");
    md("d");
    lk(pp("mine"), "/s");
    dr(pp("d"));
    EXPECT(off() == 1 && there("mine") && there("d") && ledger_has(2));
    return 0;
}

static int c_off_lstat_fails(void)
{
    reset();
    lk(pp("gone"), "/s");
    EXPECT(off() == 1 && ledger_has(1));
    return 0;
}

static int (*case_cur)(void);

// A case runs in a child, with its output off and its failures on the real stderr.
static int case_cur_run(void)
{
    loud_fd = dup(2);
    int null = open("/dev/null", O_WRONLY);
    dup2(null, 1);
    dup2(null, 2);
    close(null);
    return case_cur();
}

static int nftw_remove(const char *path, const struct stat *st, int type, struct FTW *ftw)
{
    (void)st;
    (void)type;
    (void)ftw;
    return remove(path);
}

static void test_place_faults(void)
{
    char root[] = "/tmp/suit-unit-place.XXXXXX";
    CHECK(mkdtemp(root) != nullptr);
    static const struct {
        const char *spec;
        int (*fn)(void);
    } cases[] = {
        {"", c_plan_blocked},
        {"lstat:1", c_plan_lstat_fails},
        {"readlink:1", c_plan_readlink_fails},
        {"stat:1", c_plan_parent_stat_fails},
        {"", c_plan_link_not_ours},
        {"", c_plan_stale},
        {"lstat:1", c_plan_stale_lstat_fails},
        {"", c_missing},
        {"lstat:1", c_missing_lstat_fails},
        {"read:1", c_lock_taken_over},
        {"kill:1:EPERM", c_lock_taken_over},
        {"", c_apply_limit},
        {"mkdir:1", c_apply_mkdir_fails},
        {"mkdir:1:EEXIST", c_apply_mkdir_exists},
        {"symlink:1", c_apply_link_fails},
        {"rename:2", c_apply_link_fails},
        {"unlink:1", c_apply_remove_fails},
        {"open:1", c_apply_first_ledger_fails},
        {"rename:2", c_apply_last_ledger_fails},
        {"", c_off_mixed},
        {"rmdir:1:EEXIST", c_off_rmdir_exist},
        {"rmdir:1", c_off_rmdir_fails},
        {"unlink:1", c_off_unlink_fails},
        {"lstat:1", c_off_lstat_fails},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        snprintf(pbase, sizeof pbase, "%s/c%zu", root, i);
        CHECK(mkdir(pbase, 0755) == 0);
        case_cur = cases[i].fn;
        CHECK(in_child(cases[i].spec, case_cur_run) == 0);
    }
    CHECK(nftw(root, nftw_remove, 16, FTW_DEPTH | FTW_PHYS) == 0);
}

// ---- projects: remote keys ----------------------------------------------------

static void test_project_keys(void)
{
    static const struct {
        const char *url;
        const char *key;  // nullptr: no key
    } t[] = {
        {"https://github.com/Owner/Name.git", "github.com/Owner/Name"},
        {"[email protected]:Owner/Name.git", "github.com/Owner/Name"},
        {"ssh://[email protected]/Owner/Name", "github.com/Owner/Name"},
        {"https://zeitforge.app/r/dmestas/suit", "zeitforge.app/r/dmestas/suit"},
        {"https://GitHub.COM/Owner/Name", "github.com/Owner/Name"},
        {"HTTPS://github.com/o/n", "github.com/o/n"},
        {"https://user:[email protected]:8443/o/n.git", "github.com/o/n"},
        {"ssh://[email protected]:2222/a/b/", "host.example/a/b"},
        {"https://github.com/o/n/", "github.com/o/n"},
        {"https://github.com/o/n.git/", "github.com/o/n"},
        {"https://github.com/o/n.git.git", "github.com/o/n"},
        {"https://github.com//o/n", "github.com/o/n"},
        {"https://github.com/o/n?x=1#frag", "github.com/o/n"},
        {"https://github.com/o/a.b.c", "github.com/o/a.b.c"},
        {"https://github.com/o/.github", "github.com/o/.github"},
        {"https://github.com/o/name.gitx", "github.com/o/name.gitx"},
        {"https://github.com/o/.git", "github.com/o"},
        {"github.com:o/n.git", "github.com/o/n"},
        {"host:path", "host/path"},
        {"user@host:~me/repo", "host/~me/repo"},
        {"[email protected]:Owner/Name", "github.com/Owner/Name"},
        {"git://host.example/a/b.git", "host.example/a/b"},
        {"http://10.0.0.5:3000/team/repo.git", "10.0.0.5/team/repo"},
        {"a@[email protected]:x/y", "host.example/x/y"},
        {"https://u@[email protected]/x", "host.example/x"},
        {"", nullptr},
        {"/local/path/repo", nullptr},
        {"./relative:path", nullptr},
        {"../repo", nullptr},
        {"file:///x/y", nullptr},
        {"FILE:///x/y", nullptr},
        {"://host/path", nullptr},
        {"https://github.com", nullptr},
        {"https://github.com/", nullptr},
        {"https://github.com/.git", nullptr},
        {"https://github.com////", nullptr},
        {"https:///path", nullptr},
        {"https://[::1]/a/b", nullptr},
        {"https://ho st/a", nullptr},
        {"https://host/a b", nullptr},
        {"https://host/a\tb", nullptr},
        {"https://host/a\x7f" "b", nullptr},
        {"https://ho_st/a", nullptr},
        {"https://host/", nullptr},
        {"justaword", nullptr},
        {"host:", nullptr},
        {":path", nullptr},
        {"https://?q", nullptr},
        {"#x", nullptr},
    };
    char key[PROJECT_KEY_MAX + 1];
    for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) {
        memset(key, 'x', sizeof key);
        bool ok = project_key_from_url(t[i].url, key, sizeof key);
        CHECK(ok == (t[i].key != nullptr));
        CHECK(ok ? t[i].key != nullptr && strcmp(key, t[i].key) == 0 : key[0] == '\0');
        if (ok != (t[i].key != nullptr) || (ok && strcmp(key, t[i].key) != 0))
            printf("  address '%s' gave '%s'\n", t[i].url, ok ? key : "(none)");
        if (ok) CHECK(project_key_ok(key));
    }
}

static void test_project_key_limits(void)
{
    char url[PROJECT_URL_MAX + 64];
    char key[PROJECT_KEY_MAX + 1];
    // exactly PROJECT_KEY_MAX bytes of key is the longest that fits
    size_t pre = strlen("h.test/");
    memset(url, 0, sizeof url);
    snprintf(url, sizeof url, "https://h.test/");
    memset(url + strlen(url), 'a', PROJECT_KEY_MAX - pre);
    CHECK(project_key_from_url(url, key, sizeof key) && strlen(key) == PROJECT_KEY_MAX);
    CHECK(project_key_ok(key));
    url[strlen(url)] = 'a';
    CHECK(!project_key_from_url(url, key, sizeof key) && key[0] == '\0');
    // a cap that is too small for the key
    CHECK(!project_key_from_url("https://h.test/a/b", key, 8) && key[0] == '\0');
    CHECK(project_key_from_url("https://h.test/a/b", key, 11) && strcmp(key, "h.test/a/b") == 0);
    CHECK(!project_key_from_url("https://h.test/a/b", key, 10) && key[0] == '\0');
    // an address of PROJECT_URL_MAX bytes or more is refused
    memset(url, 'a', PROJECT_URL_MAX + 8);
    url[PROJECT_URL_MAX + 8] = '\0';
    memcpy(url, "https://h.test/", 15);
    CHECK(!project_key_from_url(url, key, sizeof key));
    memset(url, 'a', PROJECT_URL_MAX - 1);
    url[PROJECT_URL_MAX - 1] = '\0';
    memcpy(url, "https://h.test/", 15);
    CHECK(!project_key_from_url(url, key, sizeof key));  // the key is over its own limit
}

static void test_project_key_ok(void)
{
    static const struct {
        const char *key;
        bool ok;
    } t[] = {
        {"github.com/Owner/Name", true},
        {"a/b", true},
        {"h-1.test/a/b.c", true},
        {"", false},
        {"/", false},
        {"a/", false},
        {"/b", false},
        {"ab", false},
        {"GitHub.com/o/n", false},
        {"git hub.com/o/n", false},
        {"h_x/o", false},
        {"h/o n", false},
        {"h/o\tn", false},
        {"h/o\x7f" "n", false},
        {"h//o", false},
        {"h/o/", false},
        {"h/o.git", false},
        {"h/.git", false},
        {"h/x.gitx", true},
        {"h/git", true},
        {"h:80/o", false},
        {"h@x/o", false},
    };
    for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) {
        CHECK(project_key_ok(t[i].key) == t[i].ok);
        if (project_key_ok(t[i].key) != t[i].ok) printf("  key '%s'\n", t[i].key);
    }
    char big[PROJECT_KEY_MAX + 3];
    memset(big, 'a', sizeof big);
    big[1] = '/';
    big[PROJECT_KEY_MAX] = '\0';
    CHECK(project_key_ok(big));
    big[PROJECT_KEY_MAX] = 'a';
    big[PROJECT_KEY_MAX + 1] = '\0';
    CHECK(!project_key_ok(big));
}

static void test_project_path_ok(void)
{
    char big[PROJECT_PATH_MAX + 2];
    CHECK(project_path_ok("/"));
    CHECK(project_path_ok("/a"));
    CHECK(project_path_ok("/a b/c"));
    CHECK(project_path_ok("/caf\xc3\xa9"));
    CHECK(!project_path_ok(""));
    CHECK(!project_path_ok("a"));
    CHECK(!project_path_ok("/a/"));
    CHECK(!project_path_ok("/a\nb"));
    CHECK(!project_path_ok("/a\tb"));
    CHECK(!project_path_ok("/a\x7f"));
    memset(big, 'a', sizeof big);
    big[0] = '/';
    big[PROJECT_PATH_MAX - 1] = '\0';
    CHECK(project_path_ok(big));
    big[PROJECT_PATH_MAX - 1] = 'a';
    big[PROJECT_PATH_MAX] = '\0';
    CHECK(!project_path_ok(big));
}

// ---- projects: the git config reader and the three files ---------------------

static bool remote_of(const char *config, char *url)
{
    static char text[4096];
    size_t len = strlen(config);
    memcpy(text, config, len + 1);
    return project_git_remote(text, len, url, PROJECT_URL_MAX);
}

static void test_project_git_remote(void)
{
    char url[PROJECT_URL_MAX];
    CHECK(remote_of("[remote \"origin\"]\n\turl = https://a.test/x/y.git\n", url) && strcmp(url, "https://a.test/x/y.git") == 0);
    // origin beats an earlier remote
    CHECK(remote_of("[remote \"up\"]\n\turl = u1\n[remote \"origin\"]\n\turl = o1\n", url) && strcmp(url, "o1") == 0);
    // no origin: the first remote
    CHECK(remote_of("[remote \"up\"]\n\turl = u1\n[remote \"other\"]\n\turl = u2\n", url) && strcmp(url, "u1") == 0);
    CHECK(remote_of("[remote \"up\"]\n\tfetch = +x\n[remote \"other\"]\n\turl = u2\n", url) && strcmp(url, "u2") == 0);
    // section and key names are not case sensitive, blanks and a CR do not matter
    CHECK(remote_of("  [Remote \"origin\"]  \r\n  URL=  spaced \t\r\n", url) && strcmp(url, "spaced") == 0);
    CHECK(remote_of("[remote \"origin\"]\nurl=x", url) && strcmp(url, "x") == 0);
    // only the first url of a remote counts
    CHECK(remote_of("[remote \"origin\"]\nurl = first\nurl = second\n", url) && strcmp(url, "first") == 0);
    // a url outside a remote, or in another section, is not an address
    CHECK(!remote_of("url = x\n[core]\nurl = y\n[branch \"origin\"]\nurl = z\n", url));
    CHECK(!remote_of("[remote \"origin\"]\n[core]\nurl = y\n", url));
    CHECK(!remote_of("[remote]\nurl = x\n", url));
    CHECK(!remote_of("[remote \"origin\"\nurl = x\n", url));
    CHECK(!remote_of("[remote origin]\nurl = x\n", url));
    CHECK(!remote_of("[remote \"origin]\nurl = x\n", url));
    CHECK(remote_of("[remote \"a\"]\nurl = x\n", url) && strcmp(url, "x") == 0);
    CHECK(!remote_of("[remote \"origin\"]\nurl\n", url));
    CHECK(!remote_of("[remote \"origin\"]\nurl x\n", url));
    CHECK(!remote_of("[remote \"origin\"]\nurl =\n", url));
    CHECK(!remote_of("[remote \"origin\"]\nurl =   \n", url));
    CHECK(!remote_of("[remote \"origin\"]\nurlx = a\n", url));
    CHECK(!remote_of("", url));
    CHECK(!remote_of("\n\n", url));
    // a remote named like origin but longer or shorter is not origin
    CHECK(remote_of("[remote \"up\"]\nurl = u\n[remote \"origins\"]\nurl = o\n[remote \"orig\"]\nurl = p\n", url)
        && strcmp(url, "u") == 0);
    // a bad url line is skipped and a later remote's is used
    char big[PROJECT_URL_MAX + 64];
    snprintf(big, sizeof big, "[remote \"origin\"]\nurl = %*s\n[remote \"b\"]\nurl = ok\n", (int)PROJECT_URL_MAX, "");
    memset(strchr(big, '=') + 2, 'a', PROJECT_URL_MAX);
    CHECK(remote_of(big, url) && strcmp(url, "ok") == 0);
    // the longest address that fits
    char fit[PROJECT_URL_MAX + 64];
    int n = snprintf(fit, sizeof fit, "[remote \"origin\"]\nurl = ");
    memset(fit + n, 'b', PROJECT_URL_MAX - 1);
    memcpy(fit + n + PROJECT_URL_MAX - 1, "\n", 2);
    CHECK(remote_of(fit, url) && strlen(url) == PROJECT_URL_MAX - 1);
    // text ends in the middle of a line, and a NUL ends a line early
    char nul[] = "[remote \"origin\"]\nurl = a\0b\n";
    CHECK(project_git_remote(nul, sizeof nul - 1, url, sizeof url) && strcmp(url, "a") == 0);
}

static Roots roots_t;
static Projects projects_t;
static Projects fill_t;

static void roots_bad(const char *text, int line, const char *part)
{
    ProjectError e;
    bool ok = roots_parse(&roots_t, text, strlen(text), &e);
    CHECK(!ok && e.line == line && strstr(e.msg, part) != nullptr && roots_t.n == 0);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  roots %zu bytes: wanted line %d '%s', got %d '%s'\n", strlen(text), line, part, e.line, ok ? "(parsed)" : e.msg);
}

static void projects_bad(const char *text, bool with_kind, int line, const char *part)
{
    ProjectError e;
    bool ok = projects_parse(&projects_t, text, strlen(text), with_kind, &e);
    CHECK(!ok && e.line == line && strstr(e.msg, part) != nullptr && projects_t.n == 0);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  projects '%s': wanted line %d '%s', got %d '%s'\n", text, line, part, e.line, ok ? "(parsed)" : e.msg);
}

static void test_roots_parse(void)
{
    ProjectError e;
    CHECK(roots_parse(&roots_t, "", 0, &e) && roots_t.n == 0);
    CHECK(roots_parse(&roots_t, "/a\n/b c\n", 8, &e) && roots_t.n == 2 && strcmp(roots_t.path[1], "/b c") == 0);
    roots_bad("a\n", 1, "absolute path");
    roots_bad("/a\n\n", 2, "absolute path");
    roots_bad("/a/\n", 1, "absolute path");
    roots_bad("/a\t\n", 1, "absolute path");
    roots_bad("/a", 1, "no newline");
    roots_bad("/a\n/b\n/a\n", 3, "duplicate root /a");
    char text[PROJECT_LINE_MAX + 64];
    // a line of PROJECT_LINE_MAX bytes is a line limit error, shorter is a root limit error
    memset(text, 'a', sizeof text);
    text[0] = '/';
    text[PROJECT_LINE_MAX + 1] = '\n';
    text[PROJECT_LINE_MAX + 2] = '\0';
    roots_bad(text, 1, "limit is 8192");
    text[PROJECT_ROOT_MAX + 1] = '\n';
    text[PROJECT_ROOT_MAX + 2] = '\0';
    roots_bad(text, 1, "over 3000");
    text[PROJECT_ROOT_MAX] = '\n';
    text[PROJECT_ROOT_MAX + 1] = '\0';
    CHECK(roots_parse(&roots_t, text, PROJECT_ROOT_MAX + 1, &e) && roots_t.n == 1);
    char two[] = "/a\0b\n";
    CHECK(!roots_parse(&roots_t, two, sizeof two - 1, &e) && e.line == 1 && strstr(e.msg, "NUL") != nullptr);
    // 64 roots fit, a 65th does not
    static char many[(ROOTS_MAX + 1) * 8];
    size_t len = 0;
    for (size_t i = 0; i < ROOTS_MAX; i++) len += (size_t)snprintf(many + len, 16, "/r%zu\n", i);
    CHECK(roots_parse(&roots_t, many, len, &e) && roots_t.n == ROOTS_MAX);
    len += (size_t)snprintf(many + len, 16, "/over\n");
    CHECK(!roots_parse(&roots_t, many, len, &e) && e.line == (int)ROOTS_MAX + 1 && strstr(e.msg, "too many roots") != nullptr);
    // the file limit
    static char big[ROOTS_FILE_MAX + 2];
    memset(big, '\n', sizeof big);
    CHECK(!roots_parse(&roots_t, big, ROOTS_FILE_MAX + 1, &e) && e.line == 0 && strstr(e.msg, "limit is 262144") != nullptr);
    CHECK(!roots_parse(&roots_t, big, ROOTS_FILE_MAX, &e) && e.line == 1);
}

static void test_projects_parse(void)
{
    ProjectError e;
    CHECK(projects_parse(&projects_t, "", 0, true, &e) && projects_t.n == 0);
    const char *good = "github.com/o/n /a b/c git\n- /d fossil\nh.test/x /e zit\n";
    CHECK(projects_parse(&projects_t, good, strlen(good), true, &e) && projects_t.n == 3);
    CHECK(strcmp(projects_t.e[0].path, "/a b/c") == 0 && projects_t.e[0].kind == KIND_GIT);
    CHECK(projects_t.e[1].key[0] == '\0' && projects_t.e[1].kind == KIND_FOSSIL && projects_t.e[2].kind == KIND_ZIT);
    const char *set = "github.com/o/n /a b\nh.test/x /e\n";
    CHECK(projects_parse(&projects_t, set, strlen(set), false, &e) && projects_t.n == 2);
    CHECK(strcmp(projects_t.e[0].path, "/a b") == 0 && projects_t.e[0].kind == KIND_NONE);
    projects_bad("x\n", true, 1, "expected 'KEY PATH KIND'");
    projects_bad("a/b /x\n", true, 1, "expected 'KEY PATH KIND'");
    projects_bad("x\n", false, 1, "expected 'KEY PATH'");
    projects_bad("a/b /x svn\n", true, 1, "unknown kind 'svn'");
    projects_bad("a/b /x Git\n", true, 1, "unknown kind 'Git'");
    projects_bad("- /x git\n", false, 1, "not a remote key");
    projects_bad("-  /x\n", false, 1, "not a remote key");
    projects_bad("GitHub.com/o /x git\n", true, 1, "not a remote key");
    projects_bad("a/b x git\n", true, 1, "a path is absolute");
    projects_bad("a/b /x/ git\n", true, 1, "a path is absolute");
    projects_bad("a/b / git\nx\n", true, 2, "expected");
    projects_bad("a/b /x git\na/c /x fossil\n", true, 2, "duplicate path /x");
    projects_bad("a/b /x git", true, 1, "no newline");
    projects_bad("a/b /x\x01y git\n", true, 1, "a path is absolute");
    // the text buffer fills before the entry limit when the paths are long
    static Projects fill;
    char longp[PROJECT_PATH_MAX];
    memset(longp, 'a', sizeof longp);
    longp[0] = '/';
    longp[PROJECT_PATH_MAX - 1] = '\0';
    uint32_t added = 0;
    char num[16];
    for (;; added++) {
        memcpy(longp + 1, num, (size_t)snprintf(num, sizeof num, "%07u", added));
        if (projects_add(&fill, "", longp, KIND_GIT) != ADD_OK) break;
    }
    CHECK(added > 400 && added < PROJECT_ENTRY_MAX && fill.n == added);
    static char many[PROJECT_FILE_MAX + 16];
    char num_line[64];
    size_t len = 0;
    for (uint32_t i = 0; i <= PROJECT_ENTRY_MAX; i++) len += (size_t)snprintf(many + len, 64, "- /p%u git\n", i);
    CHECK(!projects_parse(&projects_t, many, len, true, &e) && e.line == (int)PROJECT_ENTRY_MAX + 1
        && strstr(e.msg, "too many entries") != nullptr);
    len -= (size_t)snprintf(num_line, sizeof num_line, "- /p%u git\n", PROJECT_ENTRY_MAX);
    CHECK(projects_parse(&projects_t, many, len, true, &e) && projects_t.n == PROJECT_ENTRY_MAX);
    static char over[PROJECT_FILE_MAX + 2];
    memset(over, '\n', sizeof over);
    CHECK(!projects_parse(&projects_t, over, PROJECT_FILE_MAX + 1, true, &e) && e.line == 0 && strstr(e.msg, "limit is 1048576") != nullptr);
}

// ---- projects: reading and writing files ---------------------------------------

static char pfile[256];

static void pfile_put(const char *text, size_t len)
{
    int fd = open(pfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
    CHECK(fd >= 0 && write(fd, text, len) == (ssize_t)len);
    close(fd);
}

static int pr_read(void)
{
    char buf[16];
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(pfile, buf, 8, &len, &err);
    return r == READ_OK && len == 5 && strcmp(buf, "hello") == 0 ? 0 : 1;
}

static int pr_read_fails(void)
{
    char buf[16];
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(pfile, buf, 8, &len, &err);
    return r == READ_FAILED && err == EIO ? 0 : 1;
}

static int pr_open_fails(void)
{
    char buf[16];
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(pfile, buf, 8, &len, &err);
    return r == READ_FAILED && err == EACCES ? 0 : 1;
}

static void test_project_files(void)
{
    char dir[] = "/tmp/suit-unit-proj.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    snprintf(pfile, sizeof pfile, "%s/f", dir);
    char buf[16];
    size_t len = 99;
    int err = 0;
    CHECK(project_read_file(pfile, buf, 8, &len, &err) == READ_MISSING && len == 0);
    pfile_put("hello", 5);
    CHECK(project_read_file(pfile, buf, 8, &len, &err) == READ_OK && len == 5 && strcmp(buf, "hello") == 0);
    pfile_put("12345678", 8);
    CHECK(project_read_file(pfile, buf, 8, &len, &err) == READ_OK && len == 8 && buf[8] == '\0');
    pfile_put("123456789", 9);
    CHECK(project_read_file(pfile, buf, 8, &len, &err) == READ_BIG);
    pfile_put("", 0);
    CHECK(project_read_file(pfile, buf, 8, &len, &err) == READ_OK && len == 0 && buf[0] == '\0');
    pfile_put("hello", 5);
    CHECK(in_child("read:1:EINTR", pr_read) == 0);
    CHECK(in_child("read:1:EIO", pr_read_fails) == 0);
    CHECK(in_child("open:1:EACCES", pr_open_fails) == 0);

    // roots and projects: write, load, add, remove, find
    Roots r;
    ProjectError e;
    r.n = 0;
    CHECK(roots_add(&r, "/b") == ADD_OK && roots_add(&r, "/a c") == ADD_OK && roots_add(&r, "/b") == ADD_DUPLICATE);
    CHECK(roots_write(&r, pfile) == 0);
    Roots r2;
    CHECK(roots_load(&r2, pfile, &e) && r2.n == 2 && strcmp(r2.path[0], "/b") == 0);
    CHECK(roots_remove(&r2, "/b") && r2.n == 1 && strcmp(r2.path[0], "/a c") == 0 && !roots_remove(&r2, "/b"));
    CHECK(roots_write(&r2, "/nonexistent-dir/f") != 0);
    pfile_put("relative\n", 9);
    CHECK(!roots_load(&r2, pfile, &e) && e.line == 1 && r2.n == 0);
    CHECK(unlink(pfile) == 0 && roots_load(&r2, pfile, &e) && r2.n == 0);
    CHECK(mkdir(pfile, 0700) == 0 && !roots_load(&r2, pfile, &e) && e.line == 0 && strstr(e.msg, "cannot read") != nullptr);
    CHECK(!projects_load(&projects_t, pfile, true, &e) && e.line == 0 && strstr(e.msg, "cannot read") != nullptr);
    CHECK(rmdir(pfile) == 0);
    CHECK(projects_load(&projects_t, pfile, true, &e) && projects_t.n == 0);
    static char bigtext[PROJECT_FILE_MAX + 2];
    memset(bigtext, '\n', sizeof bigtext);
    pfile_put(bigtext, PROJECT_FILE_MAX + 1);
    CHECK(!projects_load(&projects_t, pfile, true, &e) && e.line == 0 && strstr(e.msg, "over the limit of 1048576") != nullptr);
    pfile_put(bigtext, ROOTS_FILE_MAX + 1);
    CHECK(!roots_load(&r2, pfile, &e) && e.line == 0 && strstr(e.msg, "over the limit of 262144") != nullptr);

    Projects *p = &projects_t;
    p->n = 0;
    p->used = 0;
    CHECK(projects_add(p, "b.test/x", "/z", KIND_FOSSIL) == ADD_OK && projects_add(p, "", "/a", KIND_ZIT) == ADD_OK);
    CHECK(projects_add(p, "c.test/x", "/a", KIND_GIT) == ADD_DUPLICATE);
    CHECK(projects_find(p, "/a") != nullptr && projects_find(p, "/a")->kind == KIND_ZIT && projects_find(p, "/q") == nullptr);
    CHECK(projects_write(p, pfile, true) == 0);
    Projects *q = &fill_t;
    CHECK(projects_load(q, pfile, true, &e) && q->n == 2 && strcmp(q->e[0].path, "/a") == 0 && q->e[0].key[0] == '\0');
    CHECK(strcmp(project_kind_name(q->e[0].kind), "zit") == 0 && strcmp(project_kind_name(q->e[1].kind), "fossil") == 0);
    CHECK(strcmp(project_kind_name(KIND_GIT), "git") == 0);
    CHECK(projects_remove(q, "/a") && q->n == 1 && !projects_remove(q, "/a") && strcmp(q->e[0].path, "/z") == 0);
    CHECK(projects_write(q, pfile, false) == 0);
    CHECK(projects_write(q, "/nonexistent-dir/f", true) != 0);
    // a list too big for the file: 300 entries of 4000-byte paths
    char longp[PROJECT_PATH_MAX];
    memset(longp, 'a', sizeof longp);
    longp[0] = '/';
    longp[4000] = '\0';
    p->n = 0;
    p->used = 0;
    char num[16];
    for (int i = 0; i < 300; i++) {
        memcpy(longp + 1, num, (size_t)snprintf(num, sizeof num, "%06d", i));
        CHECK(projects_add(p, "k.test/x", longp, KIND_GIT) == ADD_OK);
    }
    CHECK(projects_write(p, pfile, true) == EFBIG);
    unlink(pfile);
    rmdir(dir);
}

// ---- lint -------------------------------------------------------------------

static LintRules lrules;
static LintRules lnone;

static bool lint_refused(const char *line)
{
    return lint_line(&lnone, line, strlen(line)) != nullptr;
}

static void test_lint_refused_lines(void)
{
    static const char *const refused[] = {
        "-----BEGIN RSA PRIVATE KEY-----", "x -----BEGIN PRIVATE KEY-----",
        "AKIAIOSFODNN7EXAMPLE", "id: AKIAIOSFODNN7EXAMPLEXYZ",
        "k=ghp_abcdefghijklmnopqrst", "k=gho_abcdefghijklmnopqrst", "k=ghs_abcdefghijklmnop_rst",
        "k=github_pat_abcdefghijklmnopqrst",
        "sk-abcdefghijklmnopqrst", "use sk-proj-abc_def-ghi-jklmnop here",
        "xoxb-1234567890", "xoxp-abcdefghij", "xoxa-1234-567-89",
        "api_key = 'abcdefghijklmnopqrstuvwx'", "PASSWORD: \"Abcdefghijklmnopqrstuvwxyz0123\"",
        "GITHUB_TOKEN=abcdefghij0123456789abcd", "my_secret_value: abcdefghijklmnopqrstuvwxyz",
        "apikey=abcdefghijklmnopqrstuvwx", "api-key: abcdefghijklmnopqrstuvwx",
        "passwd = abcdefghijklmnopqrstuvwx", "ToKeN\t=\tabcdefghijklmnopqrstuvwxyz",
        "secret=aaaaaaaaaaaaaaaaaaaaaaaab", "secret=baaaaaaaaaaaaaaaaaaaaaaaa", "token==abcdefghijklmnopqrstuvwxyz",
        "secret_tokenizer = abcdefghijklmnopqrstuvwxyz", "tokentoken = abcdefghijklmnopqrstuvwxyz",
        "token short and then token = abcdefghijklmnopqrstuvwxyz",
        "Co-Authored-By: someone", "Generated with a tool", "GENERATED BY AI", "claude-session: x",
        "Written by AI", "assisted by ai", "xx co-authored-by:",
        "my-token-v2: abcdefghijklmnopqrstuvwxyz", "secret = abcdefghij_klmnopqrstuvwxyz",
    };
    for (size_t i = 0; i < sizeof refused / sizeof refused[0]; i++) {
        CHECK(lint_refused(refused[i]));
        if (!lint_refused(refused[i])) printf("  was not refused: %s\n", refused[i]);
    }
    static const char *const allowed[] = {
        "", "token", "token=", "token:", "secret = ", "password = '", "sk-abcdefghijklmnopqrs",
        "ghp_abcdefghijklmnopqrs", "gho_abcdefghijklmnopqrs", "github_pat_abcdefghijklmnopqrs",
        "xoxb-123456789", "AKIAIOSFODNN7EXAMPL", "AKIAiosfodnn7example01", "sK-abcdefghijklmnopqrstuvw",
        "token = $TOKEN", "password: <your password>", "token: {{ secrets.X }}", "password=${PASSWORD}",
        "token = abcdefghijklmnopqrstuvw", "the token is expired and the password: please enter something",
        "secret: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "token = '----------------------------'",
        "-----BEGIN CERTIFICATE-----", "PRIVATE KEY----- -----BEGIN", "-----BEGIN PRIVATE KEY",
        "co-authored by", "generated by hand", "secret_tokenizer = x", "token is here; no value: x",
        "AKIAABCDEFGHIJKLMNO:", "AKIAABCDEFGHIJKLMNO-", "ghp_abcdefghij012345678-", "sk-abcdefghij012345678.xyz",
    };
    for (size_t i = 0; i < sizeof allowed / sizeof allowed[0]; i++) {
        CHECK(!lint_refused(allowed[i]));
        if (lint_refused(allowed[i])) printf("  was refused: %s\n", allowed[i]);
    }
    CHECK(strcmp(lint_line(&lnone, "AKIAIOSFODNN7EXAMPLE", 20), "token-shaped value") == 0);
    CHECK(strcmp(lint_line(&lnone, "generated with", 14), "attribution text") == 0);
    CHECK(lint_line(&lnone, "AKIAIOSFODNN7EXAMPLE", 19) == nullptr);
}

static bool lint_rules(const char *text, LintError *e)
{
    return lint_rules_parse(&lrules, text, strlen(text), e);
}

static void lint_rules_error(const char *text, int line, const char *part)
{
    LintError e = {0, 0, ""};
    bool ok = lint_rules(text, &e);
    CHECK(!ok && e.line == line && strstr(e.msg, part) != nullptr && lrules.n_allow == 0 && lrules.n_forbid == 0);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr) printf("  rules: %s -> %d %s\n", text, e.line, e.msg);
}

static void test_lint_rules(void)
{
    LintError e;
    CHECK(lint_rules("", &e) && lrules.n_allow == 0 && lrules.n_forbid == 0);
    CHECK(lint_rules("allow .x\nallow x/.y\n", &e) && lrules.n_allow == 2);
    CHECK(lint_rules("allow docs/example.md\nforbid Internal-Only\nforbid two  words\nallow a b/c\n", &e));
    CHECK(lrules.n_allow == 2 && strcmp(lrules.allow[0], "docs/example.md") == 0 && strcmp(lrules.allow[1], "a b/c") == 0);
    CHECK(lrules.n_forbid == 2 && strcmp(lrules.forbid[0], "internal-only") == 0);
    CHECK(lint_allowed(&lrules, "docs/example.md") && !lint_allowed(&lrules, "docs/example.mdx") && lint_allowed(&lrules, "a b/c"));
    CHECK(strcmp(lint_line(&lrules, "see INTERNAL-only", 17), "text this wardrobe forbids") == 0);
    CHECK(lint_line(&lrules, "two words", 9) == nullptr && lint_line(&lrules, "a TWO  WORDS b", 14) != nullptr);
    lint_rules_error("allow x", 1, "no newline");
    lint_rules_error("allow x\nforbid y", 2, "no newline");
    lint_rules_error("\n", 1, "expected");
    lint_rules_error("# note\n", 1, "expected");
    lint_rules_error("allow\n", 1, "expected");
    lint_rules_error("allow \n", 1, "needs an argument");
    lint_rules_error("forbid \n", 1, "needs an argument");
    lint_rules_error("deny x\n", 1, "expected");
    lint_rules_error("allow  x\n", 1, "no space at either end");
    lint_rules_error("allow x \n", 1, "no space at either end");
    lint_rules_error("allow /x\n", 1, "relative");
    lint_rules_error("allow x/\n", 1, "relative");
    lint_rules_error("allow x//y\n", 1, "relative");
    lint_rules_error("allow ./x\n", 1, "relative");
    lint_rules_error("allow x/../y\n", 1, "relative");
    lint_rules_error("allow x/.\n", 1, "relative");
    lint_rules_error("allow ..\n", 1, "relative");
    lint_rules_error("allow x\tz\n", 1, "relative");
    lint_rules_error("allow x\nallow x\n", 2, "duplicate allow x");
    lint_rules_error("forbid  x\n", 1, "no space at either end");
    lint_rules_error("forbid x \n", 1, "no space at either end");
    lint_rules_error("forbid a\x7f" "b\n", 1, "no control byte");
    lint_rules_error("forbid a\x01" "b\n", 1, "no control byte");
    lint_rules_error("forbid Abc\nforbid aBC\n", 2, "duplicate forbid abc");
    CHECK(!lint_rules_parse(&lrules, "allow a\0b\n", 10, &e) && e.line == 1 && strstr(e.msg, "NUL") != nullptr);
    // limits
    static char big[LINT_RULES_FILE_MAX + 64];
    memset(big, 'x', sizeof big);
    memcpy(big, "forbid ", 7);
    big[LINT_TEXT_MAX + 8] = '\n';
    CHECK(!lint_rules_parse(&lrules, big, LINT_TEXT_MAX + 9, &e) && e.line == 1 && strstr(e.msg, "over 200 bytes") != nullptr);
    big[LINT_TEXT_MAX + 7] = '\n';
    CHECK(lint_rules_parse(&lrules, big, LINT_TEXT_MAX + 8, &e) && lrules.n_forbid == 1);
    memset(big, 'x', sizeof big);
    memcpy(big, "allow ", 6);
    big[LINT_RULES_LINE_MAX + 1] = '\n';
    CHECK(!lint_rules_parse(&lrules, big, LINT_RULES_LINE_MAX + 2, &e) && e.line == 1 && strstr(e.msg, "limit is 1024") != nullptr);
    memset(big, '\n', sizeof big);
    CHECK(!lint_rules_parse(&lrules, big, LINT_RULES_FILE_MAX + 1, &e) && e.line == 0 && strstr(e.msg, "limit is") != nullptr);
    size_t off = 0;
    for (uint32_t i = 0; i <= LINT_ALLOW_MAX; i++) {
        off += (size_t)snprintf(big + off, 16, "allow f%u\n", i);
        if (i == LINT_ALLOW_MAX - 1) CHECK(lint_rules_parse(&lrules, big, off, &e) && lrules.n_allow == LINT_ALLOW_MAX);
    }
    CHECK(!lint_rules_parse(&lrules, big, off, &e) && e.line == (int)LINT_ALLOW_MAX + 1 && strstr(e.msg, "too many allow") != nullptr);
    off = 0;
    for (uint32_t i = 0; i <= LINT_FORBID_MAX; i++) {
        off += (size_t)snprintf(big + off, 16, "forbid f%u\n", i);
        if (i == LINT_FORBID_MAX - 1) CHECK(lint_rules_parse(&lrules, big, off, &e) && lrules.n_forbid == LINT_FORBID_MAX);
    }
    CHECK(!lint_rules_parse(&lrules, big, off, &e) && e.line == (int)LINT_FORBID_MAX + 1 && strstr(e.msg, "too many forbid") != nullptr);
}

typedef struct {
    size_t n;
    size_t line[8];
    const char *what[8];
} Found;

static void found_add(void *state, size_t line, const char *what)
{
    Found *f = state;
    f->line[f->n] = line;
    f->what[f->n] = what;
    f->n++;
}

static size_t scan(const char *text, size_t len, Found *f)
{
    f->n = 0;
    return lint_text(&lnone, false, text, len, found_add, f);
}

static void test_lint_text(void)
{
    Found f;
    const char *t = "fine\nGenerated with x\nfine\nsk-abcdefghijklmnopqrst";
    CHECK(scan(t, strlen(t), &f) == 2 && f.n == 2 && f.line[0] == 2 && f.line[1] == 4);
    CHECK(strcmp(f.what[0], "attribution text") == 0 && strcmp(f.what[1], "token-shaped value") == 0);
    t = "fine\r\nfine\r\n";
    CHECK(scan(t, strlen(t), &f) == 0);
    CHECK(scan("", 0, &f) == 0);
    t = "generated with\n";
    f.n = 0;
    CHECK(lint_text(&lnone, true, t, strlen(t), found_add, &f) == 0 && f.n == 0);
    t = "\n\nco-authored-by: a\n";
    CHECK(scan(t, strlen(t), &f) == 1 && f.line[0] == 3);
    // A NUL in the first 8 KiB makes the file binary; one after that does not.
    t = "generated with\0x\n";
    CHECK(scan(t, 16, &f) == 0);
    static char big[LINT_BINARY_PROBE + 64];
    memset(big, 'a', sizeof big);
    memcpy(big, "generated with\n", 15);
    big[LINT_BINARY_PROBE - 1] = '\0';
    CHECK(scan(big, sizeof big, &f) == 0);
    big[LINT_BINARY_PROBE - 1] = 'a';
    big[LINT_BINARY_PROBE] = '\0';
    CHECK(scan(big, sizeof big, &f) == 1 && f.line[0] == 1);
    // A line of 64 KiB is read; one byte more is refused, and the text after it still is.
    static char line[LINT_LINE_MAX + 64];
    memset(line, 'a', sizeof line);
    line[LINT_LINE_MAX] = '\n';
    memcpy(line + LINT_LINE_MAX + 1, "generated with", 14);
    CHECK(scan(line, LINT_LINE_MAX + 1, &f) == 0);
    CHECK(scan(line, LINT_LINE_MAX + 15, &f) == 1 && f.line[0] == 2);
    line[LINT_LINE_MAX] = 'a';
    line[LINT_LINE_MAX + 1] = '\n';
    CHECK(scan(line, LINT_LINE_MAX + 2, &f) == 1 && f.line[0] == 1 && strstr(f.what[0], "64 KiB") != nullptr);
    f.n = 0;
    CHECK(lint_text(&lnone, true, line, LINT_LINE_MAX + 2, found_add, &f) == 1 && f.line[0] == 1);
    CHECK(lint_has_header("---\nname: x\n", 12) && lint_has_header("---\r\nx", 6) && lint_has_header("---", 3));
    CHECK(!lint_has_header("", 0) && !lint_has_header("\n---\n", 5) && !lint_has_header("----\n", 5));
    CHECK(!lint_has_header("--\n", 3) && !lint_has_header("# x\n---\n", 8) && !lint_has_header("---x\n", 5));
    CHECK(!lint_has_header("\r\n", 2));
}

static char lfile[256];

static void lfile_put(const char *text, size_t len)
{
    int fd = open(lfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
    CHECK(fd >= 0 && write(fd, text, len) == (ssize_t)len);
    close(fd);
}

static int lr_load(void)
{
    LintError e;
    return lint_rules_load(&lrules, lfile, &e) && lrules.n_allow == 1 ? 0 : 1;
}

static int lr_load_fails(void)
{
    LintError e = {0, 0, ""};
    return !lint_rules_load(&lrules, lfile, &e) && strstr(e.msg, "cannot read") != nullptr ? 0 : 1;
}

static int lr_open_fails(void)
{
    LintError e = {0, 0, ""};
    return !lint_rules_load(&lrules, lfile, &e) && strstr(e.msg, "cannot open") != nullptr ? 0 : 1;
}

static void test_lint_load(void)
{
    LintError e = {0, 0, ""};
    snprintf(lfile, sizeof lfile, "/tmp/suit-unit-lint.%d", (int)getpid());
    unlink(lfile);
    CHECK(lint_rules_load(&lrules, lfile, &e) && lrules.n_allow == 0 && lrules.n_forbid == 0);
    lfile_put("allow a/b\nforbid x\n", 19);
    CHECK(lint_rules_load(&lrules, lfile, &e) && lrules.n_allow == 1 && lrules.n_forbid == 1);
    lfile_put("allow a/b\nforbid x", 18);
    CHECK(!lint_rules_load(&lrules, lfile, &e) && e.line == 2 && lrules.n_allow == 0 && lrules.n_forbid == 0);
    static char big[LINT_RULES_FILE_MAX + 2];
    memset(big, '\n', sizeof big);
    lfile_put(big, LINT_RULES_FILE_MAX + 1);
    CHECK(!lint_rules_load(&lrules, lfile, &e) && e.line == 0 && strstr(e.msg, "over the limit") != nullptr);
    lfile_put("allow a/b\n", 10);
    CHECK(in_child("read:1:EINTR", lr_load) == 0);
    CHECK(in_child("read:1:EIO", lr_load_fails) == 0);
    CHECK(in_child("open:1:EACCES", lr_open_fails) == 0);
    unlink(lfile);
}

// END

static const char PLIST_RUN[] =
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
    "<plist version=\"1.0\">\n<dict>\n"
    "\t<key>Label</key>\n\t<string>app.zeitforge.suit.run</string>\n"
    "\t<key>ProgramArguments</key>\n\t<array>\n\t\t<string>/opt/suit/suit-run</string>\n\t</array>\n"
    "\t<key>StartInterval</key>\n\t<integer>60</integer>\n"
    "\t<key>RunAtLoad</key>\n\t<false/>\n"
    "\t<key>ProcessType</key>\n\t<string>Background</string>\n"
    "\t<key>LowPriorityIO</key>\n\t<true/>\n"
    "\t<key>StandardErrorPath</key>\n\t<string>/home/u/.suit/log/run.err</string>\n"
    "</dict>\n</plist>\n";

static char text[INSTALL_TEXT_MAX];

static bool text_is(ssize_t len, const char *want)
{
    return len == (ssize_t)strlen(want) && memcmp(text, want, (size_t)len) == 0;
}

static void test_install_plist(void)
{
    InstallSpec s = {"/opt/suit/suit", "/opt/suit/suit-run", "/home/u/.suit", false};
    CHECK(text_is(install_plist(text, sizeof text, &s, TIMER_RUN), PLIST_RUN));
    // tend starts `suit tend`, every hour, and a SUIT_HOME other than the default is passed on.
    s.home = "/data/suit home";
    s.home_set = true;
    ssize_t n = install_plist(text, sizeof text, &s, TIMER_TEND);
    CHECK(text_is(n, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
        "<plist version=\"1.0\">\n<dict>\n"
        "\t<key>Label</key>\n\t<string>app.zeitforge.suit.tend</string>\n"
        "\t<key>ProgramArguments</key>\n\t<array>\n\t\t<string>/opt/suit/suit</string>\n"
        "\t\t<string>tend</string>\n\t</array>\n"
        "\t<key>StartInterval</key>\n\t<integer>3600</integer>\n"
        "\t<key>RunAtLoad</key>\n\t<false/>\n"
        "\t<key>ProcessType</key>\n\t<string>Background</string>\n"
        "\t<key>LowPriorityIO</key>\n\t<true/>\n"
        "\t<key>EnvironmentVariables</key>\n\t<dict>\n\t\t<key>SUIT_HOME</key>\n"
        "\t\t<string>/data/suit home</string>\n\t</dict>\n"
        "\t<key>StandardErrorPath</key>\n\t<string>/data/suit home/log/tend.err</string>\n"
        "</dict>\n</plist>\n"));
    // Every character XML needs escaped is, and a space needs nothing.
    InstallSpec w = {"/a b/s&<>\"'", "/a b/r&<>\"'", "/h", false};
    n = install_plist(text, sizeof text, &w, TIMER_RUN);
    CHECK(n > 0 && strstr(text, "<string>/a b/r&amp;&lt;&gt;&quot;&apos;</string>") != nullptr);
    n = install_plist(text, sizeof text, &w, TIMER_TEND);
    CHECK(n > 0 && strstr(text, "<string>/a b/s&amp;&lt;&gt;&quot;&apos;</string>") != nullptr);
}

static void test_install_systemd(void)
{
    InstallSpec s = {"/opt/suit/suit", "/opt/suit/suit-run", "/home/u/.suit", false};
    CHECK(text_is(install_service(text, sizeof text, &s, TIMER_RUN),
        "[Unit]\nDescription=suit: look for changes and apply them\n\n"
        "[Service]\nType=oneshot\nExecStart=\"/opt/suit/suit-run\"\n"));
    CHECK(text_is(install_service(text, sizeof text, &s, TIMER_TEND),
        "[Unit]\nDescription=suit: tend every wardrobe\n\n"
        "[Service]\nType=oneshot\nExecStart=\"/opt/suit/suit\" tend\n"));
    CHECK(text_is(install_timer(text, sizeof text, &s, TIMER_RUN),
        "[Unit]\nDescription=suit: every minute\n\n"
        "[Timer]\nOnBootSec=60s\nOnUnitActiveSec=60s\nAccuracySec=1s\n\n"
        "[Install]\nWantedBy=timers.target\n"));
    CHECK(text_is(install_timer(text, sizeof text, &s, TIMER_TEND),
        "[Unit]\nDescription=suit: every hour\n\n"
        "[Timer]\nOnBootSec=3600s\nOnUnitActiveSec=3600s\nPersistent=true\n\n"
        "[Install]\nWantedBy=timers.target\n"));
    // A SUIT_HOME other than the default is passed on; a space, a quote, a
    // backslash, a percent sign and a dollar sign are written the way systemd reads them.
    InstallSpec w = {"/a b/s", "/a b/r\"q\\%$", "/data/su it\"%", true};
    ssize_t n = install_service(text, sizeof text, &w, TIMER_RUN);
    CHECK(text_is(n, "[Unit]\nDescription=suit: look for changes and apply them\n\n"
        "[Service]\nType=oneshot\nExecStart=\"/a b/r\\\"q\\\\%%$$\"\n"
        "Environment=\"SUIT_HOME=/data/su it\\\"%%\"\n"));
    n = install_service(text, sizeof text, &w, TIMER_TEND);
    CHECK(n > 0 && strstr(text, "ExecStart=\"/a b/s\" tend\n") != nullptr);
}

static void test_install_refusals(void)
{
    char longp[INSTALL_PATH_MAX + 3];
    memset(longp, 'a', sizeof longp - 1);
    longp[0] = '/';
    longp[sizeof longp - 1] = '\0';
    InstallSpec ok = {"/s", "/r", "/h", false};
    CHECK(install_spec_ok(&ok));
    InstallSpec bad[] = {
        {"s", "/r", "/h", false}, {"/s", "r", "/h", false}, {"/s", "/r", "h", false},
        {"/s\n", "/r", "/h", false}, {"/s", "/r\n/x", "/h", false}, {"/s", "/r", "/h\r", false},
        {"/s", "/r", "/h\x7f", false}, {nullptr, "/r", "/h", false}, {"/s", "/r", "", false},
        {longp, "/r", "/h", false}, {"/s", "/r", longp, true},
    };
    for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
        CHECK(!install_spec_ok(&bad[i]));
        CHECK(install_plist(text, sizeof text, &bad[i], TIMER_RUN) == -1);
        CHECK(install_service(text, sizeof text, &bad[i], TIMER_RUN) == -1);
        CHECK(install_timer(text, sizeof text, &bad[i], TIMER_TEND) == -1);
    }
    // The longest path that is allowed, in the character that grows most, fits.
    char edge[INSTALL_PATH_MAX + 1];
    memset(edge, '\'', sizeof edge - 1);
    edge[0] = '/';
    edge[sizeof edge - 1] = '\0';
    InstallSpec big = {edge, edge, edge, true};
    CHECK(install_plist(text, sizeof text, &big, TIMER_RUN) > 0);
    CHECK(install_service(text, sizeof text, &big, TIMER_RUN) > 0);
}

static void test_install_platform(void)
{
    unsetenv("SUIT_PLATFORM");
    unsetenv("SUIT_LOADER");
    Manager here = platform_manager();
#ifdef __APPLE__
    CHECK(here == MANAGER_LAUNCHD && strcmp(platform_loader(), "/bin/launchctl") == 0);
#else
    CHECK(here == MANAGER_SYSTEMD && strcmp(platform_loader(), "/usr/bin/systemctl") == 0);
#endif
    setenv("SUIT_PLATFORM", "linux", 1);
    CHECK(platform_manager() == MANAGER_SYSTEMD && strcmp(platform_loader(), "/usr/bin/systemctl") == 0);
    setenv("SUIT_PLATFORM", "macos", 1);
    CHECK(platform_manager() == MANAGER_LAUNCHD && strcmp(platform_loader(), "/bin/launchctl") == 0);
    setenv("SUIT_LOADER", "/tmp/fake-loader", 1);
    CHECK(strcmp(platform_loader(), "/tmp/fake-loader") == 0);
    setenv("SUIT_LOADER", "", 1);
    CHECK(strcmp(platform_loader(), "/bin/launchctl") == 0);
    unsetenv("SUIT_PLATFORM");
    unsetenv("SUIT_LOADER");
    CHECK(platform_uid() == (unsigned)getuid());
    CHECK(strcmp(install_label(TIMER_RUN), "app.zeitforge.suit.run") == 0);
    CHECK(strcmp(install_label(TIMER_TEND), "app.zeitforge.suit.tend") == 0);
}

// ---- needs ----------------------------------------------------------------

static char ndir[64];
static char npath[128];
static DoneTest ntest;

static bool done_ok(const char *s)
{
    char why[DONE_WHY_MAX];
    return done_parse(&ntest, "/home/u", s, why, sizeof why);
}

static const char *done_why(const char *s)
{
    static char why[DONE_WHY_MAX];
    why[0] = '\0';
    (void)done_parse(&ntest, "/home/u", s, why, sizeof why);
    return why;
}

static void nput(const char *name, const char *data, size_t n)
{
    snprintf(npath, sizeof npath, "%s/%s", ndir, name);
    int fd = open(npath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
    CHECK(fd >= 0 && write(fd, data, n) == (ssize_t)n);
    close(fd);
}

// The state of "NDIR/NAME contains TEXT", with the reason in WHY.
static NeedState ncontains(const char *name, const char *want, char *why)
{
    char line[256];
    snprintf(line, sizeof line, "%s/%s contains \"%s\"", ndir, name, want);
    why[0] = '\0';
    char scratch[DONE_WHY_MAX];
    CHECK(done_parse(&ntest, "", line, scratch, sizeof scratch));
    return done_eval(&ntest, why, DONE_WHY_MAX);
}

static void test_done_parse(void)
{
    CHECK(done_ok("/a/b exists") && ntest.kind == DONE_EXISTS && strcmp(ntest.path, "/a/b") == 0);
    CHECK(done_ok("~/x/y exists") && strcmp(ntest.path, "/home/u/x/y") == 0);
    CHECK(done_ok("~ exists") && strcmp(ntest.path, "/home/u") == 0);
    CHECK(done_ok("/a contains \"slots/statusline\"") && ntest.kind == DONE_CONTAINS && ntest.text_len == 16 &&
          memcmp(ntest.text, "slots/statusline", 16) == 0);
    CHECK(done_ok("/a contains \"two words\"") && ntest.text_len == 9 && memcmp(ntest.text, "two words", 9) == 0);
    CHECK(done_ok("/a contains \"say \"hi\" now\"") && ntest.text_len == 12 && memcmp(ntest.text, "say \"hi\" now", 12) == 0);
    CHECK(done_ok("/a contains \"\"\"\"") && ntest.text_len == 2 && memcmp(ntest.text, "\"\"", 2) == 0);
    CHECK(done_ok("/a contains \" \"") && ntest.text_len == 1);

    CHECK(!done_ok("") && strstr(done_why(""), "expected PATH exists") != nullptr);
    CHECK(!done_ok("/a") && !done_ok(" exists") && !done_ok("/a  exists") && !done_ok("/a exist"));
    CHECK(!done_ok("/a exists ") && !done_ok("/a exists now") && !done_ok("/a Exists"));
    CHECK(!done_ok("/a contains x") && !done_ok("/a contains  \"x\""));
    CHECK(strstr(done_why("/a contains \"x\" junk"), "closing quote last") != nullptr);
    CHECK(strstr(done_why("/a contains \"x"), "closing quote last") != nullptr);
    CHECK(strstr(done_why("/a contains \""), "closing quote last") != nullptr);
    CHECK(strstr(done_why("/a contains \"\""), "TEXT is empty") != nullptr);
    CHECK(strstr(done_why("a/b exists"), "absolute") != nullptr);
    CHECK(strstr(done_why("./a exists"), "absolute") != nullptr);
    CHECK(strstr(done_why("~u/a exists"), "absolute") != nullptr);

    char big[DONE_PATH_MAX + 16];
    memset(big, 'x', sizeof big);
    big[0] = '/';
    memcpy(big + DONE_PATH_MAX, " exists", 8);
    CHECK(strstr(done_why(big), "longer than") != nullptr);
    memcpy(big + DONE_PATH_MAX - 1, " exists", 8);  // 4095 bytes of path: the most that fits
    CHECK(done_ok(big) && strlen(ntest.path) == DONE_PATH_MAX - 1);
    char why[DONE_WHY_MAX];
    CHECK(done_parse(&ntest, "/home/u", "~/x exists", why, sizeof why));
    char long_home[DONE_PATH_MAX];
    memset(long_home, 'h', sizeof long_home - 1);
    long_home[0] = '/';
    long_home[sizeof long_home - 1] = '\0';
    CHECK(!done_parse(&ntest, long_home, "~/x exists", why, sizeof why));
    CHECK(done_parse(&ntest, "", "~/x exists", why, sizeof why) && strcmp(ntest.path, "/x") == 0);
    CHECK(!done_parse(&ntest, "", "~ exists", why, sizeof why) && strstr(why, "absolute") != nullptr);

    CHECK(need_prompt_ok("needs/a.md") && need_prompt_ok("a") && need_prompt_ok("a/./b") && need_prompt_ok("a/..b") && need_prompt_ok("ab/.x") &&
          need_prompt_ok("a/b.."));
    CHECK(!need_prompt_ok("") && !need_prompt_ok("/a") && !need_prompt_ok("../x") && !need_prompt_ok("a/../b") &&
          !need_prompt_ok("a/..") && !need_prompt_ok(".."));
}

static int ne_stat(void) { char w[DONE_WHY_MAX]; return ncontains("f", "x", w) == NEED_UNKNOWN && strstr(w, "cannot look at the file: ") != nullptr ? 0 : 1; }
static int ne_open(void) { char w[DONE_WHY_MAX]; return ncontains("f", "x", w) == NEED_UNKNOWN && strstr(w, "cannot open the file: ") != nullptr ? 0 : 1; }
static int ne_read(void) { char w[DONE_WHY_MAX]; return ncontains("f", "x", w) == NEED_UNKNOWN && strstr(w, "cannot read the file: ") != nullptr ? 0 : 1; }
static int ne_retry(void) { char w[DONE_WHY_MAX]; return ncontains("f", "world", w) == NEED_DONE ? 0 : 1; }
static int ne_short(void) { char w[DONE_WHY_MAX]; return ncontains("f", "world", w) == NEED_DONE ? 0 : 1; }
static int ne_lstat(void)
{
    char w[DONE_WHY_MAX];
    char line[256];
    snprintf(line, sizeof line, "%s/f exists", ndir);
    if (!done_parse(&ntest, "", line, w, sizeof w)) return 1;
    return done_eval(&ntest, w, sizeof w) == NEED_UNKNOWN && strstr(w, "cannot look at the file: ") != nullptr ? 0 : 1;
}

static void test_done_eval(void)
{
    snprintf(ndir, sizeof ndir, "/tmp/suit-unit-need.XXXXXX");
    CHECK(mkdtemp(ndir) != nullptr);
    char w[DONE_WHY_MAX];
    char line[256];
    snprintf(line, sizeof line, "%s/f exists", ndir);
    CHECK(done_parse(&ntest, "", line, w, sizeof w) && done_eval(&ntest, w, sizeof w) == NEED_NOT_DONE);
    nput("f", "hello world", 11);
    CHECK(done_eval(&ntest, w, sizeof w) == NEED_DONE);
    snprintf(line, sizeof line, "%s exists", ndir);  // a folder
    CHECK(done_parse(&ntest, "", line, w, sizeof w) && done_eval(&ntest, w, sizeof w) == NEED_DONE);
    snprintf(line, sizeof line, "%s/dangling exists", ndir);  // a link whose target is gone
    snprintf(npath, sizeof npath, "%s/dangling", ndir);
    CHECK(symlink("/nonexistent-target", npath) == 0);
    CHECK(done_parse(&ntest, "", line, w, sizeof w) && done_eval(&ntest, w, sizeof w) == NEED_DONE);
    snprintf(line, sizeof line, "%s/f/below exists", ndir);  // under a file
    CHECK(done_parse(&ntest, "", line, w, sizeof w) && done_eval(&ntest, w, sizeof w) == NEED_NOT_DONE);

    CHECK(ncontains("f", "hello", w) == NEED_DONE);   // the very start
    CHECK(ncontains("f", "world", w) == NEED_DONE);   // the very end
    CHECK(ncontains("f", "hello world", w) == NEED_DONE);
    CHECK(ncontains("f", "o w", w) == NEED_DONE);
    CHECK(ncontains("f", "hello worlds", w) == NEED_NOT_DONE);
    CHECK(ncontains("f", "xhello", w) == NEED_NOT_DONE);
    CHECK(ncontains("f", "z", w) == NEED_NOT_DONE);
    nput("g", "xaa", 3);
    CHECK(ncontains("g", "ab", w) == NEED_NOT_DONE);  // the first byte matches at the last place it can
    nput("g", "aab", 3);
    CHECK(ncontains("g", "ab", w) == NEED_DONE);
    nput("g", "", 0);
    CHECK(ncontains("g", "a", w) == NEED_NOT_DONE);
    CHECK(ncontains("missing", "a", w) == NEED_NOT_DONE);
    CHECK(ncontains("f/below", "a", w) == NEED_NOT_DONE);
    CHECK(ncontains("dangling", "a", w) == NEED_NOT_DONE);
    snprintf(npath, sizeof npath, "%s/link", ndir);
    CHECK(symlink("f", npath) == 0 && ncontains("link", "world", w) == NEED_DONE);  // a link to a file is read through

    snprintf(npath, sizeof npath, "%s/dir", ndir);
    CHECK(mkdir(npath, 0700) == 0);
    CHECK(ncontains("dir", "a", w) == NEED_UNKNOWN && strcmp(w, "not a regular file") == 0);

    // a block boundary falls inside the text; the text is the last bytes, and the file is the most that is read
    static char big[DONE_FILE_MAX + 1];
    memset(big, 'a', sizeof big);
    memcpy(big + 65534, "NEEDLE", 6);
    nput("big", big, 65540);
    CHECK(ncontains("big", "NEEDLE", w) == NEED_DONE && ncontains("big", "aaNEEDLEa", w) == NEED_NOT_DONE);
    memcpy(big + DONE_FILE_MAX - 6, "NEEDLE", 6);
    nput("big", big, DONE_FILE_MAX);
    CHECK(ncontains("big", "aNEEDLE", w) == NEED_DONE);
    nput("big", big, DONE_FILE_MAX + 1);
    CHECK(ncontains("big", "aNEEDLE", w) == NEED_UNKNOWN && strcmp(w, "file is over 4 MiB") == 0);

    snprintf(npath, sizeof npath, "%s/f", ndir);
    CHECK(in_child("stat:1:EIO", ne_stat) == 0);
    CHECK(in_child("open:1:EACCES", ne_open) == 0);
    CHECK(in_child("read:1:EIO", ne_read) == 0);
    CHECK(in_child("read:1:EINTR", ne_retry) == 0);
    CHECK(in_child("read:1:short", ne_short) == 0);
    CHECK(in_child("lstat:1:EIO", ne_lstat) == 0);
    CHECK(nftw(ndir, nftw_remove, 16, FTW_DEPTH | FTW_PHYS) == 0);
}

// ---- session records: config keys, paths and rules --------------------------------

static void test_usage_paths(void)
{
    UsagePath p;
    CHECK(conf_path_parse(&p, "a.b[].c", true, false));
    CHECK(p.n == 4 && !p.each[0] && !p.each[1] && p.each[2] && !p.each[3]);
    CHECK(strcmp(p.key[0], "a") == 0 && strcmp(p.key[1], "b") == 0 && p.len[3] == 1 && p.key[3][0] == 'c');
    CHECK(conf_path_parse(&p, ".", true, true) && p.n == 0);
    CHECK(!conf_path_parse(&p, ".", true, false));
    CHECK(!conf_path_parse(&p, "a[]", false, false));
    CHECK(!conf_path_parse(&p, "a..b", true, false));
    CHECK(!conf_path_parse(&p, ".a", true, false));
    CHECK(!conf_path_parse(&p, "a.", true, false));
    CHECK(!conf_path_parse(&p, "[]", true, false));
    CHECK(!conf_path_parse(&p, "a[b", true, false));
    CHECK(!conf_path_parse(&p, "a]b", true, false));
    CHECK(!conf_path_parse(&p, "a[].b[].c[].d[].e[]", true, false));  // ten steps
    CHECK(conf_path_parse(&p, "a.b.c.d.e.f.g.h", true, false) && p.n == 8);
    CHECK(!conf_path_parse(&p, "a.b.c.d.e.f.g.h.i", true, false));
    CHECK(conf_path_parse(&p, "a.b.c.d.e.f.g[]", true, false) && p.n == 8);
    CHECK(!conf_path_parse(&p, "a.b.c.d.e.f.g.h[]", true, false));
    CHECK(conf_path_parse(&p, "abcdefghijklmnopqrstuvwxyzabcdef", true, false));  // 32 bytes
    CHECK(!conf_path_parse(&p, "abcdefghijklmnopqrstuvwxyzabcdefg", true, false));
}

static void test_usage_rule(void)
{
    UsageRule r;
    char msg[256];
    CHECK(conf_rule_parse(&r, USE_SKILL, "message.content[] where type=tool_use name=Skill name input.skill id id", msg, sizeof msg));
    CHECK(r.kind == USE_SKILL && r.in.n == 3 && r.nwhere == 2 && strcmp(r.where_value[1], "Skill") == 0);
    CHECK(r.name.n == 2 && r.name_list.n == 4 && r.name_list.each[2] && strcmp(r.name_list.key[3], "text") == 0);
    CHECK(!r.between && r.has_id && r.id.n == 1);
    CHECK(conf_rule_parse(&r, USE_COMMAND, ". where type=user name message.content between <command-name>/ </command-name>", msg, sizeof msg));
    CHECK(r.in.n == 0 && r.between && strcmp(r.a, "<command-name>/") == 0 && strcmp(r.b, "</command-name>") == 0 && !r.has_id);
    CHECK(conf_rule_parse(&r, USE_AGENT, "a name b between A B id c", msg, sizeof msg) && r.between && r.has_id);
    CHECK(conf_rule_parse(&r, USE_AGENT, "  a\twhere\tk=v=w   name\tb  ", msg, sizeof msg));
    CHECK(strcmp(r.where_value[0], "v=w") == 0);
    CHECK(conf_rule_parse(&r, USE_AGENT, "a \t name b", msg, sizeof msg));  // a space and a tab between words
    CHECK(strcmp(use_kind_name(USE_AGENT), "agent") == 0 && strcmp(use_kind_name(USE_COMMAND), "command") == 0);

    char long65[80];
    memset(long65, 'v', 65);
    long65[65] = '\0';
    char tx[400];
    static const struct {
        const char *tx;
        const char *part;
    } bad[] = {
        {"a..b name x", "not a path from the record's top"},
        {"a", "'name PATH' is missing"},
        {"a x", "'name PATH' is missing"},
        {"a where", "where needs at least one"},
        {"a where name x", "where needs at least one"},
        {"a where t=1 u=2 v=3 w=4 z=5 name x", "at most 4 where tests"},
        {"a where tool name x", "is not FIELD=VALUE"},
        {"a where t=1 x", "is not FIELD=VALUE"},
        {"a where a..b=1 name x", "not a path of field names in a where"},
        {"a where a[]=1 name x", "not a path of field names in a where"},
        {"a where t= name x", "must be 1 to 64 bytes"},
        {"a name", "name needs a path"},
        {"a name b[]", "name needs a path"},
        {"a name b between A", "between needs A and B"},
        {"a name b between", "between needs A and B"},
        {"a name b id", "id needs a path"},
        {"a name b id c[]", "id needs a path"},
        {"a name b extra", "unexpected 'extra'"},
        {"a name b id c extra", "unexpected 'extra'"},
        {"a name b between A B extra", "unexpected 'extra'"},
    };
    for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
        CHECK(!conf_rule_parse(&r, USE_AGENT, bad[i].tx, msg, sizeof msg));
        CHECK(strstr(msg, "use agent: ") == msg && strstr(msg, bad[i].part) != nullptr);
        if (strstr(msg, bad[i].part) == nullptr) printf("  rule '%s' gave '%s'\n", bad[i].tx, msg);
    }
    snprintf(tx, sizeof tx, "a where t=%s name x", long65);
    CHECK(!conf_rule_parse(&r, USE_SKILL, tx, msg, sizeof msg) && strstr(msg, "must be 1 to 64 bytes") != nullptr);
    snprintf(tx, sizeof tx, "a name b between %s B", long65);
    CHECK(!conf_rule_parse(&r, USE_SKILL, tx, msg, sizeof msg) && strstr(msg, "at most 64 bytes") != nullptr);
    snprintf(tx, sizeof tx, "a name b between A %s", long65);
    CHECK(!conf_rule_parse(&r, USE_SKILL, tx, msg, sizeof msg) && strstr(msg, "at most 64 bytes") != nullptr);
}

static void test_usage_keys(void)
{
    ConfError e;
    CHECK(parse("[harness c]\nsessions = ~/a/*/*.jsonl\nsessions = /x/y\nsession time = timestamp\nsession project = cwd\n"
                "use skill = message.content[] where type=tool_use name=Skill name input.skill id id\n"
                "use agent = . name a\nuse command = . where type=user name m between <a> </a>\n", &e));
    CHECK(conf.nentries == 7);
    CHECK(strcmp(conf.entries[0].key, "sessions") == 0 && strcmp(conf.entries[2].key, "session time") == 0);
    CHECK(strcmp(conf.entries[5].key, "use agent") == 0 && strcmp(conf.entries[6].val, ". where type=user name m between <a> </a>") == 0);
    CHECK(parse("[harness c]\nsession    time   =  a.b\nuse   skill  =   .   name   x\n", &e));
    CHECK(strcmp(conf.entries[1].key, "use skill") == 0);

    expect_error("[harness c]\nsessions = relative/x\n", 2, "takes an absolute path or one starting with ~/");
    expect_error("[harness c]\nsessions = ~x\n", 2, "takes an absolute path");
    expect_error("[harness c]\nsession time = a..b\n", 2, "takes a path of field names");
    expect_error("[harness c]\nsession project = a[]\n", 2, "takes a path of field names");
    expect_error("[harness c]\nsession time = a\nsession time = b\n", 3, "duplicate key 'session time'");
    expect_error("[harness c]\nsession project = a\nsession project = b\n", 3, "duplicate key");
    expect_error("[harness c]\nsessions =\n", 2, "empty value");
    expect_error("[harness c]\nuse bogus = . name a\n", 2, "invalid key 'use bogus'");
    expect_error("[harness c]\nuse skill extra = . name a\n", 2, "invalid key");
    expect_error("[harness c]\nuse = . name a\n", 2, "unknown key 'use'");
    expect_error("[harness c]\nuse skill = a\n", 2, "use skill: 'name PATH' is missing");
    expect_error("[harness c]\nuse command = a..b name x\n", 2, "use command: 'a..b' is not a path");
    expect_error("[outfit o]\nsessions = /x\n", 2, "unknown key 'sessions'");
    expect_error("[outfit o]\nuse skill = . name a\n", 2, "unknown key 'use skill'");

    // The limits: at most 8 sessions and 16 use keys in a harness, counted across the kinds.
    char tx[4096];
    size_t n = (size_t)snprintf(tx, sizeof tx, "[harness c]\n");
    for (int i = 0; i < 8; i++) n += (size_t)snprintf(tx + n, sizeof tx - n, "sessions = /x/%d\n", i);
    CHECK(parse(tx, &e));
    snprintf(tx + n, sizeof tx - n, "sessions = /x/9\n");
    expect_error(tx, 10, "too many 'sessions' keys in a harness (limit 8)");
    n = (size_t)snprintf(tx, sizeof tx, "[harness c]\n");
    for (int i = 0; i < 16; i++) n += (size_t)snprintf(tx + n, sizeof tx - n, "use %s = . name a\n", i % 2 ? "agent" : "skill");
    CHECK(parse(tx, &e));
    snprintf(tx + n, sizeof tx - n, "use command = . name a\n");
    expect_error(tx, 18, "too many 'use' keys in a harness (limit 16)");
}

// ---- the record reader ----------------------------------------------------------

static UsageRule ur[CONF_USE_MAX];
static UsagePath ut;
static UsagePath up;
static Usage uu;
static UsageSource us;
static UsageEvent got[64];
static int ngot;
static uint64_t uend;
static char qbuf[16384];

static void ucollect(void *state, const UsageEvent *e)
{
    (void)state;
    if (ngot < 64) got[ngot] = *e;
    ngot++;
}

static void use_rules(uint32_t n, const UseKind *kinds, const char *const *texts)
{
    char msg[256];
    for (uint32_t i = 0; i < n; i++) CHECK(conf_rule_parse(&ur[i], kinds[i], texts[i], msg, sizeof msg));
    CHECK(conf_path_parse(&ut, "timestamp", false, false) && conf_path_parse(&up, "cwd", false, false));
    usage_init(&uu, ur, n, &ut, &up);
}

// The four rules of docs/harnesses.md, a time and a project.
static void std_rules(void)
{
    static const UseKind kinds[] = {USE_SKILL, USE_AGENT, USE_AGENT, USE_COMMAND};
    static const char *const texts[] = {
        "message.content[] where type=tool_use name=Skill name input.skill id id",
        "message.content[] where type=tool_use name=Agent name input.subagent_type id id",
        "message.content[] where type=tool_use name=Task name input.subagent_type id id",
        ". where type=user name message.content between <command-name>/ </command-name>",
    };
    use_rules(4, kinds, texts);
}

// Read TEXT (LEN bytes) as lines; the number of events it gave.
static int run_mem(const void *tx, size_t len)
{
    ngot = 0;
    usage_source_mem(&us, tx, len);
    CHECK(usage_read(&uu, &us, 0, &uend, ucollect, nullptr));
    return ngot;
}

// One record written with ' for ", ended with a newline, read afresh.
static int run_q(const char *json)
{
    size_t n = 0;
    for (; json[n] != '\0'; n++) qbuf[n] = json[n] == '\'' ? '"' : json[n];
    qbuf[n++] = '\n';
    std_rules();
    return run_mem(qbuf, n);
}

#define BLOCK(NAME, SKILL, ID) "{'type':'tool_use','id':'" ID "','name':'" NAME "','input':{'skill':'" SKILL "'}}"
#define REC(CONTENT) "{'type':'assistant','message':{'content':[" CONTENT "]},'timestamp':'2026-11-10T10:00:00.000Z','cwd':'/w/p'}"

static void test_reader_basics(void)
{
    CHECK(run_q(REC(BLOCK("Skill", "alpha", "toolu_1"))) == 1);
    CHECK(got[0].kind == USE_SKILL && strcmp(got[0].name, "alpha") == 0 && strcmp(got[0].id, "toolu_1") == 0);
    CHECK(strcmp(got[0].time, "2026-11-10T10:00:00.000Z") == 0 && strcmp(got[0].project, "/w/p") == 0);
    CHECK(uu.skipped == 0 && uu.lines == 1 && uend == strlen(qbuf));
    // Field order does not matter, in the record or in the block.
    CHECK(run_q("{'cwd':'/w/q','timestamp':'T','message':{'content':[{'input':{'skill':'beta'},'name':'Skill','id':'toolu_2','type':'tool_use'}]}}") == 1);
    CHECK(strcmp(got[0].name, "beta") == 0 && strcmp(got[0].id, "toolu_2") == 0 && strcmp(got[0].time, "T") == 0);
    CHECK(run_q("{'name':'Skill','input':{'skill':'g'},'type':'tool_use'}") == 0);  // not at the declared path
    CHECK(run_q("{'message':{'content':[{'name':'Skill','input':{'skill':'g'},'type':'tool_use'}]}}") == 1);
    CHECK(got[0].id[0] == '\0' && got[0].time[0] == '\0' && got[0].project[0] == '\0');
    // Two blocks in one record, with others between that are not skills.
    CHECK(run_q(REC(BLOCK("Skill", "a1", "i1") ",{'type':'text','text':'x'}," BLOCK("Read", "no", "i2") "," BLOCK("Skill", "a2", "i3"))) == 2);
    CHECK(strcmp(got[0].name, "a1") == 0 && strcmp(got[1].name, "a2") == 0 && strcmp(got[1].id, "i3") == 0);
    // Agents and the older Task, with a subagent type.
    CHECK(run_q(REC("{'type':'tool_use','id':'i','name':'Agent','input':{'subagent_type':'reviewer','prompt':'p'}},"
                    "{'type':'tool_use','id':'j','name':'Task','input':{'subagent_type':'old'}},"
                    "{'type':'tool_use','id':'k','name':'Agent','input':{'prompt':'no type'}}")) == 2);
    CHECK(got[0].kind == USE_AGENT && strcmp(got[0].name, "reviewer") == 0 && strcmp(got[1].name, "old") == 0);
}

static void test_reader_not_the_declared_path(void)
{
    // Only a real block at the declared path counts.
    CHECK(run_q("{'other':{'message':{'content':[" BLOCK("Skill", "x", "i") "]}}}") == 0);
    CHECK(run_q("{'message':{'content':{'type':'tool_use','name':'Skill','input':{'skill':'x'}}}}") == 0);
    CHECK(run_q("{'message':{'content':[[" BLOCK("Skill", "x", "i") "]]}}") == 0);
    CHECK(run_q("{'message':{'content':['a',5,null,true,[1],{}," BLOCK("Skill", "ok", "i") "]}}") == 1);
    CHECK(run_q("{'message':{'content':[{'type':'tool_use','name':'Skill','input':{'skill':'x'},'extra':{'type':'text'}}]}}") == 1);
    CHECK(run_q("{'message':{'content':[{'type':'text','text':'{\\\"type\\\":\\\"tool_use\\\",\\\"name\\\":\\\"Skill\\\"}'}]}}") == 0);
    CHECK(run_q("{'message':{'content':[{'type':5,'name':'Skill','input':{'skill':'x'}}]}}") == 0);
    CHECK(run_q("{'message':{'content':[{'type':'tool_user','name':'Skill','input':{'skill':'x'}}]}}") == 0);
    CHECK(run_q("{'message':{'content':[{'type':'text','type':'tool_use','name':'Skill','input':{'skill':'x'}}]}}") == 1);
    CHECK(run_q("{'message':{'content':[{'type':'tool_use','name':'Skill','input':'x'}]}}") == 0);
    CHECK(run_q("{'message':{'content':[{'type':'tool_use','name':'Skill','input':{'skill':5}}]}}") == 0);
    CHECK(uu.skipped == 0);
    // A key of the wrong length or longer than a field name ever is.
    CHECK(run_q("{'message':{'content':[{'type':'tool_use','name':'Skill','input':{'skill':'x','abcdefghijklmnopqrstuvwxyzabcdefghij':1}}]}}") == 1);
    CHECK(run_q("{'message':{'content':[{'ty':'tool_use','name':'Skill','input':{'skill':'x'}}]}}") == 0);
    CHECK(run_q("{'mes\\u0073age':{'content':[" BLOCK("Skill", "esc", "i") "]}}") == 1);
}

static void test_reader_names(void)
{
    // Escapes in a name are decoded.
    CHECK(run_q(REC(BLOCK("Skill", "\\u0061l\\/p\\\\h\\u0041\\u004A\\u006b\\u004a", "i"))) == 1);
    CHECK(strcmp(got[0].name, "al/p\\hAJkJ") == 0);
    // Names that are not names: counted as skipped, not as events.
    static const char *const bad[] = {
        "has space", "a<b", "a>b", "a\\\"b", "", "a\\nb", "a\\tb", "a\\bb", "a\\fb", "a\\rb", "\\ud83d\\ude00", "\\u00e9", "\\u00E9", "\\u0100x", "\\ue000", "\\u0000",
        "\xc3\xa9", "a\177b",
    };
    for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
        char rec[512];
        snprintf(rec, sizeof rec, REC(BLOCK("Skill", "%s", "i")), bad[i]);
        CHECK(run_q(rec) == 0);
        CHECK(uu.skipped == 1);
        if (uu.skipped != 1) printf("  name %zu\n", i);
    }
    // 200 bytes are kept, 201 are not.
    char big[400];
    memset(big, 'n', 200);
    big[200] = '\0';
    char rec[1024];
    snprintf(rec, sizeof rec, REC(BLOCK("Skill", "%s", "i")), big);
    CHECK(run_q(rec) == 1 && strlen(got[0].name) == 200);
    big[200] = 'n';
    big[201] = '\0';
    snprintf(rec, sizeof rec, REC(BLOCK("Skill", "%s", "i")), big);
    CHECK(run_q(rec) == 0 && uu.skipped == 1);
    // Namespaced and scoped names keep the whole string.
    CHECK(run_q(REC(BLOCK("Skill", "plugin:skill", "i") "," BLOCK("Skill", "apps/web:deploy", "j"))) == 2);
    CHECK(strcmp(got[0].name, "plugin:skill") == 0 && strcmp(got[1].name, "apps/web:deploy") == 0);
    // A bad escape is not JSON: the line is skipped whole.
    CHECK(run_q(REC(BLOCK("Skill", "a\\xb", "i"))) == 0 && uu.skipped == 1);
    CHECK(run_q(REC(BLOCK("Skill", "a\\u12G4", "i"))) == 0 && uu.skipped == 1);
    CHECK(run_q(REC(BLOCK("Skill", "a\\u12g4", "i"))) == 0 && uu.skipped == 1);
    CHECK(run_q(REC(BLOCK("Skill", "a\\u12", "i"))) == 0 && uu.skipped == 1);
    // An id that is too long or not a token drops the invocation; one that is not a string is no id.
    CHECK(run_q(REC(BLOCK("Skill", "a", "has space"))) == 0 && uu.skipped == 1);
    snprintf(rec, sizeof rec, REC("{'type':'tool_use','id':'%s','name':'Skill','input':{'skill':'a'}}"), big);
    CHECK(run_q(rec) == 0 && uu.skipped == 1);
    memset(big, 'i', 128);
    big[128] = '\0';
    snprintf(rec, sizeof rec, REC("{'type':'tool_use','id':'%s','name':'Skill','input':{'skill':'a'}}"), big);
    CHECK(run_q(rec) == 1 && strlen(got[0].id) == 128);
    CHECK(run_q(REC("{'type':'tool_use','id':7,'name':'Skill','input':{'skill':'a'}}")) == 1 && got[0].id[0] == '\0');
}

static void test_reader_whitespace_and_no_time(void)
{
    // Spaces, tabs and a carriage return between the parts of a record.
    CHECK(run_q("{\t'message' \r:\t{ 'content' : [ " BLOCK("Skill", "ws", "i") " ,\t{ } ] } ,\r 'cwd'\t:\t'/w' }\r") == 1);
    CHECK(strcmp(got[0].name, "ws") == 0 && strcmp(got[0].project, "/w") == 0);
    // A reader told of no time and no project finds none.
    static const UseKind kind[] = {USE_SKILL};
    static const char *const txt[] = {"a name b"};
    char msg[256];
    CHECK(conf_rule_parse(&ur[0], kind[0], txt[0], msg, sizeof msg));
    usage_init(&uu, ur, 1, nullptr, nullptr);
    const char *rec = "{\"a\":{\"b\":\"v\"},\"timestamp\":\"T\",\"cwd\":\"/p\"}\n";
    CHECK(run_mem(rec, strlen(rec)) == 1);
    CHECK(got[0].time[0] == '\0' && got[0].project[0] == '\0');
}

static void test_reader_time_and_project(void)
{
    char rec[1500];
    char s[600];
    memset(s, 't', 40);
    s[40] = '\0';
    snprintf(rec, sizeof rec, "{'timestamp':'%s','cwd':'/p','message':{'content':[" BLOCK("Skill", "a", "i") "]}}", s);
    CHECK(run_q(rec) == 1 && strcmp(got[0].time, s) == 0);
    s[40] = 't';
    s[41] = '\0';
    snprintf(rec, sizeof rec, "{'timestamp':'%s','cwd':'/p','message':{'content':[" BLOCK("Skill", "a", "i") "]}}", s);
    CHECK(run_q(rec) == 1 && got[0].time[0] == '\0');
    memset(s, 'p', 511);
    s[511] = '\0';
    snprintf(rec, sizeof rec, "{'cwd':'%s','message':{'content':[" BLOCK("Skill", "a", "i") "]}}", s);
    CHECK(run_q(rec) == 1 && strcmp(got[0].project, s) == 0);
    s[511] = 'p';
    s[512] = '\0';
    snprintf(rec, sizeof rec, "{'cwd':'%s','message':{'content':[" BLOCK("Skill", "a", "i") "]}}", s);
    CHECK(run_q(rec) == 1 && got[0].project[0] == '\0');
    CHECK(run_q("{'timestamp':5,'cwd':[1],'message':{'content':[" BLOCK("Skill", "a", "i") "]}}") == 1);
    CHECK(got[0].time[0] == '\0' && got[0].project[0] == '\0');
}

static void test_reader_commands(void)
{
    // A user record whose content is a string, or a list of blocks with tx.
    CHECK(run_q("{'type':'user','message':{'content':'<command-message>f</command-message>\\n<command-name>/foo</command-name>\\n<command-args></command-args>'},'timestamp':'T'}") == 1);
    CHECK(got[0].kind == USE_COMMAND && strcmp(got[0].name, "foo") == 0 && got[0].id[0] == '\0' && strcmp(got[0].time, "T") == 0);
    CHECK(run_q("{'type':'user','message':{'content':[{'type':'text','text':'<command-name>/bar</command-name>'},{'type':'image'},'str',{'type':'text','text':'plain'}]}}") == 1);
    CHECK(strcmp(got[0].name, "bar") == 0);
    CHECK(run_q("{'type':'assistant','message':{'content':'<command-name>/foo</command-name>'}}") == 0);
    CHECK(run_q("{'type':'user','message':{'content':5}}") == 0);
    CHECK(run_q("{'type':'user','message':{'content':'<command-name>/ns:foo</command-name>'}}") == 1 && strcmp(got[0].name, "ns:foo") == 0);
    CHECK(uu.skipped == 0);
    // Without the first tag, nothing; with it but no end, or an empty name, a name that is not one.
    CHECK(run_q("{'type':'user','message':{'content':'<command-name>foo</command-name>'}}") == 0 && uu.skipped == 0);
    CHECK(run_q("{'type':'user','message':{'content':'<command-name>/foo'}}") == 0 && uu.skipped == 1);
    CHECK(run_q("{'type':'user','message':{'content':'<command-name>/</command-name>'}}") == 0 && uu.skipped == 1);
    CHECK(run_q("{'type':'user','message':{'content':'<command-name>/a b</command-name>'}}") == 0 && uu.skipped == 1);
    // A name of 250 bytes between the tags is too long to be a name.
    char tx[1500];
    char longname[300];
    memset(longname, 'z', 250);
    longname[250] = '\0';
    snprintf(tx, sizeof tx, "{'type':'user','message':{'content':'<command-name>/%s</command-name>'}}", longname);
    CHECK(run_q(tx) == 0 && uu.skipped == 1);
    // Only the first 512 bytes are looked at for the tags.
    char pad[600];
    memset(pad, 'x', 470);
    pad[470] = '\0';
    snprintf(tx, sizeof tx, "{'type':'user','message':{'content':'%s<command-name>/in</command-name>'}}", pad);
    CHECK(run_q(tx) == 1 && strcmp(got[0].name, "in") == 0);
    snprintf(tx, sizeof tx, "{'type':'user','message':{'content':'%s<command-name>/farther-than-b</command-name>'}}", pad);
    CHECK(run_q(tx) == 0 && uu.skipped == 1);  // A is there, B is past the 512th byte
    memset(pad, 'x', 520);
    pad[520] = '\0';
    snprintf(tx, sizeof tx, "{'type':'user','message':{'content':'%s<command-name>/late</command-name>'}}", pad);
    CHECK(run_q(tx) == 0 && uu.skipped == 0);  // A is past the 512th byte
}

static void test_reader_lines(void)
{
    std_rules();
    const char *good = "{'message':{'content':[" BLOCK("Skill", "a", "i") "]}}";
    char tx[2048];
    size_t n = 0;
    for (const char *p = good; *p != '\0'; p++) tx[n++] = *p == '\'' ? '"' : *p;
    size_t one = n;
    tx[n++] = '\n';
    // A last line with no newline is not read, and the offset says where it starts.
    memcpy(tx + n, tx, one);
    CHECK(run_mem(tx, n + one) == 1 && uend == n);
    CHECK(run_mem(tx, one) == 0 && uend == 0);
    CHECK(run_mem(tx, 0) == 0 && uend == 0);
    CHECK(run_mem(tx, n) == 1 && uend == n);
    // Reading from an offset starts at that line.
    tx[n + one] = '\n';
    ngot = 0;
    usage_source_mem(&us, tx, n + one + 1);
    CHECK(usage_read(&uu, &us, n, &uend, ucollect, nullptr) && ngot == 1 && uend == n + one + 1);
    ngot = 0;
    usage_source_mem(&us, tx, n + one + 1);
    CHECK(usage_read(&uu, &us, 0, &uend, ucollect, nullptr) && ngot == 2);
    // Lines without a block pass the filter only if they have its bytes; a blank line is not JSON.
    std_rules();
    CHECK(run_mem("\n\n{}\n", 5) == 0 && uu.lines == 0);
}

// A record that is not JSON, with every byte a rule looks for.
static void bad_line(const char *tail)
{
    char tx[600];
    snprintf(tx, sizeof tx, "{\"k\":\"tool_use Skill user\",\"x\":%s", tail);
    std_rules();
    size_t n = strlen(tx);
    tx[n++] = '\n';
    CHECK(run_mem(tx, n) == 0);
    CHECK(uu.skipped == 1);
    if (uu.skipped != 1) printf("  not JSON: %s\n", tail);
}

static void test_reader_not_json(void)
{
    static const char *const tails[] = {
        "", "}", "tru", "trux", "x", "nul", "falsy", "01", "-", "-x", "1.", "1.x", "1e", "1e+", "1ex", "[1,]", "[1 2]", "[", "{", "{\"a\"}",
        "{\"a\":}", "{1:2}", "{\"a\":1 \"b\":2}", "{\"a\":1,}", "\"abc", "\"a\\", "\"\\x\"", "\"\\u12G4\"", "\"a\x01\"", "\"\\u12\"", "1}}", "{} {}",
        "[]]", "{\"a\":1}x", "{\"a", "{\"a\\",
    };
    for (size_t i = 0; i < sizeof tails / sizeof tails[0]; i++) bad_line(tails[i]);
    // And the valid forms of the same, which are not skipped (the closing brace ends the record).
    static const char *const fine[] = {
        "0}", "-0}", "12}", "1.5}", "1e5}", "1E+5}", "1e-5}", "-1.25e+3}", "true}", "false}", "null}", "[]}", "{}}", "[1,2,[3],{\"a\":[]}]}",
        "\"\"}", "\" \\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u00e9 \"}", "\t1\r}", " 1 \t}", "[ 1 , 2 ] \r\t}",
    };
    for (size_t i = 0; i < sizeof fine / sizeof fine[0]; i++) {
        char tx[600];
        snprintf(tx, sizeof tx, "{\"k\":\"tool_use Skill user\",\"x\":%s\n", fine[i]);
        std_rules();
        CHECK(run_mem(tx, strlen(tx)) == 0 && uu.skipped == 0 && uu.lines == 1);
    }
}

static void test_reader_limits(void)
{
    char *line = malloc(6u << 20);
    CHECK(line != nullptr);
    static const char head[] = "{\"pad\":\"";
    static const char mid[] = "\",\"message\":{\"content\":[{\"type\":\"tool_use\",\"id\":\"i\",\"name\":\"Skill\",\"input\":{\"skill\":\"after-the-pad\"}}]}}\n";
    size_t big = 5u << 20;
    size_t n = 0;
    memcpy(line, head, sizeof head - 1);
    n = sizeof head - 1;
    memset(line + n, 'x', big);
    n += big;
    memcpy(line + n, mid, sizeof mid - 1);
    n += sizeof mid - 1;
    std_rules();
    CHECK(run_mem(line, n) == 1 && strcmp(got[0].name, "after-the-pad") == 0 && uend == n);
    // A name of 5 MiB is too long to be a name, and is not stored.
    n = (size_t)snprintf(line, 6u << 20, "{\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"");
    memset(line + n, 'n', big);
    n += big;
    n += (size_t)snprintf(line + n, 100, "\"}}]}}\n");
    std_rules();
    CHECK(run_mem(line, n) == 0 && uu.skipped == 1);
    // A command whose tx is 5 MiB: the name is in the first 512 bytes.
    n = (size_t)snprintf(line, 6u << 20, "{\"type\":\"user\",\"message\":{\"content\":\"<command-name>/big</command-name>");
    memset(line + n, 'y', big);
    n += big;
    n += (size_t)snprintf(line + n, 100, "\"}}\n");
    std_rules();
    CHECK(run_mem(line, n) == 1 && strcmp(got[0].name, "big") == 0);
    free(line);
}

// A record with a block of its own and DEPTH containers around the field "z", counting the record's own.
static void depth_case(size_t depth, bool fine)
{
    static char line[512];
    size_t n = (size_t)snprintf(line, sizeof line, "{\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"d\"}}]},\"z\":");
    for (size_t i = 1; i < depth; i++) line[n++] = '[';
    for (size_t i = 1; i < depth; i++) line[n++] = ']';
    line[n++] = '}';
    line[n++] = '\n';
    std_rules();
    CHECK(run_mem(line, n) == (fine ? 1 : 0));
    CHECK(uu.skipped == (fine ? 0u : 1u));
}

static void test_reader_depth(void)
{
    depth_case(2, true);
    depth_case(USAGE_DEPTH_MAX, true);
    depth_case(USAGE_DEPTH_MAX + 1, false);
    depth_case(USAGE_DEPTH_MAX + 40, false);
    // The same for objects inside objects: sixty-five opens in a row.
    char line[400];
    size_t n = 0;
    for (size_t i = 0; i < USAGE_DEPTH_MAX + 1; i++) n += (size_t)snprintf(line + n, 20, "{\"a\":");
    n += (size_t)snprintf(line + n, 30, "\"tool_use Skill user\"");
    line[n++] = '\n';
    std_rules();
    CHECK(run_mem(line, n) == 0 && uu.skipped == 1);
}

static void test_reader_caps(void)
{
    // At most 32 things from a line, the rest counted as skipped.
    char line[8192];
    size_t n = (size_t)snprintf(line, sizeof line, "{\"message\":{\"content\":[");
    for (int i = 0; i < 40; i++)
        n += (size_t)snprintf(line + n, sizeof line - n, "%s{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"s%d\"}}", i ? "," : "", i);
    n += (size_t)snprintf(line + n, sizeof line - n, "]}}\n");
    std_rules();
    CHECK(run_mem(line, n) == (int)USAGE_LINE_HITS_MAX && uu.skipped == 8);
    // And at most 8 names from the one thing a rule examined.
    n = (size_t)snprintf(line, sizeof line, "{\"type\":\"user\",\"message\":{\"content\":[");
    for (int i = 0; i < 10; i++)
        n += (size_t)snprintf(line + n, sizeof line - n, "%s{\"text\":\"<command-name>/c%d</command-name>\"}", i ? "," : "", i);
    n += (size_t)snprintf(line + n, sizeof line - n, "]}}\n");
    std_rules();
    CHECK(run_mem(line, n) == (int)USAGE_CAND_MAX && strcmp(got[7].name, "c7") == 0);
    // A value of one byte, and a name between one-byte tags.
    static const UseKind k0[] = {USE_SKILL, USE_COMMAND};
    static const char *const t0[] = {"a where p=q name n", ". name m between [ ]"};
    use_rules(2, k0, t0);
    CHECK(run_mem("{\"a\":{\"p\":\"q\",\"n\":\"one\"},\"m\":\"x[two]y\"}\n", 40) == 2);
    CHECK(strcmp(got[0].name, "one") == 0 && strcmp(got[1].name, "two") == 0);
    // A rule with no where test looks at every line; another needs four values; sixteen rules need sixty-four.
    static const UseKind k1[] = {USE_SKILL};
    static const char *const t1[] = {"a name b"};
    use_rules(1, k1, t1);
    CHECK(run_mem("{\"a\":{\"b\":\"v\"}}\n", 16) == 1 && strcmp(got[0].name, "v") == 0);
    UseKind kinds[CONF_USE_MAX];
    char ptext[CONF_USE_MAX][100];
    const char *texts[CONF_USE_MAX];
    for (int i = 0; i < 16; i++) {
        kinds[i] = USE_AGENT;
        snprintf(ptext[i], sizeof ptext[i], "a where p=u%d_1 q=u%d_2 r=u%d_3 s=u%d_4 name n", i, i, i, i);
        texts[i] = ptext[i];
    }
    use_rules(16, kinds, texts);
    CHECK(uu.nv == 64);
    const char *rec = "{\"a\":{\"p\":\"u15_1\",\"q\":\"u15_2\",\"r\":\"u15_3\",\"s\":\"u15_4\",\"n\":\"found\"}}\n";
    CHECK(run_mem(rec, strlen(rec)) == 1 && strcmp(got[0].name, "found") == 0);
    rec = "{\"a\":{\"p\":\"u15_1\",\"q\":\"u15_2\",\"r\":\"u15_3\",\"s\":\"x\",\"n\":\"no\"}}\n";
    CHECK(run_mem(rec, strlen(rec)) == 0);
}

// A value the pre-test looks for, cut by the end of a chunk.
static void test_reader_chunk_edge(void)
{
    // A line that ends a few bytes into the second chunk.
    char *plain = malloc(USAGE_CHUNK + 8);
    CHECK(plain != nullptr);
    memset(plain, 'x', USAGE_CHUNK + 3);
    plain[USAGE_CHUNK + 3] = '\n';
    std_rules();
    CHECK(run_mem(plain, USAGE_CHUNK + 4) == 0 && uu.skipped == 0 && uend == USAGE_CHUNK + 4);
    free(plain);
    static const char before[] = "{\"pad\":\"";
    static const char block[] = "\",\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"edge\"}}]}}\n";
    const char *cut = strstr(block, "tool_use");
    for (size_t shift = 0; shift < 13; shift++) {  // the value starts 10 bytes before the end of the chunk, to 2 after
        size_t pad = USAGE_CHUNK - 10 + shift - (sizeof before - 1) - (size_t)(cut - block);
        char *line = malloc(USAGE_CHUNK + 400);
        CHECK(line != nullptr);
        memcpy(line, before, sizeof before - 1);
        memset(line + sizeof before - 1, 'x', pad);
        memcpy(line + sizeof before - 1 + pad, block, sizeof block - 1);
        size_t n = sizeof before - 1 + pad + sizeof block - 1;
        std_rules();
        CHECK(run_mem(line, n) == 1);
        if (ngot != 1) printf("  chunk edge shift %zu\n", shift);
        free(line);
    }
}

// ---- the reader on a file, and failing reads --------------------------------------

static char ufile[] = "/tmp/suit-unit-usage.XXXXXX";

// A file of one 100 KB line that holds a skill, then a short line that holds another.
static void make_usage_file(void)
{
    int fd = mkstemp(ufile);
    CHECK(fd >= 0);
    static char line[100100];
    size_t n = (size_t)snprintf(line, sizeof line, "{\"pad\":\"");
    memset(line + n, 'x', 100000);
    n += 100000;
    n += (size_t)snprintf(line + n, sizeof line - n, "\",\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"long\"}}]}}\n");
    CHECK(write(fd, line, n) == (ssize_t)n);
    const char *second = "{\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"short\"}}]}}\n";
    CHECK(write(fd, second, strlen(second)) == (ssize_t)strlen(second));
    close(fd);
}

static int file_read(uint64_t start, bool *ok)
{
    int fd = open(ufile, O_RDONLY);
    std_rules();
    ngot = 0;
    usage_source_fd(&us, fd);
    *ok = usage_read(&uu, &us, start, &uend, ucollect, nullptr);
    close(fd);
    return ngot;
}

static int child_file_ok(void)
{
    bool ok;
    int n = file_read(0, &ok);
    return ok && n == 2 && strcmp(got[0].name, "long") == 0 && strcmp(got[1].name, "short") == 0 ? 0 : 1;
}

static int child_file_fails(void)
{
    bool ok;
    (void)file_read(0, &ok);
    return !ok && us.err == EIO ? 0 : 1;
}

static void test_reader_file(void)
{
    make_usage_file();
    bool ok;
    CHECK(file_read(0, &ok) == 2 && ok && strcmp(got[1].name, "short") == 0);
    struct stat st;
    CHECK(stat(ufile, &st) == 0 && uend == (uint64_t)st.st_size);
    // From the second line on: a seek outside the chunk.
    uint64_t second = (uint64_t)st.st_size - strlen("{\"message\":{\"content\":[{\"type\":\"tool_use\",\"name\":\"Skill\",\"input\":{\"skill\":\"short\"}}]}}\n");
    CHECK(file_read(second, &ok) == 1 && ok && strcmp(got[0].name, "short") == 0 && uend == (uint64_t)st.st_size);
    CHECK(file_read(second - 3, &ok) == 1 && ok);  // what is left of the first line is not a record
    CHECK(file_read(100000, &ok) == 1 && ok && uu.skipped == 1);
    CHECK(child_file_ok() == 0);
    // A read that returns a few bytes at a time gives the same; a read that fails fails the scan.
    CHECK(in_child("read:1:short", child_file_ok) == 0);
    CHECK(in_child("read:3:short", child_file_ok) == 0);
    for (int i = 1; i <= 5; i++) {
        char spec[32];
        snprintf(spec, sizeof spec, "read:%d", i);
        int rc = in_child(spec, child_file_fails);
        CHECK(rc == 0);
        if (rc != 0) printf("  %s: %d\n", spec, rc);
    }
    CHECK(in_child("read:6", child_file_ok) == 0);
    CHECK(in_child("lseek:1", child_file_fails) == 0);
    CHECK(in_child("lseek:2", child_file_ok) == 0);
    unlink(ufile);
}

// ---- the tally's time, trimming and wildcards -------------------------------------

static void test_tally_helpers(void)
{
    char t[20];
    tally_civil(0, t);
    CHECK(strcmp(t, "1970-01-01T00:00:00") == 0);
    tally_civil(-5, t);
    CHECK(strcmp(t, "1970-01-01T00:00:00") == 0);
    tally_civil(86399, t);
    CHECK(strcmp(t, "1970-01-01T23:59:59") == 0);
    tally_civil(951782400, t);
    CHECK(strcmp(t, "2000-02-29T00:00:00") == 0);
    tally_civil(1709164800, t);
    CHECK(strcmp(t, "2024-02-29T00:00:00") == 0);
    tally_civil(1794000000, t);
    CHECK(strcmp(t, "2026-11-06T21:20:00") == 0);
    tally_civil(4102444800, t);
    CHECK(strcmp(t, "2100-01-01T00:00:00") == 0);

    CHECK(tally_time_ok("2026-11-10T10:00:00", 19) && tally_time_ok("2026-11-10T10:00:00.123Z", 24));
    CHECK(!tally_time_ok("2026-11-10T10:00:0", 18) && !tally_time_ok("2026-11-10X10:00:00", 19));
    CHECK(!tally_time_ok("2026-11-10T10:00:0x", 19) && !tally_time_ok("2026+11-10T10:00:00", 19));
    CHECK(!tally_time_ok("2026-11-10T10:00:00\tZ", 20) && !tally_time_ok("2026-11-10T10:00:00\nZ", 20));
    CHECK(!tally_time_ok("2026-11-10T10:00:00.00000000000000000000000Z", 44));

    char buf[400];
    const char *lines = "2025-01-01T00:00:00 a\n2026-01-01T00:00:00 b\n2026-06-01T00:00:00 c\n2026-07-01T00:00:00 d\n";
    size_t len = strlen(lines);
    memcpy(buf, lines, len);
    CHECK(tally_trim(buf, len, "2026-01-01T00:00:00", 10, 1000) == len - 22);
    CHECK(memcmp(buf, "2026-01-01T00:00:00 b\n", 22) == 0);
    memcpy(buf, lines, len);
    CHECK(tally_trim(buf, len, "2000-01-01T00:00:00", 2, 1000) == 44 && memcmp(buf, "2026-06-01", 10) == 0);
    memcpy(buf, lines, len);
    CHECK(tally_trim(buf, len, "2000-01-01T00:00:00", 10, 50) == 44);
    memcpy(buf, lines, len);
    CHECK(tally_trim(buf, len, "2000-01-01T00:00:00", 10, 1000) == len);
    memcpy(buf, lines, len);
    CHECK(tally_trim(buf, len, "2100-01-01T00:00:00", 10, 1000) == 0);

    CHECK(tally_wild("*.jsonl", 7, "a.jsonl") && tally_wild("*.jsonl", 7, ".jsonl") && !tally_wild("*.jsonl", 7, "a.json"));
    CHECK(tally_wild("a*b*c", 5, "aXbYc") && tally_wild("a*b*c", 5, "abc") && !tally_wild("a*b*c", 5, "acb"));
    CHECK(tally_wild("*", 1, "") && tally_wild("*", 1, "anything") && tally_wild("**", 2, "x") && tally_wild("abc", 3, "abc"));
    CHECK(!tally_wild("abc", 3, "abcd") && !tally_wild("abcd", 4, "abc") && !tally_wild("", 0, "x") && tally_wild("", 0, ""));
    CHECK(tally_wild("a*", 1, "a") && !tally_wild("a*", 1, "ab") && tally_wild("ab*", 2, "ab"));  // the length counts, not the NUL
    CHECK(tally_wild("a*", 2, "ab") && tally_wild("*b", 2, "aab") && !tally_wild("*b", 2, "aba"));
}

static void test_wall_clock(void)
{
    int64_t s = 0;
    CHECK(sys_wall_sec(&s) && s > 1700000000);
    setenv("SUIT_NOW", "1794000000", 1);
    CHECK(sys_wall_sec(&s) && s == 1794000000);
    unsetenv("SUIT_NOW");
}

// ---- `suit curate`: the front matter, the JSON, the matching, the periods ----------------------------------

// The description of the front matter of TEXT, and its length through LEN.
static const char *front(const char *yaml, size_t *len)
{
    static char out[4096];
    size_t n = curate_front_description(yaml, strlen(yaml), out);
    if (len != nullptr) *len = n;
    return out;
}

static bool front_is(const char *yaml, const char *expect)
{
    size_t n;
    const char *result = front(yaml, &n);
    bool same = strcmp(result, expect) == 0 && n == strlen(expect);
    if (!same) printf("  front matter of %s: result '%s' (%zu), expect '%s'\n", yaml, result, n, expect);
    return same;
}

static void test_curate_front_matter(void)
{
    CHECK(front_is("---\ndescription: hello   world\n---\nbody\n", "hello world"));
    CHECK(front_is("no fence\n", ""));
    CHECK(front_is("", ""));
    CHECK(front_is("---", ""));
    CHECK(front_is("---\ndescription: x\n", ""));
    CHECK(front_is("----\ndescription: x\n---\n", ""));
    CHECK(front_is("\xEF\xBB\xBF---\ndescription: x\n---\n", "x"));
    CHECK(front_is("---\r\ndescription: x\r\n---\r\n", "x"));
    CHECK(front_is("---  \ndescription: x\n--- \t\n", "x"));
    CHECK(front_is("---\nname: a\n---\n", ""));
    CHECK(front_is("---\ndescriptionx: no\ndescription:foo\n  description: nested\n---\n", ""));
    CHECK(front_is("---\ndescription:\n---\n", ""));
    CHECK(front_is("---\ndescription: \t \n---\n", ""));
    CHECK(front_is("---\ndescription:\t  tabbed  \t\n---\n", "tabbed"));
    CHECK(front_is("---\ndescription: one\ndescription: two\n---\n", "one"));
    // a plain value goes on over indented lines, and stops at any other
    CHECK(front_is("---\ndescription:\n  continued yaml\n  more\n---\n", "continued yaml more"));
    CHECK(front_is("---\ndescription: first\n  second\nname: n\n---\n", "first second"));
    CHECK(front_is("---\ndescription: a\n\n  b\n---\n", "a"));
    // double quotes
    CHECK(front_is("---\ndescription: \"say \\\"hi\\\" \\\\ end\\n there \\t x \\q\"\n---\n", "say \"hi\" \\ end there x \\q"));
    CHECK(front_is("---\ndescription: \"ab\\\n  cd\"\n---\n", "ab\\ cd"));
    CHECK(front_is("---\ndescription: \"x\" # a comment\n---\n", "x"));
    CHECK(front_is("---\ndescription: \"one\n  two\n  three\"\n---\n", "one two three"));
    CHECK(front_is("---\ndescription: \"one\ntwo\"\n---\n", "one"));
    CHECK(front_is("---\ndescription: \"unterminated\n---\n", "unterminated"));
    // tabs, and carriage returns before the end of a line
    CHECK(front_is("---\ndescription: a\tb\n---\n", "a b"));
    CHECK(front_is("---\r\ndescription: a\r\n  b\r\n---\r\n", "a b"));
    CHECK(front_is("---\ndescription: a\n\tb\n---\n", "a b"));
    CHECK(front_is("---\r\ndescription:\r\n  text\r\n---\r\n", "text"));
    CHECK(front_is("---\r\ndescription: |\r\n  a\r\n\r\n  b\r\nname: n\r\n---\r\n", "a b"));
    // single quotes
    CHECK(front_is("---\ndescription: 'a' trailing\n---\n", "a"));
    CHECK(front_is("---\ndescription: 'it''s fine'\n---\n", "it's fine"));
    CHECK(front_is("---\ndescription: 'ab''\n---\n", "ab'"));
    CHECK(front_is("---\ndescription: 'a\\b'\n---\n", "a\\b"));
    CHECK(front_is("---\ndescription: 'a\n  b'\n---\n", "a b"));
    // block scalars
    CHECK(front_is("---\ndescription: >-\n  folded one\n  folded two\n---\n", "folded one folded two"));
    CHECK(front_is("---\ndescription: |\n  a\n\n  b\nname: n\n---\n", "a b"));
    CHECK(front_is("---\ndescription: |+\n  x\r\n \r\n  y\n---\n", "x y"));
    CHECK(front_is("---\ndescription: >2\n  x\n---\n", "x"));
    CHECK(front_is("---\ndescription: >\nname: n\n---\n", ""));
    CHECK(front_is("---\ndescription: > not a header\n---\n", "> not a header"));
    CHECK(front_is("---\ndescription: |x\n---\n", "|x"));
    CHECK(front_is("---\ndescription: |\n---\n", ""));
    // the cut
    CHECK(curate_cut("abcdef", 6, 10) == 6);
    CHECK(curate_cut("abcdef", 6, 4) == 4);
    CHECK(curate_cut("a\xC3\xA9", 3, 2) == 1);
    CHECK(curate_cut("a\xC3\xA9", 3, 3) == 3);
    CHECK(curate_cut("\xE2\x82\xAC\xE2\x82\xAC", 6, 4) == 3);
    CHECK(curate_cut("\xE2\x82\xAC\xE2\x82\xAC", 6, 5) == 3);
    CHECK(curate_cut("\x80\x80\x80", 3, 2) == 0);
}

static const char *json_of(const char *s, size_t n)
{
    static char out[512];
    CurateBuf b = {.p = out, .cap = sizeof out - 1};
    curate_json_string(&b, s, n);
    out[b.len] = '\0';
    return b.over ? "OVER" : out;
}

static bool json_is(const char *s, size_t n, const char *expect)
{
    const char *result = json_of(s, n);
    bool same = strcmp(result, expect) == 0;
    if (!same) printf("  json of %zu bytes: result %s, expect %s\n", n, result, expect);
    return same;
}

static void test_curate_json(void)
{
    CHECK(json_is("", 0, "\"\""));
    CHECK(json_is("plain", 5, "\"plain\""));
    CHECK(json_is("a\"b\\c", 5, "\"a\\\"b\\\\c\""));
    CHECK(json_is("</script><img>&", 15, "\"\\u003c/script\\u003e\\u003cimg\\u003e\\u0026\""));
    CHECK(json_is("\x01\n\t\x1f", 4, "\"\\u0001\\u000a\\u0009\\u001f\""));
    CHECK(json_is("\x7f", 1, "\"\x7f\""));
    CHECK(json_is("\xC3\xA9", 2, "\"\xC3\xA9\""));
    CHECK(json_is("\xE2\x82\xAC", 3, "\"\xE2\x82\xAC\""));
    CHECK(json_is("\xE2\x80\x80", 3, "\"\xE2\x80\x80\""));
    CHECK(json_is("\xE2\x80\xA8|\xE2\x80\xA9", 7, "\"\\u2028|\\u2029\""));
    CHECK(json_is("\xEF\xBF\xBF", 3, "\"\xEF\xBF\xBF\""));
    CHECK(json_is("\xF0\x9F\x98\x80", 4, "\"\xF0\x9F\x98\x80\""));
    CHECK(json_is("\xF4\x8F\xBF\xBF", 4, "\"\xF4\x8F\xBF\xBF\""));
    // bytes that are not UTF-8 become U+FFFD, one for each byte
    const char *fffd = "\xEF\xBF\xBD";
    char expect[64];
    CHECK(json_is("\xFF", 1, "\"\xEF\xBF\xBD\""));
    CHECK(json_is("\x80", 1, "\"\xEF\xBF\xBD\""));
    CHECK(json_is("\xC0\x80", 2, "\"\xEF\xBF\xBD\xEF\xBF\xBD\""));
    CHECK(json_is("\xC3", 1, "\"\xEF\xBF\xBD\""));
    CHECK(json_is("\xC3(", 2, "\"\xEF\xBF\xBD(\""));
    CHECK(json_is("\xE0\x80\x80", 3, "\"\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\""));
    CHECK(json_is("\xE2\x82", 2, "\"\xEF\xBF\xBD\xEF\xBF\xBD\""));
    CHECK(json_is("\xED\xA0\x80", 3, "\"\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\""));
    CHECK(json_is("\xF4\x90\x80\x80", 4, "\"\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\""));
    CHECK(json_is("\xF5\x80\x80\x80", 4, "\"\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\""));
    snprintf(expect, sizeof expect, "\"a%sb\"", fffd);
    CHECK(json_is("a\xFF" "b", 3, expect));
    // a buffer that is too small is over, and stays so
    char small[8];
    CurateBuf b = {.p = small, .cap = sizeof small};
    curate_json_string(&b, "abcdefgh", 8);
    CHECK(b.over && b.len <= sizeof small);
    size_t len = b.len;
    curate_json_string(&b, "x", 1);
    CHECK(b.over && b.len == len);
}

static uint32_t hits[16];
static uint32_t nhits;

static void note_hit(void *state, uint32_t index)
{
    CHECK(state == &nhits);
    hits[nhits++] = index;
}

static uint32_t matches(const char *const *names, uint32_t n, const char *usage)
{
    nhits = 0;
    uint32_t count = curate_matches(names, n, usage, strlen(usage), note_hit, &nhits);
    CHECK(count == nhits);
    return count;
}

static void test_curate_matches(void)
{
    const char *const names[] = {"a", "ab", "b", "b", "c-d"};
    CHECK(matches(names, 5, "a") == 1 && hits[0] == 0);
    CHECK(matches(names, 5, "ab") == 1 && hits[0] == 1);
    CHECK(matches(names, 5, "b") == 2 && hits[0] == 2 && hits[1] == 3);
    CHECK(matches(names, 5, "plug:b") == 2 && hits[0] == 2);
    CHECK(matches(names, 5, "plug:sub:b") == 2);
    CHECK(matches(names, 5, "c-d") == 1 && hits[0] == 4);
    CHECK(matches(names, 5, "x:c-d") == 1);
    CHECK(matches(names, 5, "") == 0);
    CHECK(matches(names, 5, "b:") == 0);
    CHECK(matches(names, 5, ":") == 0);
    CHECK(matches(names, 5, "abc") == 0);
    CHECK(matches(names, 5, "A") == 0);
    CHECK(matches(names, 5, "zz") == 0);
    CHECK(matches(names, 5, "0") == 0);
    CHECK(matches(names, 5, "plug-a") == 0);
    CHECK(matches(names, 0, "a") == 0);
    CHECK(matches(names, 1, "b") == 0);
}

static void test_curate_periods(void)
{
    CurateCuts c;
    curate_cuts(1795176000, 30, &c);  // 2026-11-20T12:00:00Z
    CHECK(strcmp(c.window, "2026-10-21T12:00:00") == 0);
    CHECK(strcmp(c.d90, "2026-08-22T12:00:00") == 0);
    CHECK(strcmp(c.week[0], "2026-10-23T12:00:00") == 0);
    CHECK(strcmp(c.week[1], "2026-10-30T12:00:00") == 0);
    CHECK(strcmp(c.week[2], "2026-11-06T12:00:00") == 0);
    CHECK(strcmp(c.week[3], "2026-11-13T12:00:00") == 0);
    CHECK(curate_week(&c, "2026-11-20T11:00:00.000Z") == 3);
    CHECK(curate_week(&c, "2026-11-13T12:00:00.000Z") == 3);
    CHECK(curate_week(&c, "2026-11-13T11:59:59.999Z") == 2);
    CHECK(curate_week(&c, "2026-11-06T12:00:00") == 2);
    CHECK(curate_week(&c, "2026-11-06T11:59:59") == 1);
    CHECK(curate_week(&c, "2026-10-30T12:00:00") == 1);
    CHECK(curate_week(&c, "2026-10-30T11:59:59") == 0);
    CHECK(curate_week(&c, "2026-10-23T12:00:00") == 0);
    CHECK(curate_week(&c, "2026-10-23T11:59:59") == -1);
    CHECK(curate_week(&c, "2020-01-01T00:00:00") == -1);
    CHECK(curate_week(&c, "2027-01-01T00:00:00") == 3);
    curate_cuts(1795176000, 1, &c);
    CHECK(strcmp(c.window, "2026-11-19T12:00:00") == 0);
    curate_cuts(1795176000, 400, &c);
    CHECK(strcmp(c.window, "2025-10-16T12:00:00") == 0);
}

// ---- `suit curate apply`: the choices file, the outfit of a project, the edits of a suit.conf -------------------

// Parse LINE; the result kind, with the choice in C and the message in MSG.
static ChoiceLine choice_line(const char *line, CurateChoice *c, char *msg)
{
    msg[0] = '\0';
    return curate_choice_parse(line, strlen(line), c, msg, 256);
}

static void test_choices_header(void)
{
    CHECK(curate_choices_header("# suit choices 1", 16));
    CHECK(curate_choices_header("# suit choices 1\r", 17));
    CHECK(!curate_choices_header("# suit choices 1 ", 17));
    CHECK(!curate_choices_header("# suit choices 2", 16));
    CHECK(!curate_choices_header("# suit choices 1\r\r", 18));
    CHECK(!curate_choices_header("# suit choices", 14));
    CHECK(!curate_choices_header("", 0));
    CHECK(!curate_choices_header("\r", 1));
    CHECK(!curate_choices_header("keep skill main a", 17));
}

static void test_call_lines(void)
{
    // the harness key
    ConfError e;
    CHECK(parse("[harness h]\nskills.call = disable-model-invocation: true\n", &e));
    CHECK(parse("[harness h]\nskills.call = a.b_c-9: x y:z\n", &e));
    expect_error("[harness h]\nskills.call = nocolon\n", 2, "takes one front matter line, NAME: VALUE, of at most 200 bytes");
    expect_error("[harness h]\nskills.call = a:b\n", 2, "front matter line");
    expect_error("[harness h]\nskills.call = a:  b\n", 2, "front matter line");
    expect_error("[harness h]\nskills.call = a b: c\n", 2, "front matter line");
    expect_error("[harness h]\nskills.call = : c\n", 2, "front matter line");
    expect_error("[harness h]\nskills.call = a: c\tb\n", 2, "front matter line");
    expect_error("[harness h]\nskills.call = a: x\nskills.call = a: y\n", 3, "");
    expect_error("[outfit o]\nskills.call = a: b\n", 2, "");
    CHECK(conf_header_line_ok("a: b", 4));
    CHECK(!conf_header_line_ok("a: ", 3));
    CHECK(!conf_header_line_ok("a: b ", 5));
    CHECK(!conf_header_line_ok("a: b\x7f", 5));
    CHECK(!conf_header_line_ok("a:", 2));
    CHECK(!conf_header_line_ok("a:bc", 4));
    CHECK(!conf_header_line_ok("ab c", 4));
    CHECK(!conf_header_line_ok("", 0));
    char longest[202];
    memset(longest, 'v', sizeof longest);
    memcpy(longest, "k: ", 3);
    CHECK(conf_header_line_ok(longest, 200));
    CHECK(!conf_header_line_ok(longest, 201));

    // the verbs
    CurateChoice c;
    char msg[256];
    CHECK(choice_line("call skill main alpha", &c, msg) == CHOICE_OK && c.act == CHOICE_CALL && c.kind == 0);
    CHECK(choice_line("auto skill main alpha", &c, msg) == CHOICE_OK && c.act == CHOICE_AUTO);
    CHECK(choice_line("call agent main alpha", &c, msg) == CHOICE_BAD && strcmp(msg, "call is for a skill, not agent") == 0);
    CHECK(choice_line("auto command main alpha", &c, msg) == CHOICE_BAD && strcmp(msg, "auto is for a skill, not command") == 0);
    CHECK(choice_line("call skill main alpha github.com/o/p", &c, msg) == CHOICE_BAD && strstr(msg, "keep, retire, call and auto takes 3 fields") == msg);

    // the front matter
    const char *lines[] = {"disable-model-invocation: true", "x-hidden: yes"};
    uint64_t have = 9;
    CHECK(curate_front_has("no", 2, lines, 2, &have) == FRONT_NONE && have == 0);
    CHECK(curate_front_has("---", 3, lines, 2, &have) == FRONT_NONE);
    CHECK(curate_front_has("---\na: b\n", 9, lines, 2, &have) == FRONT_NONE);
    CHECK(curate_front_has("---\na: b", 8, lines, 2, &have) == FRONT_NONE);
    const char *both = "---\nx-hidden: yes\ndisable-model-invocation: true\r\n---";
    CHECK(curate_front_has(both, strlen(both), lines, 2, &have) == FRONT_OK && have == 3);
    const char *same_length = "---\ndisable-model-invocation: nope\n---\n";
    CHECK(curate_front_has(same_length, strlen(same_length), lines, 2, &have) == FRONT_OK && have == 0);
    const char *after = "---\n---\ndisable-model-invocation: true\n";
    CHECK(curate_front_has(after, strlen(after), lines, 2, &have) == FRONT_OK && have == 0);
    char out[256];
    size_t olen = 0;
    const char *named = "---\nname: n\nx-hidden: yes\n---\nbody";
    CHECK(curate_front_edit(named, strlen(named), lines, 2, true, out, sizeof out, &olen) == FRONT_OK);
    CHECK(olen == strlen("---\nname: n\ndisable-model-invocation: true\nx-hidden: yes\n---\nbody") &&
        memcmp(out, "---\nname: n\ndisable-model-invocation: true\nx-hidden: yes\n---\nbody", olen) == 0);
    const char *crlf = "---\r\nd: x\r\n---\r\n";
    CHECK(curate_front_edit(crlf, strlen(crlf), lines, 1, true, out, sizeof out, &olen) == FRONT_OK);
    CHECK(olen == strlen("---\r\ndisable-model-invocation: true\r\nd: x\r\n---\r\n") &&
        memcmp(out, "---\r\ndisable-model-invocation: true\r\nd: x\r\n---\r\n", olen) == 0);
    const char *twice = "---\nname: n\ndisable-model-invocation: true\nkeep: me\ndisable-model-invocation: true\n---\ndisable-model-invocation: true\n";
    CHECK(curate_front_edit(twice, strlen(twice), lines, 2, false, out, sizeof out, &olen) == FRONT_OK);
    CHECK(olen == strlen("---\nname: n\nkeep: me\n---\ndisable-model-invocation: true\n") &&
        memcmp(out, "---\nname: n\nkeep: me\n---\ndisable-model-invocation: true\n", olen) == 0);
    CHECK(curate_front_edit("x", 1, lines, 2, true, out, sizeof out, &olen) == FRONT_NONE);
    CHECK(curate_front_edit(named, strlen(named), lines, 2, true, out, 10, &olen) == FRONT_FULL);
    CHECK(curate_front_edit(twice, strlen(twice), lines, 2, false, out, 10, &olen) == FRONT_FULL);
}

static void test_choices_lines(void)
{
    CurateChoice c;
    char msg[256];
    CHECK(choice_line("", &c, msg) == CHOICE_NONE);
    CHECK(choice_line("\r", &c, msg) == CHOICE_NONE);
    CHECK(choice_line("# a comment", &c, msg) == CHOICE_NONE);
    CHECK(choice_line("#keep skill main a", &c, msg) == CHOICE_NONE);
    CHECK(choice_line("keep skill main alpha", &c, msg) == CHOICE_OK);
    CHECK(c.act == CHOICE_KEEP && c.kind == 0 && strcmp(c.ward, "main") == 0 && strcmp(c.name, "alpha") == 0 && c.project[0] == '\0');
    CHECK(choice_line("retire agent side a.b_c-d\r", &c, msg) == CHOICE_OK);
    CHECK(c.act == CHOICE_RETIRE && c.kind == 1 && strcmp(c.ward, "side") == 0 && strcmp(c.name, "a.b_c-d") == 0);
    CHECK(choice_line("keep command m x", &c, msg) == CHOICE_OK && c.kind == 2);
    CHECK(choice_line("personal skill main alpha github.com/o/r", &c, msg) == CHOICE_OK);
    CHECK(c.act == CHOICE_PERSONAL && strcmp(c.project, "github.com/o/r") == 0);
    CHECK(choice_line("personal skill main alpha host:8080/a@b~c/d", &c, msg) == CHOICE_OK && strcmp(c.project, "host:8080/a@b~c/d") == 0);
    CHECK(choice_line("personal skill main alpha a~", &c, msg) == CHOICE_OK);
    // a name of 128 bytes is one, 129 is not
    char long_name[200];
    char line[400];
    memset(long_name, 'n', 128);
    long_name[128] = '\0';
    snprintf(line, sizeof line, "keep skill main %s", long_name);
    CHECK(choice_line(line, &c, msg) == CHOICE_OK && strlen(c.name) == 128);
    long_name[128] = 'n';
    long_name[129] = '\0';
    snprintf(line, sizeof line, "keep skill main %s", long_name);
    CHECK(choice_line(line, &c, msg) == CHOICE_BAD && strstr(msg, "NAME is not a name: ") == msg);
    CHECK(strlen(msg) < 80);
    // a wardrobe of 128 bytes is one (its outfits are refused later, not here)
    char wline[400];
    char w128[129];
    memset(w128, 'W', 128);
    w128[128] = '\0';
    snprintf(wline, sizeof wline, "personal skill %s n github.com/o/p", w128);
    CHECK(choice_line(wline, &c, msg) == CHOICE_OK && strlen(c.ward) == 128);
    snprintf(wline, sizeof wline, "personal skill %sW n github.com/o/p", w128);
    CHECK(choice_line(wline, &c, msg) == CHOICE_BAD && strstr(msg, "WARDROBE is not a name") == msg);
    // a project of 512 bytes is one, 513 is not
    char project[600];
    char big[800];
    memset(project, 'p', 512);
    project[512] = '\0';
    snprintf(big, sizeof big, "personal skill main a %s", project);
    CHECK(choice_line(big, &c, msg) == CHOICE_OK && strlen(c.project) == 512);
    project[512] = 'p';
    project[513] = '\0';
    snprintf(big, sizeof big, "personal skill main a %s", project);
    CHECK(choice_line(big, &c, msg) == CHOICE_BAD && strstr(msg, "PROJECT is not a project key: ") == msg);
    // a folder, or nothing, is refused for the line, and says so
    CHECK(choice_line("personal skill main a ~/work/p", &c, msg) == CHOICE_FOLDER && strstr(msg, "PROJECT is a folder, not a project key") == msg);
    CHECK(choice_line("personal skill main a /work/p", &c, msg) == CHOICE_FOLDER);
    CHECK(choice_line("personal skill main a -", &c, msg) == CHOICE_FOLDER);
    CHECK(choice_line("personal skill main a -x", &c, msg) == CHOICE_OK);
    CHECK(choice_line("personal skill main a x/~", &c, msg) == CHOICE_OK);
    // a NUL byte is never part of a field; in a comment it is nothing
    CHECK(curate_choice_parse("keep skill main \0", 17, &c, msg, sizeof msg) == CHOICE_BAD && strcmp(msg, "NUL byte in line") == 0);
    CHECK(curate_choice_parse("personal skill main a x\0y", 25, &c, msg, sizeof msg) == CHOICE_BAD);
    CHECK(curate_choice_parse("# a\0b", 6, &c, msg, sizeof msg) == CHOICE_NONE);
    // malformed
    CHECK(choice_line("frobnicate skill main a", &c, msg) == CHOICE_BAD && strstr(msg, "unknown choice (keep, retire, personal, call or auto): 'frobnicate'") == msg);
    CHECK(choice_line("keep", &c, msg) == CHOICE_BAD && strstr(msg, "takes 3 fields") != nullptr && strstr(msg, "has 0") != nullptr);
    CHECK(choice_line("keep skill main", &c, msg) == CHOICE_BAD && strstr(msg, "has 2") != nullptr);
    CHECK(choice_line("keep skill main a b", &c, msg) == CHOICE_BAD && strstr(msg, "has 4") != nullptr);
    CHECK(choice_line("personal skill main a", &c, msg) == CHOICE_BAD && strstr(msg, "personal takes 4 fields, KIND WARDROBE NAME PROJECT, and this has 3") != nullptr);
    CHECK(choice_line("personal skill main a b c", &c, msg) == CHOICE_BAD && strstr(msg, "too many fields") != nullptr);
    CHECK(choice_line("keep skill main a b c", &c, msg) == CHOICE_BAD && strstr(msg, "too many fields") != nullptr);
    CHECK(choice_line("keep skills main a", &c, msg) == CHOICE_BAD && strstr(msg, "KIND is skill, agent or command, not 'skills'") == msg);
    CHECK(choice_line("keep instructions main a", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("keep skill ma/in a", &c, msg) == CHOICE_BAD && strstr(msg, "WARDROBE is not a name: 'ma/in'") == msg);
    CHECK(choice_line("keep skill  a", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("keep skill main a/b", &c, msg) == CHOICE_BAD && strstr(msg, "NAME is not a name: 'a/b'") == msg);
    CHECK(choice_line("keep skill main a*", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("keep skill main a ", &c, msg) == CHOICE_BAD);
    CHECK(choice_line(" keep skill main a", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("Keep skill main a", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("personal skill main a pro!ject", &c, msg) == CHOICE_BAD && strstr(msg, "PROJECT is not a project key: 'pro!ject'") == msg);
    CHECK(choice_line("personal skill main a pro\xC3\xA9", &c, msg) == CHOICE_BAD);
    CHECK(choice_line("personal skill main a ", &c, msg) == CHOICE_BAD);
    // a long echoed field is cut
    snprintf(big, sizeof big, "frobnicate%s skill main a", project);
    CHECK(choice_line(big, &c, msg) == CHOICE_BAD && strlen(msg) < 130);
    // every byte, as the last byte of a project: a key's characters only
    for (int b = 1; b < 256; b++) {
        char one[40] = "personal skill main a x";
        one[strlen(one)] = (char)b;
        bool want = (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '\r' || strchr("._-/:@~", b) != nullptr;
        CHECK((choice_line(one, &c, msg) == CHOICE_OK) == want);
    }
    // the message fits a small buffer
    char tiny[12];
    CHECK(curate_choice_parse("keep skillz main a", 18, &c, tiny, sizeof tiny) == CHOICE_BAD && strlen(tiny) == 11);
}

static void test_personal_outfit(void)
{
    char out[CONF_NAME_MAX + 1];
    CHECK(curate_personal_outfit("main", "github.com/o/solo", 1, out) == 31 && strcmp(out, "personal.main.github.com-o-solo") == 0);
    CHECK(curate_personal_outfit("main", "github.com/o/solo", 0, out) == 31 && strcmp(out, "personal.main.github.com-o-solo") == 0);
    CHECK(curate_personal_outfit("side", "github.com/o/solo", 2, out) == 33 && strcmp(out, "personal.side.github.com-o-solo-2") == 0);
    CHECK(curate_personal_outfit("m", "github.com/o/solo", 12, out) == 31 && strcmp(out, "personal.m.github.com-o-solo-12") == 0);
    CHECK(curate_personal_outfit("m", "a.b_c-d/e:f@g~h", 1, out) == 26 && strcmp(out, "personal.m.a.b_c-d-e-f-g-h") == 0);
    CHECK(curate_personal_outfit("m", "github.com/o/a-b", 1, out) == curate_personal_outfit("m", "github.com/o/a/b", 1, out));
    CHECK(curate_personal_outfit("m", "", 1, out) == 11 && strcmp(out, "personal.m.") == 0);
    for (int b = 1; b < 256; b++) {
        char one[4] = {'a', (char)b, 'c', '\0'};
        bool same = (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '.' || b == '_' || b == '-';
        CHECK(curate_personal_outfit("m", one, 1, out) == 14 && out[12] == (same ? (char)b : '-'));
    }
    char project[300];
    memset(project, 'x', 299);
    project[299] = '\0';
    CHECK(curate_personal_outfit("main", project, 1, out) == CONF_NAME_MAX && out[CONF_NAME_MAX] == '\0');
    CHECK(conf_name_ok(out, strlen(out), false));
    CHECK(curate_personal_outfit("main", project, 2, out) == CONF_NAME_MAX && strcmp(out + 126, "-2") == 0);
    CHECK(curate_personal_outfit("main", project, 100, out) == CONF_NAME_MAX && strcmp(out + 124, "-100") == 0);
    // a wardrobe name that leaves no room: refused, with or without a suffix
    char ward[CONF_NAME_MAX + 1];
    memset(ward, 'w', CONF_NAME_MAX);
    ward[CONF_NAME_MAX] = '\0';
    CHECK(curate_personal_outfit(ward, "p", 1, out) == 0);
    ward[119] = '\0';  // personal. and this make 128 bytes, and no dot
    CHECK(curate_personal_outfit(ward, "p", 1, out) == 0);
    ward[118] = '\0';  // and the dot make 128: it fits, with nothing of the project
    CHECK(curate_personal_outfit(ward, "p", 1, out) == CONF_NAME_MAX && out[127] == '.');
    CHECK(curate_personal_outfit(ward, "p", 2, out) == 0);
    ward[117] = '\0';
    CHECK(curate_personal_outfit(ward, "p", 1, out) == CONF_NAME_MAX && out[127] == 'p');
    CHECK(curate_home_outfit("kept", "main", out) == 9 && strcmp(out, "kept.main") == 0);
    memset(ward, 'w', 123);
    ward[123] = '\0';  // kept. and this are 128 bytes
    CHECK(curate_home_outfit("kept", ward, out) == CONF_NAME_MAX && out[4] == '.');
    CHECK(curate_home_outfit("attic", ward, out) == 0);
    ward[122] = '\0';
    CHECK(curate_home_outfit("attic", ward, out) == CONF_NAME_MAX);
    memset(ward, 'w', 124);
    ward[124] = '\0';
    CHECK(curate_home_outfit("kept", ward, out) == 0);
    CHECK(curate_is_attic("attic") && curate_is_attic("attic.main") && curate_is_attic("attic."));
    CHECK(!curate_is_attic("atticus") && !curate_is_attic("attic-main") && !curate_is_attic("kept.attic") && !curate_is_attic("") && !curate_is_attic("att"));
}

// An edit applied to TEXT, in a buffer of CAP bytes: the new text.
static char edit_buf[1 << 16];
static size_t edit_len;

static void edit_start(const char *t)
{
    edit_len = strlen(t);
    memcpy(edit_buf, t, edit_len);
}

static bool edit_is(const char *want)
{
    bool same = edit_len == strlen(want) && memcmp(edit_buf, want, edit_len) == 0;
    if (!same) printf("  edit: got '%.*s', want '%s'\n", (int)edit_len, edit_buf, want);
    return same;
}

static EditResult edit_value(int line, size_t cap, const char *a, const char *b, const char *c)
{
    const char *words[3];
    size_t n = 0;
    if (a != nullptr) words[n++] = a;
    if (b != nullptr) words[n++] = b;
    if (c != nullptr) words[n++] = c;
    return curate_edit_value(edit_buf, &edit_len, cap, line, words, n);
}

static void test_edit_value(void)
{
    constexpr size_t ROOM = sizeof edit_buf;
    // the key as written, the spacing round the value, a comment and the rest are kept
    edit_start("[outfit o]\nskills = a b c\nagents = x\n");
    CHECK(edit_value(2, ROOM, "a", "c", nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\nskills = a c\nagents = x\n"));
    edit_start("[outfit o]\n  skills   =   a  b   # three\t\nagents = x\n");
    CHECK(edit_value(2, ROOM, "b", nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\n  skills   =   b   # three\t\nagents = x\n"));
    edit_start("[outfit o]\nskills = a b #c\n");
    CHECK(edit_value(2, ROOM, "a", "b", "z") == EDIT_OK);
    CHECK(edit_is("[outfit o]\nskills = a b z #c\n"));
    // a # inside a word is not a comment
    edit_start("[outfit o]\nskills = a#b c\n");
    CHECK(edit_value(2, ROOM, "a#b", nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\nskills = a#b\n"));
    // CR LF stays
    edit_start("[outfit o]\r\nskills = a b\r\nagents = x\r\n");
    CHECK(edit_value(2, ROOM, "b", nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\r\nskills = b\r\nagents = x\r\n"));
    // the first line, the last line with no newline
    edit_start("skills = a b");
    CHECK(edit_value(1, ROOM, "a", "b", "c") == EDIT_OK);
    CHECK(edit_is("skills = a b c"));
    // removing a line: in the middle, the first, the last with a newline
    edit_start("[outfit o]\nskills = a\nagents = x\n");
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\nagents = x\n"));
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\n"));
    edit_start("skills = a\nagents = x\n");
    CHECK(edit_value(1, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("agents = x\n"));
    CHECK(edit_value(1, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is(""));
    // removing the last line, which has no newline: the newline before it goes too
    edit_start("[outfit o]\nskills = a");
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]"));
    edit_start("[outfit o]\r\nskills = a");
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]"));
    edit_start("[outfit o]\n\nskills = a");
    CHECK(edit_value(3, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("[outfit o]\n"));
    edit_start("skills = a");
    CHECK(edit_value(1, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is(""));
    edit_start("x\nskills = a");
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is("x"));
    edit_start("\nskills = a");
    CHECK(edit_value(2, ROOM, nullptr, nullptr, nullptr) == EDIT_OK);
    CHECK(edit_is(""));
    // a line of 4096 bytes is allowed, one of 4097 is not
    char word[5000];
    memset(word, 'w', 4087);
    word[4087] = '\0';
    edit_start("skills = a\n");
    CHECK(edit_value(1, ROOM, word, nullptr, nullptr) == EDIT_OK && edit_len == 4096 + 1);
    word[4087] = 'w';
    word[4088] = '\0';
    edit_start("skills = a\n");
    CHECK(edit_value(1, ROOM, word, nullptr, nullptr) == EDIT_LONG);
    CHECK(edit_is("skills = a\n"));
    // the CR counts in the line
    edit_start("skills = a\r\n");
    word[4087] = '\0';
    CHECK(edit_value(1, ROOM, word, nullptr, nullptr) == EDIT_LONG);
    // no room
    edit_start("skills = a\n");
    CHECK(edit_value(1, 12, "a", "b", nullptr) == EDIT_FULL);
    CHECK(edit_is("skills = a\n"));
    CHECK(edit_value(1, 13, "a", "b", nullptr) == EDIT_OK);
    CHECK(edit_is("skills = a b\n"));
}

static void test_edit_insert(void)
{
    constexpr size_t ROOM = sizeof edit_buf;
    edit_start("[outfit o]\nskills = a\n[outfit p]\n");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 2, "agents = x") == EDIT_OK);
    CHECK(edit_is("[outfit o]\nskills = a\nagents = x\n[outfit p]\n"));
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 1, "include = q") == EDIT_OK);
    CHECK(edit_is("[outfit o]\ninclude = q\nskills = a\nagents = x\n[outfit p]\n"));
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 5, "skills = z") == EDIT_OK);
    CHECK(edit_is("[outfit o]\ninclude = q\nskills = a\nagents = x\n[outfit p]\nskills = z\n"));
    // CR LF: the new line ends as the first does
    edit_start("[outfit o]\r\nskills = a\r\n");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 1, "agents = x") == EDIT_OK);
    CHECK(edit_is("[outfit o]\r\nagents = x\r\nskills = a\r\n"));
    // the last line has no newline: the new one follows it and has none either
    edit_start("[outfit o]");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 1, "skills = a") == EDIT_OK);
    CHECK(edit_is("[outfit o]\nskills = a"));
    edit_start("[outfit o]\r\nx = y");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 2, "skills = a") == EDIT_OK);
    CHECK(edit_is("[outfit o]\r\nx = y\r\nskills = a"));
    // limits
    char big[5000];
    memset(big, 'z', 4096);
    big[4096] = '\0';
    edit_start("[outfit o]\n");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 1, big) == EDIT_OK && edit_len == 11 + 4097);
    big[4096] = 'z';
    big[4097] = '\0';
    edit_start("[outfit o]\n");
    CHECK(curate_edit_insert(edit_buf, &edit_len, ROOM, 1, big) == EDIT_LONG);
    CHECK(curate_edit_insert(edit_buf, &edit_len, 12, 1, "a") == EDIT_FULL);
    CHECK(curate_edit_insert(edit_buf, &edit_len, 13, 1, "a") == EDIT_OK);
    CHECK(edit_is("[outfit o]\na\n"));
}

static void test_edit_append(void)
{
    constexpr size_t ROOM = sizeof edit_buf;
    edit_start("");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[outfit kept]", "skills = a") == EDIT_OK);
    CHECK(edit_is("[outfit kept]\nskills = a\n"));
    edit_start("x = y\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[outfit kept]", nullptr) == EDIT_OK);
    CHECK(edit_is("x = y\n\n[outfit kept]\n"));
    edit_start("x = y");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[outfit kept]", "skills = a") == EDIT_OK);
    CHECK(edit_is("x = y\n\n[outfit kept]\nskills = a\n"));
    // a blank line already ends the text: no second one
    edit_start("x = y\n\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("x = y\n\n[a]\n"));
    edit_start("x = y\n  \t\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("x = y\n  \t\n[a]\n"));
    edit_start("\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("\n[a]\n"));
    edit_start("x = y\r\n\r\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", "k = v") == EDIT_OK);
    CHECK(edit_is("x = y\r\n\r\n[a]\r\nk = v\r\n"));
    edit_start("x = y\r\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("x = y\r\n\r\n[a]\r\n"));
    edit_start("x = y\r\nz = w");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("x = y\r\nz = w\r\n\r\n[a]\r\n"));
    // the text is only white space and no newline: it ends, then a blank line
    edit_start("  ");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("  \n\n[a]\n"));
    // limits
    char big[5000];
    memset(big, 'z', 4097);
    big[4097] = '\0';
    edit_start("x\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, big, nullptr) == EDIT_LONG);
    CHECK(curate_edit_append(edit_buf, &edit_len, ROOM, "[a]", big) == EDIT_LONG);
    CHECK(curate_edit_append(edit_buf, &edit_len, 6, "[a]", nullptr) == EDIT_FULL);
    CHECK(curate_edit_append(edit_buf, &edit_len, 7, "[a]", nullptr) == EDIT_OK);
    CHECK(edit_is("x\n\n[a]\n"));
    edit_start("x\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, 11, "[a]", "k=v") == EDIT_OK);
    CHECK(edit_is("x\n\n[a]\nk=v\n"));
    edit_start("x\n");
    CHECK(curate_edit_append(edit_buf, &edit_len, 10, "[a]", "k=v") == EDIT_FULL);
}



// ---- the certificate bundle reader ------------------------------------------

static Anchors anchors;
static unsigned char pem_buf[ANCHORS_FILE_MAX + 2];
static char anchors_dir[4096];
static char anchors_path[4200];

static size_t read_fixture(const char *path, unsigned char *buf, size_t cap)
{
    FILE *f = fopen(path, "rb");
    if (f == nullptr) return 0;
    size_t n = fread(buf, 1, cap, f);
    fclose(f);
    return n;
}

static bool parse_pem(const char *pem, char *reason)
{
    return anchors_parse(&anchors, (const unsigned char *)pem, strlen(pem), reason, 200);
}

static void test_anchors_parse(void)
{
    char why[200];
    unsigned char ec[4096];
    unsigned char rsa[4096];
    size_t nec = read_fixture("test/fixtures/ec-ca.pem", ec, sizeof ec);
    size_t nrsa = read_fixture("test/fixtures/rsa-leaf.pem", rsa, sizeof rsa);
    CHECK(nec > 0 && nrsa > 0);
    CHECK(anchors_parse(&anchors, ec, nec, why, sizeof why));
    CHECK(anchors.n == 1 && anchors.skipped == 0);
    CHECK(anchors.ta[0].flags == BR_X509_TA_CA && anchors.ta[0].pkey.key_type == BR_KEYTYPE_EC);
    CHECK(anchors.ta[0].dn.len > 0 && anchors.ta[0].pkey.key.ec.qlen == 65);
    CHECK(anchors_parse(&anchors, rsa, nrsa, why, sizeof why));
    CHECK(anchors.n == 1 && anchors.ta[0].flags == 0 && anchors.ta[0].pkey.key_type == BR_KEYTYPE_RSA);
    CHECK(anchors.ta[0].pkey.key.rsa.nlen == 256 && anchors.ta[0].pkey.key.rsa.elen == 3);
    // both, a key between them that is not a certificate, no newline at the end
    size_t n = 0;
    memcpy(pem_buf, ec, nec);
    n += nec;
    const char *other = "junk before\n-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
    memcpy(pem_buf + n, other, strlen(other));
    n += strlen(other);
    memcpy(pem_buf + n, rsa, nrsa - 1);
    n += nrsa - 1;
    CHECK(anchors_parse(&anchors, pem_buf, n, why, sizeof why));
    CHECK(anchors.n == 2 && anchors.ta[1].pkey.key_type == BR_KEYTYPE_RSA);
    CHECK(parse_pem("", why) && anchors.n == 0);
    CHECK(parse_pem("no PEM here at all\n", why) && anchors.n == 0);
    CHECK(!parse_pem("-----BEGIN CERTIFICATE-----\n@@@@\n-----END CERTIFICATE-----\n", why));
    CHECK(strcmp(why, "it is not PEM text") == 0 && anchors.n == 0);
    CHECK(!parse_pem("-----BEGIN CERTIFICATE-----\nMIIB\n", why));
    CHECK(strcmp(why, "its last PEM object has no END line") == 0);
    // a certificate BearSSL cannot read is passed over
    CHECK(parse_pem("-----BEGIN CERTIFICATE-----\nMIIBAAAA\n-----END CERTIFICATE-----\n", why));
    CHECK(anchors.n == 0 && anchors.skipped == 1);
}

static void test_anchors_limits(void)
{
    char why[200];
    unsigned char ec[4096];
    size_t nec = read_fixture("test/fixtures/ec-ca.pem", ec, sizeof ec);
    // a certificate over ANCHORS_DER_MAX bytes is passed over
    size_t n = 0;
    const char *begin = "-----BEGIN CERTIFICATE-----\n";
    const char *end = "-----END CERTIFICATE-----\n";
    memcpy(pem_buf, begin, strlen(begin));
    n += strlen(begin);
    for (int line = 0; line < 400; line++) {
        memset(pem_buf + n, 'A', 64);
        pem_buf[n + 64] = '\n';
        n += 65;
    }
    memcpy(pem_buf + n, end, strlen(end));
    n += strlen(end);
    memcpy(pem_buf + n, ec, nec);
    n += nec;
    CHECK(anchors_parse(&anchors, pem_buf, n, why, sizeof why));
    CHECK(anchors.n == 1 && anchors.skipped == 1);
    // ANCHORS_MAX certificates, then one more
    n = 0;
    for (size_t i = 0; i < ANCHORS_MAX; i++) {
        memcpy(pem_buf + n, ec, nec);
        n += nec;
    }
    CHECK(anchors_parse(&anchors, pem_buf, n, why, sizeof why) && anchors.n == ANCHORS_MAX);
    memcpy(pem_buf + n, ec, nec);
    n += nec;
    CHECK(!anchors_parse(&anchors, pem_buf, n, why, sizeof why));
    CHECK(strcmp(why, "more than 512 certificates") == 0 && anchors.n == 0);
    memset(pem_buf, '\n', ANCHORS_FILE_MAX + 1);
    CHECK(anchors_parse(&anchors, pem_buf, ANCHORS_FILE_MAX, why, sizeof why));
    CHECK(!anchors_parse(&anchors, pem_buf, ANCHORS_FILE_MAX + 1, why, sizeof why));
    CHECK(strcmp(why, "it is over 1048576 bytes") == 0);
}

static int load_ok(void)
{
    char why[400];
    char used[4200];
    return anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why) && anchors.n == 1 ? 0 : 1;
}

static int load_fails_eio(void)
{
    char why[400];
    char used[4200];
    return !anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why) && strstr(why, "cannot read") != nullptr ? 0 : 1;
}

static char trust_path[4200];

static int load_trust_fails(void)
{
    char why[400];
    char used[4200];
    return !anchors_load(&anchors, trust_path, used, sizeof used, why, sizeof why) && why[0] != '\0' ? 0 : 1;
}

// A file of PEM at PATH with MODE.
static void put_pem(const char *path, const unsigned char *pem, size_t n, mode_t mode)
{
    FILE *f = fopen(path, "wb");
    CHECK(f != nullptr && fwrite(pem, 1, n, f) == n);
    fclose(f);
    CHECK(chmod(path, mode) == 0);
}

// LOAD (with CA_FILE, or the bundles when null) is refused, and the message holds WANT.
static void refused(const char *ca_file, const char *want)
{
    char why[600];
    char used[4200];
    bool ok = anchors_load(&anchors, ca_file, used, sizeof used, why, sizeof why);
    CHECK(!ok && strstr(why, want) != nullptr);
    if (ok || strstr(why, want) == nullptr) printf("  got: %s\n", ok ? "loaded" : why);
}

static void test_anchors_trust(const unsigned char *ec, size_t nec)
{
    char why[400];
    char used[4200];
    char p[4200];
    char link[4200];
    char sub[4200];
    snprintf(p, sizeof p, "%s/t.pem", anchors_dir);
    snprintf(link, sizeof link, "%s/link.pem", anchors_dir);
    snprintf(sub, sizeof sub, "%s/open", anchors_dir);
    put_pem(p, ec, nec, 0644);
    CHECK(anchors_load(&anchors, p, used, sizeof used, why, sizeof why));
    // a file group or others can write
    CHECK(chmod(p, 0664) == 0);
    refused(p, "t.pem is not trusted: it can be written by group or others");
    CHECK(chmod(p, 0646) == 0);
    refused(p, "it can be written by group or others");
    CHECK(chmod(p, 0644) == 0);
    // a file of another user: the test pretends to be someone else
    setenv("SUIT_UID", "4242", 1);
    refused(p, "t.pem is not trusted: it belongs to another user");
    unsetenv("SUIT_UID");
    // a symbolic link: refused as a CA file, followed as a bundle
    CHECK(symlink(p, link) == 0);
    refused(link, "cannot read");
    setenv("SSL_CERT_FILE", link, 1);
    CHECK(anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why) && anchors.n == 1);
    unlink(link);
    // a FIFO is refused at once, never waited on
    CHECK(mkfifo(link, 0600) == 0);
    refused(link, "is not trusted: it is not a regular file");
    unlink(link);
    // a folder others can write, sticky or not
    CHECK(mkdir(sub, 0700) == 0);
    char inner[4300];
    snprintf(inner, sizeof inner, "%s/ca.pem", sub);
    put_pem(inner, ec, nec, 0644);
    CHECK(chmod(sub, 0777) == 0);
    refused(inner, "ca.pem is not trusted: its folder can be written by group or others");
    CHECK(chmod(sub, 01777) == 0);
    refused(inner, "its folder can be written by group or others");
    CHECK(chmod(sub, 0770) == 0);
    refused(inner, "its folder can be written by group or others");
    CHECK(chmod(sub, 0700) == 0);
    CHECK(anchors_load(&anchors, inner, used, sizeof used, why, sizeof why));
    unlink(inner);
    rmdir(sub);
    // a relative SSL_CERT_FILE
    setenv("SSL_CERT_FILE", "ca.pem", 1);
    refused(nullptr, "ca.pem: a certificate file's path is absolute");
    unsetenv("SSL_CERT_FILE");
    // the calls that look at the file and its folder failing
    snprintf(trust_path, sizeof trust_path, "%s", p);
    CHECK(in_child("fstat:1", load_trust_fails) == 0);
    CHECK(in_child("stat:1", load_trust_fails) == 0);
    unlink(p);
}

static void test_anchors_load(void)
{
    char why[400];
    char used[4200];
    char cwd[2048];
    CHECK(getcwd(cwd, sizeof cwd) != nullptr);
    snprintf(anchors_dir, sizeof anchors_dir, "%s/build/tmp/unit-anchors.XXXXXX", cwd);
    CHECK(mkdtemp(anchors_dir) != nullptr);
    snprintf(anchors_path, sizeof anchors_path, "%s/ca.pem", anchors_dir);
    unsigned char ec[4096];
    size_t nec = read_fixture("test/fixtures/ec-ca.pem", ec, sizeof ec);
    FILE *f = fopen(anchors_path, "wb");
    CHECK(f != nullptr && fwrite(ec, 1, nec, f) == nec);
    fclose(f);
    CHECK(chmod(anchors_path, 0644) == 0);  // whatever the umask
    CHECK(anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why));
    CHECK(anchors.n == 1 && strcmp(used, anchors_path) == 0);
    CHECK(!anchors_load(&anchors, "/nonexistent/ca.pem", used, sizeof used, why, sizeof why));
    CHECK(strcmp(why, "no certificate file: none of /nonexistent/ca.pem exists") == 0 && used[0] == '\0');
    CHECK(!anchors_load(&anchors, anchors_dir, used, sizeof used, why, sizeof why));
    CHECK(strstr(why, "is not trusted: it is not a regular file") != nullptr);
    // the environment: SSL_CERT_FILE first, then the system's (here one named file)
    unsetenv("SSL_CERT_FILE");
    setenv("SUIT_CA_BUNDLE", "/nonexistent/system.pem", 1);
    CHECK(!anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why));
    CHECK(strcmp(why, "no certificate file: none of /nonexistent/system.pem exists; set SSL_CERT_FILE to the system's bundle") == 0);
    setenv("SSL_CERT_FILE", "", 1);
    CHECK(!anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why));
    setenv("SSL_CERT_FILE", "/nonexistent/env.pem", 1);
    CHECK(!anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why));
    CHECK(strstr(why, "none of /nonexistent/env.pem, /nonexistent/system.pem exists") != nullptr);
    setenv("SSL_CERT_FILE", anchors_path, 1);
    CHECK(anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why) && strcmp(used, anchors_path) == 0);
    setenv("SSL_CERT_FILE", "/nonexistent/env.pem", 1);
    setenv("SUIT_CA_BUNDLE", anchors_path, 1);
    CHECK(anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why) && strcmp(used, anchors_path) == 0);
    unsetenv("SSL_CERT_FILE");
    unsetenv("SUIT_CA_BUNDLE");
    // the system's own list: whatever it holds, the answer is clean
    bool sys = anchors_load(&anchors, nullptr, used, sizeof used, why, sizeof why);
    CHECK(sys ? anchors.n > 0 : why[0] != '\0');
    CHECK(in_child("open:1:EACCES", load_fails_eio) == 0);
    CHECK(in_child("read:1", load_fails_eio) == 0);
    CHECK(in_child("read:1:EINTR", load_ok) == 0);
    CHECK(in_child("read:2:EINTR", load_ok) == 0);
    // a file that is not PEM, and one that is too long
    f = fopen(anchors_path, "wb");
    CHECK(f != nullptr && fputs("hello\n", f) >= 0);
    fclose(f);
    CHECK(chmod(anchors_path, 0644) == 0);  // whatever the umask
    CHECK(!anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why));
    CHECK(strstr(why, "ca.pem holds no certificate suit can use") != nullptr);
    f = fopen(anchors_path, "wb");
    memset(pem_buf, '\n', ANCHORS_FILE_MAX + 1);
    CHECK(f != nullptr && fwrite(pem_buf, 1, ANCHORS_FILE_MAX + 1, f) == ANCHORS_FILE_MAX + 1);
    fclose(f);
    CHECK(chmod(anchors_path, 0644) == 0);  // whatever the umask
    CHECK(!anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why));
    CHECK(strstr(why, "ca.pem: it is over 1048576 bytes") != nullptr);
    f = fopen(anchors_path, "wb");
    CHECK(f != nullptr && fputs("-----BEGIN CERTIFICATE-----\n@@\n-----END CERTIFICATE-----\n", f) >= 0);
    fclose(f);
    CHECK(chmod(anchors_path, 0644) == 0);  // whatever the umask
    CHECK(!anchors_load(&anchors, anchors_path, used, sizeof used, why, sizeof why));
    CHECK(strstr(why, "ca.pem: it is not PEM text") != nullptr);
    unlink(anchors_path);
    test_anchors_trust(ec, nec);
    rmdir(anchors_dir);
}

static void test_anchors_path_check(void)
{
    CHECK(anchors_path_check("/etc/ssl/cert.pem") == nullptr);
    CHECK(strcmp(anchors_path_check(""), "a certificate file's path is 1 to 1024 characters") == 0);
    char longp[1100];
    memset(longp, 'a', sizeof longp - 1);
    longp[0] = '/';
    longp[sizeof longp - 1] = '\0';
    CHECK(strcmp(anchors_path_check(longp), "a certificate file's path is 1 to 1024 characters") == 0);
    longp[1024] = '\0';
    CHECK(anchors_path_check(longp) == nullptr);
    CHECK(strcmp(anchors_path_check("ca.pem"), "a certificate file's path is absolute") == 0);
    CHECK(strcmp(anchors_path_check("/a b"), "a certificate file's path has printable characters only, and no space") == 0);
    CHECK(strcmp(anchors_path_check("/a\x7f"), "a certificate file's path has printable characters only, and no space") == 0);
}

// ---- the network's wrappers -------------------------------------------------

static int w_socket(void) { return fails_eio(sys_socket(AF_INET, SOCK_STREAM, 0) < 0); }
static int w_connect(void) { return fails_eio(sys_connect(-1, nullptr, 0) < 0); }
static int w_poll(void) { return fails_eio(sys_poll(0, POLLIN, 0) < 0); }
static int w_getsockopt(void) { int e; return fails_eio(sys_socket_error(-1, &e) < 0); }
static int w_fcntl(void) { return fails_eio(sys_set_nonblock(-1) < 0); }
static int w_recv(void) { char b[1]; return fails_eio(sys_recv(-1, b, 1) < 0); }
static int w_recv_all(void) { char b[1]; return fails_eio(sys_recv_all(-1, b, 1) < 0); }
static int w_send(void) { return fails_eio(sys_send(-1, "x", 1) < 0); }
static int w_socketpair(void) { int sv[2]; return fails_eio(sys_socketpair(sv) < 0); }
static int w_fork(void) { return fails_eio(sys_fork() < 0); }
static int w_signal(void) { return fails_eio(sys_signal(getpid(), 0) < 0); }
static int w_getaddrinfo(void) { struct addrinfo *r = nullptr; return sys_getaddrinfo("localhost", "1", nullptr, &r) == EAI_FAIL ? 0 : 1; }
static int w_core(void) { return fails_eio(sys_no_core_dumps() < 0); }
static int no_core(void)
{
    struct rlimit r;
    return sys_no_core_dumps() == 0 && getrlimit(RLIMIT_CORE, &r) == 0 && r.rlim_cur == 0 && r.rlim_max == 0 ? 0 : 1;
}
static int w_entropy(void) { unsigned char b[8]; return fails_eio(sys_entropy(b, sizeof b) < 0); }

static void test_net_wrappers(void)
{
    static const struct {
        const char *spec;
        int (*fn)(void);
    } cases[] = {
        {"socket:1", w_socket}, {"connect:1", w_connect}, {"poll:1", w_poll},
        {"getsockopt:1", w_getsockopt}, {"fcntl:1", w_fcntl}, {"recv:1", w_recv},
        {"recv:1", w_recv_all}, {"send:1", w_send}, {"socketpair:1", w_socketpair},
        {"fork:1", w_fork}, {"signal:1", w_signal}, {"getaddrinfo:1", w_getaddrinfo},
        {"entropy:1", w_entropy}, {"setrlimit:1", w_core},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        CHECK(in_child(cases[i].spec, cases[i].fn) == 0);
    }
    // the calls themselves, once each
    int sv[2];
    CHECK(sys_socketpair(sv) == 0);
    CHECK(sys_set_nonblock(sv[0]) == 0);
    CHECK(sys_send(sv[1], "ab", 2) == 2);
    CHECK(sys_poll(sv[0], POLLIN, 1000) == 1);
    char b[4];
    CHECK(sys_recv(sv[0], b, 1) == 1 && b[0] == 'a');
    close(sv[1]);
    CHECK(sys_recv_all(sv[0], b, sizeof b) == 1 && b[0] == 'b');
    close(sv[0]);
    unsigned char e[32];
    CHECK(sys_entropy(e, sizeof e) == 0);
    CHECK(sys_signal(getpid(), 0) == 0);
    CHECK(in_child("", no_core) == 0);
    // what BearSSL's codes say
    char t[300];
    tls_error_text(BR_ERR_X509_NOT_TRUSTED, t, sizeof t);
    CHECK(strcmp(t, "the server's certificate is not signed by a CA suit trusts") == 0);
    tls_error_text(BR_ERR_RECV_FATAL_ALERT + 40, t, sizeof t);
    CHECK(strncmp(t, "the server ended the handshake with TLS alert 40: ", 50) == 0);
    tls_error_text(BR_ERR_RECV_FATAL_ALERT + 70, t, sizeof t);
    CHECK(strncmp(t, "the server ended the handshake with TLS alert 70 (protocol version)", 67) == 0);
    tls_error_text(BR_ERR_SEND_FATAL_ALERT + 40, t, sizeof t);
    CHECK(strcmp(t, "suit ended the handshake with TLS alert 40") == 0);
    tls_error_text(BR_ERR_BAD_MAC, t, sizeof t);
    CHECK(strcmp(t, "TLS error 7 (BearSSL's code)") == 0);
}

int main(void)
{
    test_install_plist();
    test_install_systemd();
    test_install_refusals();
    test_install_platform();
    test_valid();
    test_comments();
    test_lists();
    test_errors();
    test_wear_headers();
    test_more_errors();
    test_header_names_and_spacing();
    test_valid_names();
    test_upstream_keys();
    test_long_cycle_message();
    test_limits();
    test_line_and_file();
    test_dump_is_stable();
    test_wrapper_faults();
    test_fault_counts_calls();
    test_self_path();
    test_say_and_out();
#ifndef SUIT_COVER
    test_ensure_aborts();
#endif
    test_stamp_too_large();
    test_writer();
    test_write_keeps_mode();
    test_glob();
    test_merge();
    test_resolve();
    test_resolve_machine();
    test_join_four();
    test_resolve_errors();
    test_resolve_limits();
    test_ledger();
    test_exclude_line();
    test_place_limits();
    test_listdir();
    test_place_faults();
    test_fault_lists();
    test_project_keys();
    test_project_key_limits();
    test_project_key_ok();
    test_project_path_ok();
    test_project_git_remote();
    test_roots_parse();
    test_projects_parse();
    test_project_files();
    test_lint_refused_lines();
    test_lint_rules();
    test_lint_text();
    test_lint_load();
    test_done_parse();
    test_done_eval();
    test_usage_paths();
    test_usage_rule();
    test_usage_keys();
    test_reader_basics();
    test_reader_not_the_declared_path();
    test_reader_names();
    test_reader_whitespace_and_no_time();
    test_reader_time_and_project();
    test_reader_commands();
    test_reader_lines();
    test_reader_not_json();
    test_reader_limits();
    test_reader_depth();
    test_reader_caps();
    test_reader_chunk_edge();
    test_reader_file();
    test_tally_helpers();
    test_wall_clock();
    test_curate_front_matter();
    test_curate_json();
    test_curate_matches();
    test_curate_periods();
    test_choices_header();
    test_choices_lines();
    test_call_lines();
    test_personal_outfit();
    test_edit_value();
    test_edit_insert();
    test_edit_append();
    test_anchors_parse();
    test_anchors_limits();
    test_anchors_load();
    test_anchors_path_check();
    test_net_wrappers();
    printf("unit: %d checks, %d failed\n", checks, failures);
    return failures == 0 ? 0 : 1;
}