Skip to content
pi-c Documentation
Login

Documentation

/* pic's user database: ~/.pic/pic.sqlite. Tables are prefixed picu_ (the
 * journal's are pic_, libfossil's fsl*) so one file could hold them all. */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "platform.h"
#include "sqlar.h"
#include "userdb.h"

#define USERDB_VERSION "1"

static sqlite3 *conn;
static pid_t conn_pid;

/* picu_credential: an API key, or a subscription sign-in's tokens (oauth: a
 * JSON object, sealed whole). The CHECK grew 'oauth'; credential_kinds
 * rebuilds a table made before that. */
#define CREDENTIAL_TABLE(name)                                                                                         \
    "CREATE TABLE IF NOT EXISTS " name "(name TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('api_key', 'oauth')),"\
    " sealed BLOB NOT NULL, created_ms INTEGER NOT NULL, used_ms INTEGER)"

static const char schema[] =
    "CREATE TABLE IF NOT EXISTS picu_meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);"
    "CREATE TABLE IF NOT EXISTS picu_setting(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_ms INTEGER NOT NULL);"
    /* Pi's model catalog per provider from pi.dev; models: JSON array, sqlar rule. */
    "CREATE TABLE IF NOT EXISTS picu_catalog(provider TEXT PRIMARY KEY, sz INTEGER NOT NULL, models BLOB NOT NULL,"
    " checked_ms INTEGER NOT NULL, last_modified_ms INTEGER NOT NULL, etag TEXT);"
    "CREATE TABLE IF NOT EXISTS picu_trust(path TEXT PRIMARY KEY, trusted INTEGER NOT NULL CHECK(trusted IN (0,1)),"
    " decided_ms INTEGER NOT NULL);"
    /* How often a skill was loaded (skills.c): by /skill:NAME or a read of its file. */
    "CREATE TABLE IF NOT EXISTS picu_skill_use(name TEXT NOT NULL, path TEXT NOT NULL, uses INTEGER NOT NULL,"
    " last_ms INTEGER NOT NULL, PRIMARY KEY(name, path));"
    "CREATE TABLE IF NOT EXISTS picu_scoped_model(position INTEGER PRIMARY KEY, pattern TEXT NOT NULL);"
    "CREATE TABLE IF NOT EXISTS picu_bug(id INTEGER PRIMARY KEY, created_ms INTEGER NOT NULL, workspace TEXT NOT NULL,"
    " conversation TEXT, model TEXT, description TEXT NOT NULL);"
    "CREATE TABLE IF NOT EXISTS picu_workspace(path TEXT PRIMARY KEY, journal TEXT NOT NULL, last_used_ms INTEGER NOT NULL);"
    /* Pi v3 session lines of pic's conversations, for ctx: append-only per
     * conversation; line is the JSON line, deflated when smaller (sqlar rule).
     * kind is the line's Pi type, entry the journal entry it came from. */
    "CREATE TABLE IF NOT EXISTS picu_pi_session_line(conversation TEXT NOT NULL, seq INTEGER NOT NULL,"
    " workspace TEXT NOT NULL, kind TEXT NOT NULL, entry INTEGER, sz INTEGER NOT NULL, line BLOB NOT NULL,"
    " PRIMARY KEY(conversation, seq));"
    /* A project held in this file: its repository is libfossil's tables
     * PREFIX* (fsl_repo_open_host). remote never carries userinfo (the
     * CHECK refuses an @ before the path), and the password is never kept:
     * cred names where it comes from (keychain or environment). */
    "CREATE TABLE IF NOT EXISTS picu_project(name TEXT PRIMARY KEY, prefix TEXT NOT NULL UNIQUE,"
    " remote TEXT NOT NULL CHECK(instr(substr(substr(remote, instr(remote, '://') + 3), 1,"
    "   instr(substr(remote, instr(remote, '://') + 3) || '/', '/') - 1), '@') = 0),"
    " cred TEXT, kind TEXT NOT NULL CHECK(kind IN ('fossil', 'zit')),"
    " state TEXT NOT NULL CHECK(state IN ('cloning', 'ready')), created_ms INTEGER NOT NULL);"
    /* A process pic started (procs.c): kind, the command (truncated), the
     * conversation and workspace that started it, pid and process group, the
     * OS's start token for pid (so a reused pid is not mistaken for it), the
     * pic process that recorded it (owner_pid), and, once it ends, when and
     * how (exit_code, signal; NULL when not known). ended_ms NULL: running. */
    "CREATE TABLE IF NOT EXISTS picu_proc(id INTEGER PRIMARY KEY, kind TEXT NOT NULL, command TEXT NOT NULL,"
    " workspace TEXT, conversation TEXT, pid INTEGER NOT NULL, pgid INTEGER NOT NULL, start_token INTEGER NOT NULL,"
    " owner_pid INTEGER NOT NULL, started_ms INTEGER NOT NULL, ended_ms INTEGER, exit_code INTEGER, signal INTEGER);"
    /* The credential store (cred.c). picu_credential_key: the one master
     * key's parameters, never the key: where it comes from (source), how a
     * passphrase is stretched (kdf, iterations, salt), and a verifier (a
     * known text sealed under it) that tells a wrong passphrase from a right
     * one. picu_credential: a provider's key, sealed (nonce, ciphertext and
     * Poly1305 tag; the name is bound as AAD), so plaintext never reaches
     * this file, its WAL or a backup. */
    "CREATE TABLE IF NOT EXISTS picu_credential_key(id INTEGER PRIMARY KEY CHECK(id = 1), source TEXT NOT NULL,"
    " kdf TEXT NOT NULL, iterations INTEGER NOT NULL, salt BLOB NOT NULL, verifier BLOB NOT NULL,"
    " created_ms INTEGER NOT NULL);"
    CREDENTIAL_TABLE("picu_credential") ";"
    /* What pic last learnt of each credential from a real reply (cred.c):
     * keyed by its name (a row's, or env:VAR:HASH for a variable's value),
     * never holding key text. */
    "CREATE TABLE IF NOT EXISTS picu_credential_health(name TEXT PRIMARY KEY, state TEXT NOT NULL"
    " CHECK(state IN ('ok', 'invalid', 'credit', 'limited', 'transient', 'other')), reason TEXT, status INTEGER,"
    " until_ms INTEGER, checked_ms INTEGER NOT NULL, remaining REAL, unit TEXT, probed_ms INTEGER, answered_ms INTEGER,"
    " valid_ms INTEGER);"
    /* Remote control (docs/design/remote-protocol.md): pic's keys (static, vapid, mailbox; the
     * public half in the clear, the secret sealed under the credential store's key with the AAD
     * remote-key:NAME) and the paired phones (a JSON object sealed with the AAD remote-device:
     * and the id in hex, so a row that does not open is not a device). */
    "CREATE TABLE IF NOT EXISTS picu_remote_key(name TEXT PRIMARY KEY, public BLOB, sealed BLOB NOT NULL,"
    " created_ms INTEGER NOT NULL);"
    "CREATE TABLE IF NOT EXISTS picu_remote_device(id BLOB PRIMARY KEY, sealed BLOB NOT NULL, paired_ms INTEGER NOT NULL,"
    " seen_ms INTEGER);"
    /* Saved model endpoints (endpoints.c): a model server's URL and the model list
     * its GET /models last gave (a JSON array of {id, owned_by}), when (fetched_ms, NULL: never)
     * and why the last fetch failed (error, NULL when it worked). Its key is picu_credential's
     * row under the same name. */
    "CREATE TABLE IF NOT EXISTS picu_endpoint(name TEXT PRIMARY KEY, url TEXT NOT NULL, models TEXT NOT NULL,"
    " added_ms INTEGER NOT NULL, fetched_ms INTEGER, error TEXT);"
    /* MCP servers (mcp.c): how to reach one (url, or command as a JSON argv and cwd), the names of
     * its headers and environment variables, their values sealed whole under the credential
     * store's key (sealed, the AAD mcp-server:NAME, bound to the server's origin inside), and the
     * tool list its last tools/list gave (tools, a JSON array), the MCP revision it spoke (era),
     * when (listed_ms) and why the last listing failed (error, NULL when it worked). */
    "CREATE TABLE IF NOT EXISTS picu_mcp_server(name TEXT PRIMARY KEY, transport TEXT NOT NULL"
    " CHECK(transport IN ('http', 'stdio')), url TEXT, command TEXT, cwd TEXT, header_names TEXT NOT NULL DEFAULT '[]',"
    " env_names TEXT NOT NULL DEFAULT '[]', sealed BLOB, description TEXT, exposure TEXT,"
    " timeout INTEGER NOT NULL DEFAULT 60, enabled INTEGER NOT NULL DEFAULT 1, era TEXT, tools TEXT NOT NULL DEFAULT '[]',"
    " added_ms INTEGER NOT NULL, listed_ms INTEGER, error TEXT);"
    "INSERT OR IGNORE INTO picu_meta(key, value) VALUES('schema_version', '" USERDB_VERSION "');";

static int home_path(const char *name, char *out, size_t cap) {
    const char *home = getenv("HOME");
    return home && *home && snprintf(out, cap, "%s/.pic/%s", home, name) < (int)cap ? 0 : -1;
}

/* A whole small file (malloc'd), or NULL. */
static char *udb_slurp(const char *path) {
    FILE *f = fopen(path, "rb");
    char *buf = NULL;
    long n;
    if (!f) {
        return NULL;
    }
    if (fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) >= 0 && n < (64L << 20) && fseek(f, 0, SEEK_SET) == 0 &&
        (buf = malloc((size_t)n + 1))) {
        if (fread(buf, 1, (size_t)n, f) == (size_t)n) {
            buf[n] = '\0';
        } else {
            free(buf);
            buf = NULL;
        }
    }
    fclose(f);
    return buf;
}

static long long udb_now_ms(void) {
    return (long long)(pic_platform_get()->wall_ns() / 1000000);
}

static int udb_run(sqlite3 *db, const char *sql, const char *text) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    if (text) {
        sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, sqlite3_bind_parameter_count(q), udb_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE || rc == SQLITE_ROW ? 0 : -1;
}

static int valid_json(sqlite3 *db, const char *text) {
    sqlite3_stmt *q = NULL;
    int valid = 0;
    if (sqlite3_prepare_v2(db, "SELECT json_valid(?1)", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
        valid = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
        sqlite3_finalize(q);
    }
    return valid;
}

/* A picu_credential made before 'oauth' was a kind, rebuilt with the new
 * CHECK in one transaction (a CHECK cannot be altered in place). Checked
 * again inside the transaction, so two openers rebuild it once. */
static int credential_old(sqlite3 *db) {
    sqlite3_stmt *q = NULL;
    int old = -1;
    if (sqlite3_prepare_v2(db, "SELECT instr(sql, '''oauth''') = 0 FROM sqlite_master WHERE name = 'picu_credential'", -1,
                           &q, NULL) == SQLITE_OK) {
        old = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return old;
}

static int credential_kinds(sqlite3 *db) {
    int old = credential_old(db);
    if (old <= 0) {
        return old;
    }
    if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        return -1;
    }
    old = credential_old(db);
    if (old < 0 || (old && sqlite3_exec(db,
                                        CREDENTIAL_TABLE("picu_credential_new") ";"
                                        "INSERT INTO picu_credential_new SELECT name, kind, sealed, created_ms, used_ms"
                                        " FROM picu_credential;"
                                        "DROP TABLE picu_credential;"
                                        "ALTER TABLE picu_credential_new RENAME TO picu_credential;",
                                        NULL, NULL, NULL) != SQLITE_OK)) {
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        return -1;
    }
    return sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) == SQLITE_OK ? 0 : -1;
}

/* A picu_credential_health made before free checks has no unit (what
 * remaining is counted in) or probed_ms (when a check last ran); one made
 * before the swap prompt ordered keys, no answered_ms (a request's reply
 * came back) or valid_ms (a check said valid). */
static int health_columns(sqlite3 *db) {
    static const char *const cols[][2] = {
        {"unit", "TEXT"}, {"probed_ms", "INTEGER"}, {"answered_ms", "INTEGER"}, {"valid_ms", "INTEGER"}};
    for (size_t i = 0; i < sizeof cols / sizeof cols[0]; i++) {
        sqlite3_stmt *q = NULL;
        int have = 0;
        if (sqlite3_prepare_v2(db, "SELECT 1 FROM pragma_table_info('picu_credential_health') WHERE name = ?1", -1, &q,
                               NULL) != SQLITE_OK) {
            return -1;
        }
        sqlite3_bind_text(q, 1, cols[i][0], -1, SQLITE_STATIC);
        have = sqlite3_step(q) == SQLITE_ROW;
        sqlite3_finalize(q);
        if (!have) {
            char sql[128];
            (void)snprintf(sql, sizeof sql, "ALTER TABLE picu_credential_health ADD COLUMN %s %s", cols[i][0], cols[i][1]);
            /* two openers may both get here: the loser's "duplicate column" is no failure */
            if (sqlite3_exec(db, sql, NULL, NULL, NULL) != SQLITE_OK && sqlite3_errcode(db) != SQLITE_ERROR) {
                return -1;
            }
        }
    }
    return 0;
}

/* The legacy JSON files, imported in one transaction, then deleted. A file
 * that is not valid JSON is left in place. */
static int migrate(sqlite3 *db) {
    char spath[PATH_MAX], mpath[PATH_MAX];
    char *settings = home_path("settings.json", spath, sizeof spath) == 0 ? udb_slurp(spath) : NULL;
    char *store = home_path("models-store.json", mpath, sizeof mpath) == 0 ? udb_slurp(mpath) : NULL;
    int rc = 0;
    if (!settings && !store) {
        return 0;
    }
    if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        free(settings);
        free(store);
        return -1;
    }
    if (settings) {
        rc |= udb_run(db,
                  "INSERT OR IGNORE INTO picu_setting(key, value, updated_ms)"
                  " SELECT key, CAST(value AS TEXT), ?2 FROM json_each(?1) WHERE json_valid(?1) AND value IS NOT NULL",
                  settings);
    }
    if (store) {
        rc |= udb_run(db,
                  "INSERT OR IGNORE INTO picu_catalog(provider, sz, models, checked_ms, last_modified_ms, etag)"
                  " SELECT key, length(CAST(json_extract(value, '$.models') AS BLOB)),"
                  "   sqlar_compress(CAST(json_extract(value, '$.models') AS BLOB)),"
                  "   coalesce(json_extract(value, '$.checkedAt'), 0), coalesce(json_extract(value, '$.lastModified'), 0),"
                  "   json_extract(value, '$.etag')"
                  " FROM json_each(?1) WHERE json_valid(?1) AND json_type(value, '$.models') = 'array' AND ?2 IS NOT NULL",
                  store);
    }
    if (rc != 0 || sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) != SQLITE_OK) {
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        free(settings);
        free(store);
        return -1;
    }
    /* Committed: the files are no longer the record. Invalid JSON stays put. */
    if (settings && valid_json(db, settings)) {
        (void)unlink(spath);
    }
    if (store && valid_json(db, store)) {
        (void)unlink(mpath);
    }
    free(settings);
    free(store);
    return 0;
}

int pic_userdb_path(char *out, size_t cap) { return home_path("pic.sqlite", out, cap); }

/* SQLite's own busy handler backs off up to 100 ms per sleep, so a waiter
 * that started late can win the lock first. This one polls every 1-2 ms
 * (fixed plus jitter, so waiters do not move in step) until a 5 s deadline
 * from the first refusal. */
typedef struct {
    uint64_t start_ns;
    uint64_t rng;
    uint64_t limit_ms;
} busy_state;

static int fair_busy(void *ctx, int count) {
    busy_state *b = ctx;
    uint64_t now = pic_platform_get()->mono_ns();
    sqlite3_vfs *vfs = sqlite3_vfs_find(pic_platform_get()->vfs);
    if (count == 0) {
        b->start_ns = now;
    }
    if (now - b->start_ns >= b->limit_ms * 1000000ull || !vfs) {
        return 0;
    }
    b->rng ^= b->rng << 13; /* xorshift64 */
    b->rng ^= b->rng >> 7;
    b->rng ^= b->rng << 17;
    (void)vfs->xSleep(vfs, 1000 + (int)(b->rng % 1000));
    return 1;
}

int pic_busy_wait(sqlite3 *db, long ms) {
    busy_state *b = sqlite3_malloc(sizeof *b);
    if (!b) {
        return -1;
    }
    b->start_ns = 0;
    b->limit_ms = (uint64_t)ms;
    if (pic_platform_get()->entropy(&b->rng, sizeof b->rng) != 0 || b->rng == 0) {
        b->rng = pic_platform_get()->mono_ns() | 1;
    }
    /* The handler replaces sqlite3_busy_timeout (one or the other); the
     * client data frees its state with the connection. */
    if (sqlite3_set_clientdata(db, "pic_busy", b, sqlite3_free) != SQLITE_OK) {
        sqlite3_free(b);
        return -1;
    }
    return sqlite3_busy_handler(db, fair_busy, b) == SQLITE_OK ? 0 : -1;
}

int pic_userdb_settings(sqlite3 *db) {
    if (pic_busy_wait(db, PIC_USERDB_BUSY_MS) != 0) {
        return -1;
    }
    return sqlite3_exec(db,
                        "PRAGMA synchronous=FULL; PRAGMA foreign_keys=OFF;"
#ifdef __APPLE__
                        " PRAGMA fullfsync=ON;"
#endif
                        ,
                        NULL, NULL, NULL) == SQLITE_OK
               ? 0
               : -1;
}

sqlite3 *pic_userdb(char *err, size_t errcap) {
    char path[PATH_MAX], dir[PATH_MAX];
    const char *home = getenv("HOME");
    sqlite3 *db = NULL;
    if (conn && conn_pid == getpid()) {
        return conn;
    }
    /* A connection inherited across fork is not this process's to use or
     * close (its locks and WAL state belong to the parent): left alone. */
    conn = NULL;
    if (!home || !*home || snprintf(dir, sizeof dir, "%s/.pic", home) >= (int)sizeof dir ||
        home_path("pic.sqlite", path, sizeof path) != 0) {
        if (err) {
            (void)snprintf(err, errcap, "no home directory for ~/.pic/pic.sqlite");
        }
        return NULL;
    }
    if (mkdir(dir, 0700) != 0 && errno != EEXIST) {
        if (err) {
            (void)snprintf(err, errcap, "cannot create %s: %s", dir, strerror(errno));
        }
        return NULL;
    }
    if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, pic_platform_get()->vfs) != SQLITE_OK ||
        pic_userdb_settings(db) != 0 || sqlite3_exec(db, "PRAGMA journal_mode=WAL", NULL, NULL, NULL) != SQLITE_OK ||
        pic_sqlar_register(db) != 0 || sqlite3_exec(db, schema, NULL, NULL, NULL) != SQLITE_OK || credential_kinds(db) != 0 || health_columns(db) != 0 || migrate(db) != 0) {
        if (err) {
            (void)snprintf(err, errcap, "%s: %s", path, db ? sqlite3_errmsg(db) : "cannot open");
        }
        sqlite3_close(db);
        return NULL;
    }
    (void)chmod(path, 0600);
    conn = db;
    conn_pid = getpid();
    return conn;
}

void pic_userdb_close(void) {
    if (conn && conn_pid == getpid()) {
        sqlite3_close(conn);
    }
    conn = NULL;
}

char *pic_setting(const char *key) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (db && sqlite3_prepare_v2(db, "SELECT value FROM picu_setting WHERE key = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

int pic_offline(void) {
    char *v = pic_setting("offline");
    int on = v && strcmp(v, "true") == 0;
    free(v);
    return on;
}

int pic_model_remember(const char *model) {
    return pic_setting_set("defaultModel", model) == 0 && pic_setting_set("lastModel", model) == 0 ? 0 : -1;
}

/* This process's own setting writes: PRAGMA data_version does not count them. */
static long long setting_writes;

long long pic_setting_writes(void) { return setting_writes; }

int pic_setting_set(const char *key, const char *value) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db,
                                 value ? "INSERT INTO picu_setting(key, value, updated_ms) VALUES(?1, ?2, ?3)"
                                         " ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_ms = excluded.updated_ms"
                                       : "DELETE FROM picu_setting WHERE key = ?1",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        if (value) {
            sqlite3_bind_text(q, 2, value, -1, SQLITE_STATIC);
            sqlite3_bind_int64(q, 3, udb_now_ms());
        }
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    setting_writes++;
    return rc;
}

int pic_setting_set_json(const char *key, const char *path, const char *json) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db,
                                 json ? "INSERT INTO picu_setting(key, value, updated_ms) VALUES(?1, json_set('{}', ?2, json(?3)), ?4)"
                                        " ON CONFLICT(key) DO UPDATE SET value = json_set(CASE WHEN json_valid(value)"
                                        " AND json_type(value) = 'object' THEN value ELSE '{}' END, ?2, json(?3)),"
                                        " updated_ms = excluded.updated_ms"
                                      : "UPDATE picu_setting SET value = json_remove(value, ?2), updated_ms = ?4"
                                        " WHERE key = ?1 AND json_valid(value) AND json_type(value) = 'object'",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (json) {
            sqlite3_bind_text(q, 3, json, -1, SQLITE_STATIC);
        }
        sqlite3_bind_int64(q, 4, udb_now_ms());
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    setting_writes++;
    return rc;
}

int pic_settings_each(int (*fn)(void *ctx, const char *key, const char *value), void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT key, value FROM picu_setting ORDER BY key", -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW && !fn(ctx, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1))) {
    }
    sqlite3_finalize(q);
    return 0;
}

int pic_install_id(char out[37]) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    unsigned char b[16];
    char fresh[37];
    int rc = -1;
    if (!db || pic_platform_get()->entropy(b, sizeof b) != 0) {
        return -1;
    }
    b[6] = (unsigned char)((b[6] & 0x0f) | 0x40); /* version 4, RFC 9562 variant */
    b[8] = (unsigned char)((b[8] & 0x3f) | 0x80);
    (void)snprintf(fresh, sizeof fresh, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", b[0], b[1],
                   b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
    /* The first writer's id stands: a second process inserting at once keeps it. */
    if (sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO picu_meta(key, value) VALUES('install_id', ?1)", -1, &q, NULL) !=
            SQLITE_OK ||
        (sqlite3_bind_text(q, 1, fresh, -1, SQLITE_STATIC), sqlite3_step(q)) != SQLITE_DONE) {
        sqlite3_finalize(q);
        return -1;
    }
    sqlite3_finalize(q);
    if (sqlite3_prepare_v2(db, "SELECT value FROM picu_meta WHERE key = 'install_id' AND length(value) = 36", -1, &q,
                           NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        memcpy(out, sqlite3_column_text(q, 0), 37);
        rc = 0;
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_remote_phones(void) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int n = 0;
    if (db && sqlite3_prepare_v2(db, "SELECT count(*) FROM picu_remote_device", -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        n = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return n;
}

int pic_userdb_is(const char *path) {
    char own[PATH_MAX];
    struct stat a, b;
    if (!path || pic_userdb_path(own, sizeof own) != 0) {
        return 0;
    }
    if (stat(path, &a) == 0 && stat(own, &b) == 0) {
        return a.st_dev == b.st_dev && a.st_ino == b.st_ino;
    }
    return strcmp(path, own) == 0;
}

int pic_workspace_forget(const char *workspace) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_workspace WHERE path = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, workspace, -1, SQLITE_STATIC);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_workspace_touch(const char *workspace, const char *journal) {
    sqlite3 *db;
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (pic_userdb_is(journal)) {
        return -1;
    }
    db = pic_userdb(NULL, 0);
    if (db && sqlite3_prepare_v2(db,
                                 "INSERT INTO picu_workspace(path, journal, last_used_ms) VALUES(?1, ?2, ?3)"
                                 " ON CONFLICT(path) DO UPDATE SET journal = excluded.journal, last_used_ms = excluded.last_used_ms",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, workspace, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, journal, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 3, udb_now_ms());
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_scoped_set(const char *const *patterns, size_t n) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (!db || sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        return -1;
    }
    if (sqlite3_exec(db, "DELETE FROM picu_scoped_model", NULL, NULL, NULL) == SQLITE_OK &&
        sqlite3_prepare_v2(db, "INSERT INTO picu_scoped_model(position, pattern) VALUES(?1, ?2)", -1, &q, NULL) == SQLITE_OK) {
        rc = 0;
        for (size_t i = 0; i < n && rc == 0; i++) {
            sqlite3_bind_int64(q, 1, (sqlite3_int64)i);
            sqlite3_bind_text(q, 2, patterns[i], -1, SQLITE_STATIC);
            rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
            sqlite3_reset(q);
        }
    }
    sqlite3_finalize(q);
    if (rc != 0 || sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) != SQLITE_OK) {
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        return -1;
    }
    return 0;
}

int pic_scoped_each(int (*fn)(void *ctx, const char *pattern), void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT pattern FROM picu_scoped_model ORDER BY position", -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW && !fn(ctx, (const char *)sqlite3_column_text(q, 0))) {
    }
    sqlite3_finalize(q);
    return 0;
}

int pic_trust_get(const char *path) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int out = -1;
    if (db && sqlite3_prepare_v2(db, "SELECT trusted FROM picu_trust WHERE path = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = sqlite3_column_int(q, 0);
        }
    }
    sqlite3_finalize(q);
    return out;
}

int pic_trust_set(const char *path, int trusted) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db,
                                 "INSERT INTO picu_trust(path, trusted, decided_ms) VALUES(?1, ?2, ?3)"
                                 " ON CONFLICT(path) DO UPDATE SET trusted = excluded.trusted, decided_ms = excluded.decided_ms",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, path, -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 2, trusted ? 1 : 0);
        sqlite3_bind_int64(q, 3, udb_now_ms());
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    sqlite3_finalize(q);
    return rc;
}

long long pic_bug_add(const char *workspace, const char *conversation, const char *model, const char *description) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    long long id = -1;
    if (db && sqlite3_prepare_v2(db,
                                 "INSERT INTO picu_bug(created_ms, workspace, conversation, model, description)"
                                 " VALUES(?1, ?2, ?3, ?4, ?5)",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, udb_now_ms());
        sqlite3_bind_text(q, 2, workspace, -1, SQLITE_STATIC);
        if (conversation && *conversation) {
            sqlite3_bind_text(q, 3, conversation, -1, SQLITE_STATIC);
        }
        if (model && *model) {
            sqlite3_bind_text(q, 4, model, -1, SQLITE_STATIC);
        }
        sqlite3_bind_text(q, 5, description, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_DONE) {
            id = sqlite3_last_insert_rowid(db);
        }
    }
    sqlite3_finalize(q);
    return id;
}

int pic_bugs_each(int (*fn)(void *ctx, long long id, long long ms, const char *workspace, const char *description),
                  void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT id, created_ms, workspace, description FROM picu_bug ORDER BY id", -1, &q,
                                  NULL) != SQLITE_OK) {
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW &&
           !fn(ctx, sqlite3_column_int64(q, 0), sqlite3_column_int64(q, 1), (const char *)sqlite3_column_text(q, 2),
               (const char *)sqlite3_column_text(q, 3))) {
    }
    sqlite3_finalize(q);
    return 0;
}

int pic_projects_each(int (*fn)(void *ctx, const pic_project *p), void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db, "SELECT name, prefix, remote, cred, kind, state, created_ms FROM picu_project ORDER BY name",
                                  -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    for (;;) {
        pic_project p;
        int rc = sqlite3_step(q);
        if (rc != SQLITE_ROW) {
            sqlite3_finalize(q);
            return rc == SQLITE_DONE ? 0 : -1;
        }
        p.name = (const char *)sqlite3_column_text(q, 0);
        p.prefix = (const char *)sqlite3_column_text(q, 1);
        p.remote = (const char *)sqlite3_column_text(q, 2);
        p.cred = (const char *)sqlite3_column_text(q, 3);
        p.kind = (const char *)sqlite3_column_text(q, 4);
        p.state = (const char *)sqlite3_column_text(q, 5);
        p.created_ms = sqlite3_column_int64(q, 6);
        if (fn(ctx, &p)) {
            sqlite3_finalize(q);
            return 0;
        }
    }
}

/* ---- picu_proc: the processes pic started ---------------------------------- */

/* One short write that does not wait for the disk: these rows are a
 * convenience, and a full fsync per command start would cost more than the
 * command's bookkeeping is worth. The connection's setting is put back. */
static int proc_write(sqlite3 *db, sqlite3_stmt *q) {
    int rc;
    (void)sqlite3_exec(db, "PRAGMA synchronous=OFF", NULL, NULL, NULL);
    rc = sqlite3_step(q);
    (void)sqlite3_exec(db, "PRAGMA synchronous=FULL", NULL, NULL, NULL);
    return rc == SQLITE_DONE ? 0 : -1;
}

static void bind_opt(sqlite3_stmt *q, int i, const char *text) {
    if (text && *text) {
        sqlite3_bind_text(q, i, text, -1, SQLITE_STATIC);
    }
}

long long pic_proc_add(const pic_proc *p) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    long long id = -1;
    if (db && sqlite3_prepare_v2(db,
                                 "INSERT INTO picu_proc(kind, command, workspace, conversation, pid, pgid, start_token,"
                                 " owner_pid, started_ms) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, p->kind, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, p->command, -1, SQLITE_STATIC);
        bind_opt(q, 3, p->workspace);
        bind_opt(q, 4, p->conversation);
        sqlite3_bind_int64(q, 5, p->pid);
        sqlite3_bind_int64(q, 6, p->pgid);
        sqlite3_bind_int64(q, 7, p->start_token);
        sqlite3_bind_int64(q, 8, p->owner_pid);
        sqlite3_bind_int64(q, 9, p->started_ms ? p->started_ms : udb_now_ms());
        if (proc_write(db, q) == 0) {
            id = sqlite3_last_insert_rowid(db);
        }
    }
    sqlite3_finalize(q);
    return id;
}

int pic_proc_finish(long long id, int exit_code, int sig) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db,
                                 "UPDATE picu_proc SET ended_ms = ?2, exit_code = ?3, signal = ?4"
                                 " WHERE id = ?1 AND ended_ms IS NULL",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, udb_now_ms());
        if (exit_code >= 0) {
            sqlite3_bind_int(q, 3, exit_code);
        }
        if (sig > 0) {
            sqlite3_bind_int(q, 4, sig);
        }
        rc = proc_write(db, q);
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_procs_each(int all, int (*fn)(void *ctx, const pic_proc *p), void *ctx) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db || sqlite3_prepare_v2(db,
                                  "SELECT id, kind, command, workspace, conversation, pid, pgid, start_token, owner_pid,"
                                  " started_ms, ended_ms, exit_code, signal FROM picu_proc"
                                  " WHERE ?1 OR ended_ms IS NULL ORDER BY id",
                                  -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int(q, 1, all ? 1 : 0);
    for (;;) {
        pic_proc p;
        int rc = sqlite3_step(q);
        if (rc != SQLITE_ROW) {
            sqlite3_finalize(q);
            return rc == SQLITE_DONE ? 0 : -1;
        }
        p.id = sqlite3_column_int64(q, 0);
        p.kind = (const char *)sqlite3_column_text(q, 1);
        p.command = (const char *)sqlite3_column_text(q, 2);
        p.workspace = (const char *)sqlite3_column_text(q, 3);
        p.conversation = (const char *)sqlite3_column_text(q, 4);
        p.pid = sqlite3_column_int64(q, 5);
        p.pgid = sqlite3_column_int64(q, 6);
        p.start_token = sqlite3_column_int64(q, 7);
        p.owner_pid = sqlite3_column_int64(q, 8);
        p.started_ms = sqlite3_column_int64(q, 9);
        p.ended_ms = sqlite3_column_int64(q, 10);
        p.exit_code = sqlite3_column_type(q, 11) == SQLITE_NULL ? -1 : sqlite3_column_int(q, 11);
        p.signal = sqlite3_column_int(q, 12);
        if (fn(ctx, &p)) {
            sqlite3_finalize(q);
            return 0;
        }
    }
}

int pic_procs_prune(long long before_ms) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_proc WHERE coalesce(ended_ms, started_ms) < ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, before_ms);
        rc = proc_write(db, q);
    }
    sqlite3_finalize(q);
    return rc;
}