Skip to content
suit Artifact [ecd76fe61a]
Login

Artifact [ecd76fe61a]

Artifact ecd76fe61aa08be2347b344b18bccd7c9af9719099e6478684c40064cd98c1ec:


// 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 "conf.h"
#include "exclude.h"
#include "platform.h"
#include "ledger.h"
#include "lint.h"
#include "place.h"
#include "project.h"
#include "resolve.h"
#include "stamp.h"
#include "store_fs.h"

#include <errno.h>
#include <fcntl.h>
#include <ftw.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_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_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}, {"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->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

static bool resolve_text(const char *text, ResolveError *e)
{
    ConfError ce;
    CHECK(parse(text, &ce));
    return resolve(&conf, &assets, "/home/u", "/sh", "/sh/store/mine", 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";

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].first, "/sh/store/mine/a.md") == 0);
    CHECK(strcmp(plan.joins[0].second, "/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);
    test_machine = "";
}

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));
    CHECK(!resolve_why(&conf, &assets, "/home/u", "/sh", "/sh/store/mine", 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, nullptr, KIND_NONE};
    }
    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, nullptr, KIND_NONE};
    }
    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, nullptr, KIND_NONE}; }
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")) == 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

int main(void)
{
    test_valid();
    test_comments();
    test_lists();
    test_errors();
    test_wear_headers();
    test_more_errors();
    test_header_names_and_spacing();
    test_valid_names();
    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_resolve();
    test_resolve_machine();
    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();
    printf("unit: %d checks, %d failed\n", checks, failures);
    return failures == 0 ? 0 : 1;
}