Skip to content
pi-c Artifact [832b08bc64]
Login

Artifact [832b08bc64]

Artifact 832b08bc649303c2b97ae753521a53457eba2af510458d07c54924d737c0295c:


/* Wakes: see wake.h and docs/design/wakes.md. Core: the record, the fire and the due check. No
 * timer: a caller asks what is due, and the clock is the platform's wall clock. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "inbox.h"
#include "platform.h"
#include "wake.h"

/* SQL: wake W.id has a fire not yet taken up: its inbox row pending, or delivered as a follow-up
 * still queued behind a running request. */
#define WAKE_WAITING_SQL(W)                                                                                            \
    "EXISTS (SELECT 1 FROM pic_inbox w_p WHERE w_p.sender = 'wake:' || " W ".id AND (w_p.state = 'pending'"            \
    " OR (w_p.state = 'delivered' AND w_p.queued_id IN (SELECT w_q.id FROM pic_queued w_q WHERE w_q.state = 'queued'))))"

long long pic_wake_now_ms(void) {
#ifdef PIC_FAULTS
    const char *at = getenv("PIC_WAKE_NOW_MS"); /* tests: the wall clock at a chosen time */
    if (at && *at) {
        return strtoll(at, NULL, 10);
    }
#endif
    return (long long)(pic_platform_get()->wall_ns() / 1000000);
}

static int wake_fail(pic_store *s, int rc, const char *msg) {
    (void)snprintf(s->err, sizeof s->err, "%s", msg);
    return rc;
}

static int wake_sql_fail(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    return -1;
}

/* SQL's first column as an integer, ?1 the integer A and ?2 the text B (NULL: unbound). 0 or -1. */
static int wake_int(pic_store *s, const char *sql, long long a, const char *b, long long *out) {
    sqlite3_stmt *q = NULL;
    int rc;
    *out = 0;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, a);
    if (b) {
        sqlite3_bind_text(q, 2, b, -1, SQLITE_STATIC);
    }
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        *out = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

/* SQL with ?1 the integer A and ?2 the text B (NULL: unbound), run once. 0 or -1. */
static int wake_exec1(pic_store *s, const char *sql, long long a, const char *b) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, a);
    if (b) {
        sqlite3_bind_text(q, 2, b, -1, SQLITE_TRANSIENT);
    }
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

/* Wake ID's state STATE, with WHY, changed at NOW. 0 or -1. */
static int wake_state(pic_store *s, long long id, const char *state, const char *why, long long now) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4 WHERE id = ?1", -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, why, -1, SQLITE_TRANSIENT);
    sqlite3_bind_int64(q, 4, now);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

static const pic_wake_monitor_ops *wake_mon;

void pic_wake_monitors(const pic_wake_monitor_ops *ops) { wake_mon = ops; }

/* Monitor ID's spool, beside the journal's leases: <journal>.pic-monitors/ID.log ("" when the
 * path is too long). */
static void wake_spool(pic_store *s, long long id, char *out, size_t cap) {
    size_t n = s->lock_path ? strlen(s->lock_path) : 0, suffix = strlen(".pic-lock");
    out[0] = '\0';
    if (n > suffix && n - suffix + 48 < cap) {
        (void)snprintf(out, cap, "%.*s.pic-monitors/%lld.log", (int)(n - suffix), s->lock_path, id);
    }
}

/* Monitor ID's command started, in WORKSPACE, and its process recorded in a transaction of its
 * own. A crash between the two leaves the row with no pid: the next look adopts the process
 * SPOOL.pid names, or ends the monitor as "did not start". 0, or -1. */
static int wake_monitor_start(pic_store *s, long long id, const char *command, const char *workspace) {
    char spool[4200], tok[32];
    long pid = 0;
    long long token = 0;
    wake_spool(s, id, spool, sizeof spool);
    if (wake_mon->start(command, workspace, spool, &pid, &token) != 0) {
        return wake_state(s, id, "ended", "its command did not start", pic_wake_now_ms());
    }
    pic_fault("monitor_started");
    (void)snprintf(tok, sizeof tok, "%ld %lld", pid, token);
    return wake_exec1(s,
                      "UPDATE pic_wake SET pid = CAST(substr(?2, 1, instr(?2, ' ') - 1) AS INTEGER),"
                      " pid_started_ms = CAST(substr(?2, instr(?2, ' ') + 1) AS INTEGER) WHERE id = ?1 AND pid IS NULL",
                      id, tok);
}

/* ---- intervals -------------------------------------------------------------------------------- */

int pic_wake_parse_every(const char *text, long long *ms) {
    long long total = 0;
    const char *p = text;
    if (!text || !*text) {
        return 1;
    }
    while (*p) {
        long long n = 0, unit;
        int digits = 0;
        while (*p >= '0' && *p <= '9' && n < 100000000LL) {
            n = n * 10 + (*p++ - '0');
            digits++;
        }
        if (!digits) {
            return 1;
        }
        switch (*p) {
        case 's':
            unit = 1000;
            break;
        case 'm':
            unit = 60000;
            break;
        case 'h':
            unit = 3600000;
            break;
        case 'd':
            unit = 86400000;
            break;
        case '\0':
            if (p == text + digits && total == 0) { /* a number alone is minutes */
                *ms = n * 60000;
                return 0;
            }
            return 1;
        default:
            return 1;
        }
        p++;
        total += n * unit;
    }
    *ms = total;
    return 0;
}

void pic_wake_every_text(long long ms, char *out, size_t cap) {
    if (ms > 0 && ms % 86400000LL == 0) {
        (void)snprintf(out, cap, "%lldd", ms / 86400000LL);
    } else if (ms > 0 && ms % 3600000LL == 0) {
        (void)snprintf(out, cap, "%lldh", ms / 3600000LL);
    } else if (ms > 0 && ms % 60000LL == 0) {
        (void)snprintf(out, cap, "%lldm", ms / 60000LL);
    } else {
        (void)snprintf(out, cap, "%llds", ms / 1000);
    }
}

/* ---- the record ------------------------------------------------------------------------------- */

int pic_wake_create(pic_store *s, const pic_wake_new *w, long long *id, char *session_out, size_t cap) {
    sqlite3_stmt *q = NULL;
    long long every = w->every_ms ? w->every_ms : PIC_WAKE_SELF_PACED_MS, now = pic_wake_now_ms(), live = 0;
    char sid[64] = "";
    int rc;
    int monitor = w->kind && strcmp(w->kind, "monitor") == 0, goal = w->kind && strcmp(w->kind, "goal") == 0;
    *id = 0;
    if (!w->kind || (strcmp(w->kind, "loop") != 0 && !monitor && !goal)) {
        return wake_fail(s, 1, "a loop, a monitor or a goal");
    }
    if (goal && (!w->prompt || !*w->prompt)) {
        return wake_fail(s, 1, "a goal needs what is to be true when it is met");
    }
    if (goal && w->rounds < 0) {
        return wake_fail(s, 1, "a goal's rounds are at least 1");
    }
    if (monitor && (!w->command || !*w->command)) {
        return wake_fail(s, 1, "a monitor needs a command");
    }
    if (monitor && !wake_mon) {
        return wake_fail(s, 1, "this pic cannot run a monitor's command");
    }
    if (!monitor && (!w->prompt || !*w->prompt)) {
        return wake_fail(s, 1, "a loop needs a prompt");
    }
    if (monitor || goal) {
        every = PIC_WAKE_MIN_EVERY_MS; /* not on the clock; checked only below */
    }
    if (every < PIC_WAKE_MIN_EVERY_MS) {
        return wake_fail(s, 1, "the shortest interval is 1m");
    }
    if (every > PIC_WAKE_EXPIRY_MS) {
        return wake_fail(s, 1, "the longest interval is 7d, when a loop ends");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (!w->session || !*w->session) { /* a new, empty conversation for it */
        if (sqlite3_prepare_v2(s->db,
                               "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4))), ?1, ?1)"
                               " RETURNING id",
                               -1, &q, NULL) != SQLITE_OK) {
            rc = wake_sql_fail(s);
            pic_rollback(s);
            return rc;
        }
        sqlite3_bind_int64(q, 1, now);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
        }
        sqlite3_finalize(q);
        q = NULL;
    } else if (pic_session_resolve(s, w->session, sid, sizeof sid) != 0) {
        pic_rollback(s);
        return 1;
    }
    if (!sid[0]) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (wake_int(s, "SELECT count(*) FROM pic_wake WHERE session_id = ?2 AND state != 'ended' AND ?1 = ?1", 0, sid, &live) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (goal) {
        long long goals = 0;
        if (wake_int(s, "SELECT count(*) FROM pic_wake WHERE session_id = ?2 AND kind = 'goal' AND state != 'ended' AND ?1 = ?1", 0, sid,
                     &goals) != 0) {
            pic_rollback(s);
            return -1;
        }
        if (goals) {
            pic_rollback(s);
            return wake_fail(s, 1, "this conversation has a goal already: /goal clear ends it");
        }
    }
    if (live >= PIC_WAKE_MAX) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err,
                       "this conversation has %d loops, monitors and goals already: stop one first (/loop lists them)",
                       PIC_WAKE_MAX);
        return 1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_wake(session_id, kind, prompt, every_ms, state, creator, due_ms, created_ms,"
                           " expires_ms, updated_ms, options, command, max_rounds, max_stalls) VALUES (?1, ?2, ?3,"
                           " iif(?2 = 'loop', ?4, NULL), iif(?16, 'needs', 'active'), ?5, iif(?10, NULL, ?6), ?6, ?7, ?6, nullif(json_patch('{}',"
                           " json_object('model', ?8, 'done', iif(?11, json('true'), NULL), 'restart', iif(?12, json('true'), NULL),"
                           " 'selfPaced', iif(?15, json('true'), NULL), 'approval', iif(?16, 'asked', NULL))),"
                           " '{}'), ?9, iif(?2 = 'goal', ?13, NULL), iif(?2 = 'goal', ?14, NULL))",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, w->kind, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, w->prompt ? w->prompt : "", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, every);
    sqlite3_bind_text(q, 5, w->creator ? w->creator : "user", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 6, now);
    sqlite3_bind_int64(q, 7, now + PIC_WAKE_EXPIRY_MS);
    if (w->model && *w->model) {
        sqlite3_bind_text(q, 8, w->model, -1, SQLITE_STATIC);
    }
    if (monitor) {
        sqlite3_bind_text(q, 9, w->command, -1, SQLITE_STATIC);
    } else if (goal && w->check && *w->check) {
        sqlite3_bind_text(q, 9, w->check, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 13, w->rounds > 0 ? w->rounds : PIC_WAKE_GOAL_ROUNDS);
    sqlite3_bind_int64(q, 14, PIC_WAKE_GOAL_STALLS);
    sqlite3_bind_int(q, 15, !monitor && !goal && !w->every_ms);
    sqlite3_bind_int(q, 16, w->ask && !monitor);
    sqlite3_bind_int(q, 10, monitor);
    sqlite3_bind_int(q, 11, w->done);
    sqlite3_bind_int(q, 12, w->restart);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    *id = sqlite3_last_insert_rowid(s->db);
    if (w->ask && !monitor && wake_exec1(s, "UPDATE pic_wake SET why = ?2 WHERE id = ?1", *id, "waiting for your OK") != 0) {
        pic_rollback(s);
        return -1;
    }
    if (monitor) { /* its spool, beside the journal */
        char spool[4200];
        wake_spool(s, *id, spool, sizeof spool);
        if (!spool[0] || wake_exec1(s, "UPDATE pic_wake SET spool = ?2 WHERE id = ?1", *id, spool) != 0) {
            pic_rollback(s);
            return spool[0] ? -1 : wake_fail(s, -1, "journal path too long");
        }
    }
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    (void)snprintf(session_out, cap, "%s", sid);
    return monitor ? wake_monitor_start(s, *id, w->command, w->workspace) : 0;
}

int pic_wake_resolve(pic_store *s, const char *name, long long *id) {
    const char *p = name;
    long long n = 0, found = 0;
    *id = 0;
    if (p && (*p == 'L' || *p == 'l' || *p == 'M' || *p == 'm' || *p == 'G' || *p == 'g')) {
        p++;
    }
    if (!p || !*p) {
        (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name ? name : "");
        return 1;
    }
    for (; *p; p++) {
        if (*p < '0' || *p > '9' || n > 1000000000LL) {
            (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name);
            return 1;
        }
        n = n * 10 + (*p - '0');
    }
    if (wake_int(s, "SELECT count(*) FROM pic_wake WHERE id = ?1", n, NULL, &found) != 0) {
        return -1;
    }
    if (!found) {
        (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name);
        return 1;
    }
    *id = n;
    return 0;
}

int pic_wake_set(pic_store *s, long long id, const char *action, const char *why) {
    sqlite3_stmt *q = NULL;
    char state[16] = "";
    long long now = pic_wake_now_ms(), expires = 0, token = 0;
    long pid = 0;
    const char *to, *sql;
    int rc, asked = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT state, expires_ms, coalesce(pid, 0), coalesce(pid_started_ms, 0), state = 'needs' AND"
                           " coalesce(json_extract(options, '$.approval'), '') = 'asked' FROM pic_wake WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(state, sizeof state, "%s", (const char *)sqlite3_column_text(q, 0));
        expires = sqlite3_column_int64(q, 1);
        pid = (long)sqlite3_column_int64(q, 2);
        token = sqlite3_column_int64(q, 3);
        asked = sqlite3_column_int(q, 4);
    }
    sqlite3_finalize(q);
    if (state[0] && strcmp(state, "ended") == 0 && strcmp(action, "stop") == 0) { /* stopped already: the same answer */
        pic_rollback(s);
        return 0;
    }
    if (!state[0] || strcmp(state, "ended") == 0) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err, state[0] ? "it has ended" : "no such loop, monitor or goal");
        return 1;
    }
    if (strcmp(action, "pause") == 0) {
        to = "paused";
        why = why ? why : "paused";
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4 WHERE id = ?1";
    } else if (strcmp(action, "resume") == 0) {
        if (asked) {
            pic_rollback(s);
            return wake_fail(s, 1, "it waits for your OK: approve or decline it");
        }
        if (now >= expires) {
            pic_rollback(s);
            return wake_fail(s, 1, "it has expired: loops, monitors and goals end after 7 days");
        }
        to = "active";
        why = NULL;
        /* a loop keeps its due time; a goal runs its next round now unless one waits or runs; a goal
         * that reached its rounds gets 10 more, and its stalls start again */
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4, due_ms = CASE kind WHEN 'loop' THEN coalesce(due_ms, ?4)"
              " WHEN 'goal' THEN CASE WHEN " WAKE_WAITING_SQL("pic_wake") " OR EXISTS (SELECT 1 FROM pic_submission u WHERE"
              " u.session_id = pic_wake.session_id AND u.status = 'admitted' AND " PIC_WAKE_OF_SQL("u") " = pic_wake.id)"
              " THEN NULL ELSE ?4 END ELSE due_ms END, stalls = iif(kind = 'goal', 0, stalls),"
              " max_rounds = iif(kind = 'goal' AND fires >= coalesce(max_rounds, 0), fires + 10, max_rounds) WHERE id = ?1";
    } else if (strcmp(action, "stop") == 0) {
        to = "ended";
        why = why ? why : "stopped";
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4 WHERE id = ?1";
    } else {
        pic_rollback(s);
        return wake_fail(s, 1, "pause, resume or stop");
    }
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, to, -1, SQLITE_STATIC);
    if (why) {
        sqlite3_bind_text(q, 3, why, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 4, now);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (strcmp(to, "ended") == 0 && pid > 0 && wake_mon) { /* a monitor's command ends with it */
        wake_mon->stop(pid, token);
    }
    return 0;
}

int pic_wake_decide(pic_store *s, long long id, int approve) {
    sqlite3_stmt *q = NULL;
    char session[64] = "", kind[16] = "", *line = NULL, key[64], sender[64], got[64], st[16];
    long long now = pic_wake_now_ms(), every = 0;
    int asked = 0, done = 0, rc = -1;
    pic_inbox_msg m;
    if (pic_begin_outer(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT session_id, kind, coalesce(every_ms, 0), state = 'needs' AND coalesce(json_extract(options,"
                           " '$.approval'), '') = 'asked', coalesce(json_extract(options, '$.approval'), '') FROM pic_wake WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0));
        (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 1));
        every = sqlite3_column_int64(q, 2);
        asked = sqlite3_column_int(q, 3);
        done = strcmp((const char *)sqlite3_column_text(q, 4), approve ? "approved" : "declined") == 0;
    }
    sqlite3_finalize(q);
    q = NULL;
    if (done) { /* decided so already: the same answer */
        pic_rollback(s);
        return 0;
    }
    if (!asked) {
        rc = wake_fail(s, 1, "it is not waiting for an OK");
        goto out;
    }
    {
        char text[300], ev[24];
        pic_wake_every_text(every, ev, sizeof ev);
        if (approve) {
            (void)snprintf(text, sizeof text, "[The user approved %s %c%lld%s%s: it starts now.]", kind, kind[0] == 'g' ? 'G' : 'L', id,
                           kind[0] == 'l' ? ", every " : "", kind[0] == 'l' ? ev : "");
        } else {
            (void)snprintf(text, sizeof text, "[The user declined %s %c%lld: it was not started. Do not start it again unless they ask.]",
                           kind, kind[0] == 'g' ? 'G' : 'L', id);
        }
        if (sqlite3_prepare_v2(s->db, "SELECT json_object('type', 'steer', 'message', ?1)", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                line = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        q = NULL;
    }
    if (!line) {
        rc = wake_fail(s, -1, "out of memory");
        goto out;
    }
    (void)snprintf(key, sizeof key, "approval:%lld", id);
    (void)snprintf(sender, sizeof sender, "approval:%lld", id);
    memset(&m, 0, sizeof m);
    m.session = session;
    m.key = key;
    m.line = line;
    m.sender = sender;
    m.expires_s = PIC_INBOX_MAX_SECONDS; /* it joins the next request there, whenever that is */
    if ((rc = pic_inbox_accept(s, &m, got, sizeof got, st, sizeof st)) != 0) {
        rc = rc < 0 ? -1 : 1;
        goto out;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET state = iif(?2, 'active', 'ended'), why = iif(?2, NULL, 'declined'), updated_ms = ?3,"
                           " due_ms = iif(?2 AND kind IN ('loop', 'goal'), ?3, due_ms), options = json_set(options, '$.approval',"
                           " iif(?2, 'approved', 'declined')) WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int(q, 2, approve);
    sqlite3_bind_int64(q, 3, now);
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    q = NULL;
    if (rc != 0) {
        goto out;
    }
    pic_fault("wake_decide");
    if (pic_commit(s) != 0) {
        rc = -1;
        goto out;
    }
    pic_fault("wake_decide");
    pic_inbox_ring(s, session);
    free(line);
    return 0;
out:
    pic_rollback(s);
    free(line);
    return rc;
}

int pic_wake_pause_all(pic_store *s, const char *session, const char *why, int *count) {
    sqlite3_stmt *q = NULL;
    int rc;
    *count = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET state = 'paused', why = ?2, updated_ms = ?3 WHERE session_id = ?1 AND state = 'active'",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, why ? why : "paused with /stop", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, pic_wake_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    *count = sqlite3_changes(s->db);
    return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
}

int pic_wake_cancelled(pic_store *s, long long submission) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET state = 'paused', why = 'stopped during its run', updated_ms = ?2"
                           " WHERE state = 'active' AND id = (SELECT " PIC_WAKE_OF_SQL("u") " FROM pic_submission u WHERE u.id = ?1)",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, pic_wake_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

/* ---- the fire --------------------------------------------------------------------------------- */

/* A wake whose time has come at NOW (?1): a loop at or past its due time, or with its last fire
 * ahead of the clock (the clock stepped back), or any wake past its expiry. */
#define WAKE_DUE_SQL(W)                                                                                                \
    "(" W ".state = 'active' AND ((" W ".kind = 'loop' AND (" W ".due_ms <= ?1 OR " W ".fired_ms > ?1"                 \
    " OR " W ".expires_ms <= ?1)) OR (" W ".kind = 'goal' AND (" W ".due_ms <= ?1 OR " W ".expires_ms <= ?1))))"

static char *wake_message(pic_store *s, long long id, long long every, long long fires, long long ticks, int last,
                          const char *prompt) {
    sqlite3_stmt *q = NULL;
    char head[600], ev[32];
    char *out = NULL;
    long long paced = 0;
    size_t n;
    pic_wake_every_text(every, ev, sizeof ev);
    n = (size_t)snprintf(head, sizeof head, "[Loop L%lld, every %s, run %lld: sent by a loop the user set up, not typed just now.", id,
                         ev, fires);
    if (ticks > 1 && n < sizeof head) {
        n += (size_t)snprintf(head + n, sizeof head - n, " It stands for the %lld runs that came due while no pic was running.", ticks);
    }
    if (last && n < sizeof head) {
        n += (size_t)snprintf(head + n, sizeof head - n, " This is its last run: loops end 7 days after they start.");
    } else if (n < sizeof head && wake_int(s, "SELECT coalesce(json_extract(options, '$.selfPaced'), 0) FROM pic_wake WHERE id = ?1", id,
                                            NULL, &paced) == 0 && paced) {
        n += (size_t)snprintf(head + n, sizeof head - n,
                              " It paces itself: call the wake tool with action loop_next and seconds (60 to 3600) for when it runs"
                              " next; otherwise it runs again in %s.", ev);
    }
    if (n < sizeof head) {
        (void)snprintf(head + n, sizeof head - n, "]");
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('type', 'prompt', 'streamingBehavior', 'followUp', 'message',"
                           " ?2 || char(10) || char(10) || ?1)",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, head, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, prompt, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* A goal's round ROUND: the goal, then the harness's line saying what the round is for and how it
 * ends; after a check, what the check said (CHECK its command, EXIT its status, -1 unknown, OUTPUT
 * its last bytes). Pi's prompt command line, malloc'd. */
static char *wake_goal_round(pic_store *s, long long id, long long round, long long max_rounds, const char *goal,
                             const char *check, long long exit, const char *output) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_object('type', 'prompt', 'streamingBehavior', 'followUp', 'message', ?1 || char(10) || char(10) ||"
            " '[Goal G' || ?2 || ', round ' || ?3 || ' of ' || ?4 || ': keep working until this is true; the user set this goal,'"
            " || ' this was not typed just now.' || CASE WHEN ?5 IS NULL THEN ' When it is met, call the wake tool with action'"
            " || ' goal_done and say why; if it cannot be met, goal_blocked.' WHEN ?6 IS NULL THEN ' After each round pic runs `' ||"
            " ?5 || '`; the goal is met when it exits 0.' ELSE ' pic ran `' || ?5 || '` after the last round: ' || CASE WHEN ?6 < 0"
            " THEN 'it was interrupted, so its result is unknown.' ELSE 'it exited ' || ?6 || '.' END || ' The goal is met when it'"
            " || ' exits 0; if it cannot be, call the wake tool with action goal_blocked.' END || ']' || CASE WHEN length(?7)"
            " THEN char(10) || char(10) || 'Its output ended:' || char(10) || ?7 ELSE '' END)",
            -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, goal, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, id);
        sqlite3_bind_int64(q, 3, round);
        sqlite3_bind_int64(q, 4, max_rounds);
        if (check && *check) {
            sqlite3_bind_text(q, 5, check, -1, SQLITE_STATIC);
        }
        if (output || exit != -2) {
            sqlite3_bind_int64(q, 6, exit);
        }
        sqlite3_bind_text(q, 7, output ? output : "", -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* A goal's first round: no check has run yet. */
static char *wake_goal_message(pic_store *s, long long id, long long round, const char *goal) {
    long long max = 0;
    char *check = NULL, *out;
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT coalesce(max_rounds, 0), command FROM pic_wake WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, id);
        if (sqlite3_step(q) == SQLITE_ROW) {
            max = sqlite3_column_int64(q, 0);
            check = sqlite3_column_text(q, 1) ? strdup((const char *)sqlite3_column_text(q, 1)) : NULL;
        }
    }
    sqlite3_finalize(q);
    out = wake_goal_round(s, id, round, max, goal, check, -2, NULL);
    free(check);
    return out;
}

/* Wake ID fires at NOW when its time has come and no fire of it waits, in one transaction: its
 * count, due time and last fire advance, and its inbox row is inserted. 1 fired, 0 nothing to do,
 * -1 (rolled back; s->err). */
static int wake_fire(pic_store *s, long long id, long long now, char *session, size_t cap) {
    sqlite3_stmt *q = NULL;
    char kind[16] = "", *prompt = NULL, *line = NULL, key[96], sender[48], got[96], state[16];
    long long every = 0, fires = 0, due = 0, fired = 0, expires = 0, waiting = 0, ticks = 1, next;
    int ok = 0, rc = -1, last;
    pic_inbox_msg m;
    session[0] = '\0';
    if (pic_begin_outer(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT kind, session_id, prompt, coalesce(every_ms, 0), fires, coalesce(due_ms, ?1), coalesce(fired_ms, 0),"
                           " expires_ms, " WAKE_WAITING_SQL("w") " FROM pic_wake w WHERE w.id = ?2 AND " WAKE_DUE_SQL("w"),
                           -1, &q, NULL) != SQLITE_OK) {
        (void)wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, now);
    sqlite3_bind_int64(q, 2, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        ok = 1;
        (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 0));
        (void)snprintf(session, cap, "%s", (const char *)sqlite3_column_text(q, 1));
        prompt = strdup((const char *)sqlite3_column_text(q, 2));
        every = sqlite3_column_int64(q, 3);
        fires = sqlite3_column_int64(q, 4);
        due = sqlite3_column_int64(q, 5);
        fired = sqlite3_column_int64(q, 6);
        expires = sqlite3_column_int64(q, 7);
        waiting = sqlite3_column_int64(q, 8);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!ok) { /* another process fired it, or it was paused, since the look */
        rc = 0;
        goto out;
    }
    if (!prompt) {
        (void)wake_fail(s, -1, "out of memory");
        goto out;
    }
    last = now >= expires;
    if (waiting && !last) { /* a fire still waits to be taken up: this one is folded into the next */
        rc = 0;
        goto out;
    }
    if (waiting || (strcmp(kind, "loop") != 0 && (strcmp(kind, "goal") != 0 || last))) { /* expired: ended, no fire */
        if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET state = 'ended', why = 'expired', updated_ms = ?2 WHERE id = ?1", -1, &q,
                               NULL) != SQLITE_OK) {
            (void)wake_sql_fail(s);
            goto out;
        }
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, now);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
        sqlite3_finalize(q);
        q = NULL;
        if (rc == 0 && pic_commit(s) != 0) {
            rc = -1;
        }
        goto out;
    }
    if (strcmp(kind, "goal") == 0) { /* a goal's round: its next comes from the stop gate, not the clock */
        next = 0;
        line = wake_goal_message(s, id, fires + 1, prompt);
    } else {
        if (fired > now || due > now) { /* the clock stepped back past the last fire: fire once, anchored anew */
            next = now + every;
        } else {
            ticks = (now - due) / every + 1;
            next = due + ticks * every;
        }
        line = wake_message(s, id, every, fires + 1, ticks, last, prompt);
    }
    if (!line) {
        (void)wake_fail(s, -1, "out of memory");
        goto out;
    }
    (void)snprintf(key, sizeof key, "wake:%lld:%lld", id, fires + 1);
    (void)snprintf(sender, sizeof sender, "wake:%lld", id);
    memset(&m, 0, sizeof m);
    m.session = session;
    m.key = key;
    m.line = line;
    m.sender = sender;
    rc = pic_inbox_accept(s, &m, got, sizeof got, state, sizeof state);
    if (rc < 0) {
        goto out;
    }
    if (rc == 1) { /* the inbox refused it (full, the conversation gone): a person has to look */
        char why[PIC_ERR_CAP + 40];
        (void)snprintf(why, sizeof why, "its message was refused: %s", s->err);
        if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET state = 'needs', why = ?3, updated_ms = ?2 WHERE id = ?1", -1, &q, NULL) !=
            SQLITE_OK) {
            rc = wake_sql_fail(s);
            goto out;
        }
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, now);
        sqlite3_bind_text(q, 3, why, -1, SQLITE_TRANSIENT);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
        sqlite3_finalize(q);
        q = NULL;
        if (rc == 0 && pic_commit(s) != 0) {
            rc = -1;
        }
        goto out;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET fires = fires + 1, rounds = iif(kind = 'goal', fires + 1, rounds), fired_ms = ?2,"
                           " due_ms = nullif(?3, 0), updated_ms = ?2, state = iif(?4, 'ended', state), why = iif(?4, 'expired', why)"
                           " WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int64(q, 2, now);
    sqlite3_bind_int64(q, 3, next);
    sqlite3_bind_int(q, 4, last);
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    q = NULL;
    if (rc != 0) {
        goto out;
    }
    pic_fault("wake_fire");
    if (pic_commit(s) != 0) {
        rc = -1;
        goto out;
    }
    pic_fault("wake_fire");
    pic_inbox_ring(s, session); /* the worker looks only after the commit */
    rc = 1;
out:
    if (rc < 0 || (rc == 0 && s->nest)) {
        pic_rollback(s);
    }
    free(prompt);
    free(line);
    return rc;
}

/* ---- monitors ---------------------------------------------------------------------------------- */

/* Monitor ID at NOW: its command adopted when a crash left it unrecorded, started again when it
 * died with the computer and the person said that is safe (--restart), and its new output (whole
 * lines, at most PIC_WAKE_MONITOR_BYTES of the newest) fired with the read offset advanced in the
 * same transaction; a command that has exited, or a monitor past its 7 days, fires once more
 * and ends. 1 fired, 0 nothing to do, -1 (rolled back). */
static int wake_monitor(pic_store *s, long long id, long long now, const char *workspace) {
    sqlite3_stmt *q = NULL;
    char session[64] = "", *command = NULL, *spool = NULL, *bytes = NULL, *line = NULL, key[96], sender[48], got[96], st[16];
    long long offset = 0, token = 0, fires = 0, expires = 0, created = 0, size, end;
    long pid = 0;
    int done = 0, restart = 0, waiting = 0, alive, status, expired, final, rc = 0, ok = 0;
    size_t len = 0;
    pic_inbox_msg m;
    if (!wake_mon) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT session_id, command, spool, read_offset, coalesce(pid, 0), coalesce(pid_started_ms, 0), fires,"
                           " expires_ms, created_ms, coalesce(json_extract(options, '$.done'), 0), coalesce(json_extract(options,"
                           " '$.restart'), 0), " WAKE_WAITING_SQL("w") " FROM pic_wake w WHERE id = ?1 AND state = 'active'"
                           " AND kind = 'monitor' AND command IS NOT NULL AND spool IS NOT NULL",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        ok = 1;
        (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0));
        command = strdup((const char *)sqlite3_column_text(q, 1));
        spool = strdup((const char *)sqlite3_column_text(q, 2));
        offset = sqlite3_column_int64(q, 3);
        pid = (long)sqlite3_column_int64(q, 4);
        token = sqlite3_column_int64(q, 5);
        fires = sqlite3_column_int64(q, 6);
        expires = sqlite3_column_int64(q, 7);
        created = sqlite3_column_int64(q, 8);
        done = sqlite3_column_int(q, 9);
        restart = sqlite3_column_int(q, 10);
        waiting = sqlite3_column_int(q, 11);
    }
    sqlite3_finalize(q);
    if (!ok || !command || !spool) {
        goto out;
    }
    if (!pid) { /* started, not recorded: the process SPOOL.pid names is adopted, or it never started */
        long named = wake_mon->pidfile(spool);
        if (named > 0 && wake_mon->alive(named, 0)) {
            char tok[48];
            (void)snprintf(tok, sizeof tok, "%ld %lld", named, wake_mon->token(named));
            rc = wake_exec1(s,
                            "UPDATE pic_wake SET pid = CAST(substr(?2, 1, instr(?2, ' ') - 1) AS INTEGER),"
                            " pid_started_ms = CAST(substr(?2, instr(?2, ' ') + 1) AS INTEGER) WHERE id = ?1 AND pid IS NULL",
                            id, tok);
        } else if (now - created > 30000 && named <= 0) {
            char at[24];
            (void)snprintf(at, sizeof at, "%lld", now);
            rc = wake_exec1(s, "UPDATE pic_wake SET state = 'ended', why = 'its command did not start', updated_ms = CAST(?2 AS INTEGER)"
                               " WHERE id = ?1 AND pid IS NULL", id, at);
        } else if (named > 0) { /* it started and has gone already: the next look reads what it wrote, and ends it */
            char n[24];
            (void)snprintf(n, sizeof n, "%ld", named);
            rc = wake_exec1(s, "UPDATE pic_wake SET pid = CAST(?2 AS INTEGER) WHERE id = ?1 AND pid IS NULL", id, n);
        }
        goto out;
    }
    status = wake_mon->exit_status(spool);
    alive = status < 0 && wake_mon->alive(pid, token);
    expired = now >= expires;
    if (waiting && !expired) { /* the output that comes meanwhile goes with the next fire */
        goto out;
    }
    if (!alive && restart && status < 0 && !expired) { /* it died with the computer: the person said it may run again */
        long npid = 0;
        long long ntok = 0;
        if (wake_mon->start(command, workspace, spool, &npid, &ntok) == 0) {
            char tok[48];
            (void)snprintf(tok, sizeof tok, "%ld %lld", npid, ntok);
            rc = wake_exec1(s,
                            "UPDATE pic_wake SET pid = CAST(substr(?2, 1, instr(?2, ' ') - 1) AS INTEGER),"
                            " pid_started_ms = CAST(substr(?2, instr(?2, ' ') + 1) AS INTEGER) WHERE id = ?1",
                            id, tok);
            goto out;
        }
    }
    size = wake_mon->size(spool);
    size = size < offset ? offset : size;
    end = size;
    final = !alive || expired;
    if (!final) {
        const char *nl;
        if (done || size <= offset) {
            goto out;
        }
        if (!(bytes = wake_mon->read(spool, offset, size, &len))) {
            goto out;
        }
        for (nl = bytes + len; nl > bytes && nl[-1] != '\n'; nl--) {
        }
        if (nl == bytes) { /* a line still being written */
            goto out;
        }
        end = offset + (long long)(nl - bytes);
        len = (size_t)(nl - bytes);
    } else {
        long long from = done && size - offset > PIC_WAKE_MONITOR_BYTES ? size - PIC_WAKE_MONITOR_BYTES : offset;
        if (waiting) { /* expired with a fire waiting: ended, its command stopped, no more fires */
            if (alive) {
                wake_mon->stop(pid, token);
            }
            {
                char at[24];
                (void)snprintf(at, sizeof at, "%lld", now);
                rc = wake_exec1(s, "UPDATE pic_wake SET state = 'ended', why = 'expired', updated_ms = CAST(?2 AS INTEGER) WHERE id = ?1",
                                id, at);
            }
            goto out;
        }
        bytes = size > from ? wake_mon->read(spool, from, size, &len) : strdup("");
        if (!bytes) {
            goto out;
        }
    }
    if (expired && alive) {
        wake_mon->stop(pid, token);
    }
    {
        /* the newest PIC_WAKE_MONITOR_BYTES of it, from a line's start, with a count of the lines left out */
        const char *text = bytes;
        long long dropped = 0;
        char note[900], *shown;
        if (len > PIC_WAKE_MONITOR_BYTES) {
            const char *cut = bytes + len - PIC_WAKE_MONITOR_BYTES;
            while (cut < bytes + len && cut[-1] != '\n') {
                cut++;
            }
            for (const char *p = bytes; p < cut; p++) {
                dropped += *p == '\n';
            }
            text = cut;
        }
        shown = pic_one_line(command, 60);
        {
            size_t n = (size_t)snprintf(note, sizeof note, "[Monitor M%lld (`%s`): %s, sent by a monitor the user set up, not typed just now.",
                                        id, shown ? shown : "", done ? "its command has ended" : final ? "the last of its output" : "new output");
            if (dropped && n < sizeof note) {
                n += (size_t)snprintf(note + n, sizeof note - n, " %lld earlier lines were left out; all of it is in %s.", dropped, spool);
            }
            if (final && n < sizeof note) {
                if (expired) {
                    n += (size_t)snprintf(note + n, sizeof note - n, " The monitor has ended: 7 days are up.");
                } else if (status >= 0) {
                    n += (size_t)snprintf(note + n, sizeof note - n, " Its command exited with status %d; the monitor has ended.", status);
                } else {
                    n += (size_t)snprintf(note + n, sizeof note - n, " Its command is no longer running; the monitor has ended.");
                }
            }
            if (n < sizeof note) {
                (void)snprintf(note + n, sizeof note - n, "]");
            }
        }
        free(shown);
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_object('type', 'prompt', 'streamingBehavior', 'followUp', 'message',"
                               " CASE WHEN length(?1) THEN ?1 || iif(substr(?1, -1) = char(10), '', char(10)) || char(10) ELSE '' END"
                               " || ?2)",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 2, note, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                line = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        q = NULL;
    }
    if (!line) {
        rc = wake_fail(s, -1, "out of memory");
        goto out;
    }
    /* the fire: the offset it read from must still be the row's, and no fire may have come since */
    if (pic_begin_outer(s) != 0) {
        rc = -1;
        goto out;
    }
    {
        long long same = 0;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT count(*) FROM pic_wake w WHERE id = ?1 AND state = 'active' AND read_offset = ?2 AND fires = ?3"
                               " AND NOT " WAKE_WAITING_SQL("w"),
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, id);
            sqlite3_bind_int64(q, 2, offset);
            sqlite3_bind_int64(q, 3, fires);
            same = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        }
        sqlite3_finalize(q);
        q = NULL;
        if (!same) {
            pic_rollback(s);
            goto out;
        }
    }
    (void)snprintf(key, sizeof key, "wake:%lld:%lld", id, fires + 1);
    (void)snprintf(sender, sizeof sender, "wake:%lld", id);
    memset(&m, 0, sizeof m);
    m.session = session;
    m.key = key;
    m.line = line;
    m.sender = sender;
    rc = pic_inbox_accept(s, &m, got, sizeof got, st, sizeof st);
    if (rc != 0) {
        char why[PIC_ERR_CAP + 40];
        if (rc < 0) {
            pic_rollback(s);
            goto out;
        }
        (void)snprintf(why, sizeof why, "its message was refused: %s", s->err);
        rc = wake_state(s, id, "needs", why, now);
        if (rc != 0 || pic_commit(s) != 0) {
            pic_rollback(s);
            rc = -1;
        }
        goto out;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET fires = fires + 1, fired_ms = ?2, updated_ms = ?2, read_offset = ?3,"
                           " state = iif(?4, 'ended', state), why = iif(?4, CASE WHEN ?5 THEN 'expired' WHEN ?6 >= 0"
                           " THEN 'its command exited with status ' || ?6 ELSE 'its command is no longer running' END, why),"
                           " exit_code = iif(?6 >= 0, ?6, exit_code) WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int64(q, 2, now);
    sqlite3_bind_int64(q, 3, final ? size : end);
    sqlite3_bind_int(q, 4, final);
    sqlite3_bind_int(q, 5, expired);
    sqlite3_bind_int(q, 6, final ? status : -1);
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    q = NULL;
    if (rc != 0) {
        pic_rollback(s);
        goto out;
    }
    pic_fault("wake_fire");
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        rc = -1;
        goto out;
    }
    pic_fault("wake_fire");
    pic_inbox_ring(s, session);
    rc = 1;
out:
    free(command);
    free(spool);
    free(bytes);
    free(line);
    return rc;
}

/* ---- the due check ---------------------------------------------------------------------------- */

static int (*wake_start)(const char *db, const char *workspace, const char *session);

void pic_wake_starter(int (*start)(const char *db, const char *workspace, const char *session)) { wake_start = start; }

/* The conversations a run was started for lately, so a fire that a run cannot take up (its model
 * has no key) is not started again on every look. */
static struct {
    char session[64];
    long long at;
} wake_started[16];

static int wake_recent(const char *session, long long now) {
    int oldest = 0;
    for (int i = 0; i < 16; i++) {
        if (strcmp(wake_started[i].session, session) == 0) {
            if (now - wake_started[i].at < 30000 && now >= wake_started[i].at) {
                return 1;
            }
            oldest = i;
            break;
        }
        if (wake_started[i].at < wake_started[oldest].at) {
            oldest = i;
        }
    }
    (void)snprintf(wake_started[oldest].session, sizeof wake_started[oldest].session, "%s", session);
    wake_started[oldest].at = now;
    return 0;
}

/* The journal's path: the lock's, less its suffix. */
static void wake_db_path(pic_store *s, char *out, size_t cap) {
    size_t n = s->lock_path ? strlen(s->lock_path) : 0, suffix = strlen(".pic-lock");
    out[0] = '\0';
    if (n > suffix && n - suffix < cap) {
        memcpy(out, s->lock_path, n - suffix);
        out[n - suffix] = '\0';
    }
}

/* The next time a wake of SESSION (NULL: any) is due, wall ms; 0 when none is. 0 or -1. */
static int wake_next(pic_store *s, const char *session, long long *next_ms) {
    return wake_int(s,
                    "SELECT coalesce(min(min(coalesce(w.due_ms, w.expires_ms), w.expires_ms)), 0) FROM pic_wake w"
                    " WHERE w.state = 'active' AND (?2 IS NULL OR w.session_id = ?2) AND NOT " WAKE_WAITING_SQL("w")
                    " AND ?1 = ?1",
                    0, session, next_ms);
}

int pic_wake_due(pic_store *s, const char *workspace, const char *session, int start, int *fired, long long *next_ms) {
    sqlite3_stmt *q = NULL;
    long long now = pic_wake_now_ms(), ids[64];
    size_t n = 0;
    int rc = 0;
    *fired = 0;
    *next_ms = 0;
    /* A read first: every look must not take the write lock to learn nothing. */
    if (sqlite3_prepare_v2(s->db,
                           "SELECT w.id FROM pic_wake w WHERE " WAKE_DUE_SQL("w") " AND (?2 IS NULL OR w.session_id = ?2)"
                           " AND (NOT " WAKE_WAITING_SQL("w") " OR w.expires_ms <= ?1) ORDER BY w.due_ms, w.id LIMIT 64",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, now);
    if (session) {
        sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC);
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        ids[n++] = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    for (size_t i = 0; i < n && rc == 0; i++) {
        char sid[64];
        int one = wake_fire(s, ids[i], now, sid, sizeof sid);
        if (one < 0) {
            rc = -1;
        } else {
            *fired += one;
        }
    }
    /* Monitors: each one's spool and process looked at, in no transaction until it fires. */
    if (rc == 0 && wake_mon) {
        long long mids[64];
        size_t nm = 0;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT id FROM pic_wake WHERE kind = 'monitor' AND state = 'active' AND (?1 IS NULL OR session_id = ?1)"
                               " ORDER BY id LIMIT 64",
                               -1, &q, NULL) == SQLITE_OK) {
            if (session) {
                sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
            }
            while (sqlite3_step(q) == SQLITE_ROW && nm < 64) {
                mids[nm++] = sqlite3_column_int64(q, 0);
            }
        }
        sqlite3_finalize(q);
        for (size_t i = 0; i < nm && rc == 0; i++) {
            int one = wake_monitor(s, mids[i], now, workspace);
            if (one < 0) {
                rc = -1;
            } else {
                *fired += one;
            }
        }
    }
    /* A fire waiting in a conversation nobody works: a pic run there takes it up. */
    if (rc == 0 && start && wake_start) {
        char db[4096], (*sids)[64] = NULL;
        size_t ns = 0;
        wake_db_path(s, db, sizeof db);
        if (sqlite3_prepare_v2(s->db,
                               "SELECT DISTINCT session_id FROM pic_inbox WHERE state = 'pending' AND sender LIKE 'wake:%'"
                               " AND (?1 IS NULL OR session_id = ?1) LIMIT 16",
                               -1, &q, NULL) == SQLITE_OK) {
            if (session) {
                sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
            }
            sids = calloc(16, sizeof *sids);
            while (sids && sqlite3_step(q) == SQLITE_ROW && ns < 16) {
                (void)snprintf(sids[ns++], 64, "%s", (const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        for (size_t i = 0; i < ns && db[0]; i++) {
            if (pic_lease_holder(s, sids[i]) == 0 && !wake_recent(sids[i], now)) {
                (void)wake_start(db, workspace, sids[i]);
            }
        }
        free(sids);
    }
    return rc == 0 ? wake_next(s, session, next_ms) : rc;
}

/* ---- goals: the stop gate ------------------------------------------------------------------------ */

/* The active goal of SUBMISSION's conversation, 0 when it has none. */
static long long wake_goal_of(pic_store *s, long long submission) {
    long long id = 0;
    return wake_int(s,
                    "SELECT coalesce((SELECT w.id FROM pic_wake w JOIN pic_submission u ON u.session_id = w.session_id WHERE"
                    " u.id = ?1 AND w.kind = 'goal' AND w.state = 'active' ORDER BY w.id DESC LIMIT 1), 0)",
                    submission, NULL, &id) == 0
               ? id
               : -1;
}

static int wake_check_cancelled(void *ctx) {
    (void)ctx;
    return pic_interrupted != 0;
}

int pic_wake_goal_active(pic_store *s, long long submission) { return wake_goal_of(s, submission) > 0; }

int pic_wake_goal_judge(pic_store *s, long long submission, const char *workspace, int exec_seconds) {
    long long goal = 0, had = 0;
    char *check = NULL, *facts = NULL;
    sqlite3_stmt *q = NULL;
    pic_hook_answer a;
    int rc = 0;
    if (!s->stop_policy || (goal = wake_goal_of(s, submission)) <= 0) {
        return goal < 0 ? -1 : 0;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT command FROM pic_wake WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, goal);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            check = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    q = NULL;
    /* The check: journaled as a hook run, started before it runs and done after; once a request. */
    if (check) {
        char ref[24];
        (void)snprintf(ref, sizeof ref, "%lld", goal);
        if (wake_int(s, "SELECT count(*) FROM pic_hook_run WHERE event = 'GoalCheck' AND submission_id = ?1 AND ref = CAST(?2 AS INTEGER)",
                     submission, ref, &had) != 0) {
            free(check);
            return -1;
        }
        if (!had && !pic_interrupted) {
            const pic_executor *ex = pic_executor_get();
            static const char *const env[] = {"PIC_GOAL_CHECK=1", NULL};
            pic_spawn_result p;
            int64_t row = 0;
            if (pic_begin(s) != 0) {
                free(check);
                return -1;
            }
            if (sqlite3_prepare_v2(s->db,
                                   "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, command, state, created_ms)"
                                   " SELECT 'GoalCheck', session_id, id, ?2, ?3, 'started', ?4 FROM pic_submission WHERE id = ?1",
                                   -1, &q, NULL) != SQLITE_OK) {
                rc = wake_sql_fail(s);
            } else {
                sqlite3_bind_int64(q, 1, submission);
                sqlite3_bind_int64(q, 2, goal);
                sqlite3_bind_text(q, 3, check, -1, SQLITE_STATIC);
                sqlite3_bind_int64(q, 4, pic_wake_now_ms());
                rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
                row = sqlite3_last_insert_rowid(s->db);
            }
            sqlite3_finalize(q);
            q = NULL;
            if (rc != 0 || pic_commit(s) != 0) {
                pic_rollback(s);
                free(check);
                return -1;
            }
            pic_fault("after-goal-check-started");
            memset(&p, 0, sizeof p);
            if (ex->spawn) {
                pic_spawn_req r = {check, workspace, "", 0, env, exec_seconds, 0, PIC_WAKE_MONITOR_BYTES, wake_check_cancelled, NULL};
                (void)ex->spawn(ex->state, &r, &p);
            } else {
                (void)snprintf(p.why, sizeof p.why, "this build's executor runs no commands");
            }
            if (pic_begin(s) != 0) {
                free(p.out);
                free(p.err);
                free(check);
                return -1;
            }
            if (sqlite3_prepare_v2(s->db,
                                   "UPDATE pic_hook_run SET state = iif(?5, 'interrupted', 'done'), exit_code = nullif(?2, -1),"
                                   " duration_ms = ?3, context = ?4, error = CASE WHEN ?5 THEN 'cancelled before it finished'"
                                   " WHEN ?2 = -1 THEN nullif(?6, '') END WHERE id = ?1 AND state = 'started'",
                                   -1, &q, NULL) != SQLITE_OK) {
                rc = wake_sql_fail(s);
            } else {
                size_t no = p.out ? strlen(p.out) : 0, ne = p.err ? strlen(p.err) : 0;
                char *both = malloc(no + ne + 2);
                if (both) {
                    (void)snprintf(both, no + ne + 2, "%s%s%s", p.out ? p.out : "", no && ne ? "\n" : "", p.err ? p.err : "");
                }
                sqlite3_bind_int64(q, 1, row);
                sqlite3_bind_int64(q, 2, p.exited ? p.code : -1);
                sqlite3_bind_int64(q, 3, p.ms);
                sqlite3_bind_text(q, 4, both ? both : "", -1, SQLITE_TRANSIENT);
                sqlite3_bind_int(q, 5, p.cancelled);
                sqlite3_bind_text(q, 6, p.timed_out ? "timed out" : p.why, -1, SQLITE_TRANSIENT);
                rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
                free(both);
            }
            sqlite3_finalize(q);
            q = NULL;
            free(p.out);
            free(p.err);
            if (rc != 0 || pic_commit(s) != 0) {
                pic_rollback(s);
                free(check);
                return -1;
            }
        }
    }
    free(check);
    if (pic_interrupted) {
        return 0; /* the request is cancelled, and its goal paused */
    }
    /* The facts the policy decides with: all from the journal. */
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_object('goal', w.prompt, 'round', w.fires, 'maxRounds', coalesce(w.max_rounds, 0), 'stalls', w.stalls,"
            " 'maxStalls', coalesce(w.max_stalls, 0), 'worked', json(iif(EXISTS (SELECT 1 FROM pic_effect f JOIN pic_entry e"
            " ON e.seq = f.entry_seq WHERE e.submission_id = ?1 AND f.tool IN ('write', 'edit', 'bash') AND f.state IN ('done', 'unknown')),"
            " 'true', 'false')), 'check', json(CASE WHEN w.command IS NULL THEN 'null' ELSE (SELECT json_object('command', w.command,"
            " 'exitCode', iif(r.state = 'done', r.exit_code, NULL), 'output', substr(coalesce(r.context, ''), -2000), 'same',"
            " json(iif(coalesce(r.context, '') = coalesce((SELECT p.context FROM pic_hook_run p WHERE p.event = 'GoalCheck'"
            " AND p.ref = w.id AND p.submission_id < ?1 ORDER BY p.id DESC LIMIT 1), char(1)) AND r.exit_code IS"
            " (SELECT p.exit_code FROM pic_hook_run p WHERE p.event = 'GoalCheck' AND p.ref = w.id AND p.submission_id < ?1"
            " ORDER BY p.id DESC LIMIT 1), 'true', 'false')))"
            " FROM pic_hook_run r WHERE r.event = 'GoalCheck' AND r.submission_id = ?1 AND r.ref = w.id ORDER BY r.id DESC LIMIT 1) END),"
            " 'declared', json(CASE WHEN json_extract(w.options, '$.declared.submission') = ?1 THEN json_object('state',"
            " json_extract(w.options, '$.declared.state'), 'reason', json_extract(w.options, '$.declared.reason')) ELSE 'null' END))"
            " FROM pic_wake w WHERE w.id = ?2",
            -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, submission);
        sqlite3_bind_int64(q, 2, goal);
        if (sqlite3_step(q) == SQLITE_ROW) {
            facts = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (!facts) {
        return wake_sql_fail(s);
    }
    rc = pic_hooks_ask(s, "StopPolicy", submission, goal, s->stop_policy->name, s->stop_policy->answer, facts, &a);
    pic_hook_answer_free(&a);
    free(facts);
    return rc;
}

int pic_wake_goal_apply(pic_store *s, long long submission, int *fired) {
    sqlite3_stmt *q = NULL;
    char act[16] = "", *reason = NULL, *prompt = NULL, *check = NULL, *output = NULL, *line = NULL, session[64] = "";
    long long goal, fires = 0, stalls = 0, max_rounds = 0, max_stalls = 0, exit = -1;
    int stall = 0, rc = 0, ok = 0;
    *fired = 0;
    if ((goal = wake_goal_of(s, submission)) <= 0) {
        return goal < 0 ? -1 : 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_extract(r.context, '$.goal'), coalesce(json_extract(r.context, '$.stall'), 0), r.reason,"
                           " w.prompt, w.command, w.fires, w.stalls, coalesce(w.max_rounds, 0), coalesce(w.max_stalls, 0),"
                           " w.session_id, (SELECT coalesce(c.exit_code, -1) FROM pic_hook_run c WHERE c.event = 'GoalCheck'"
                           "  AND c.submission_id = ?1 AND c.ref = w.id ORDER BY c.id DESC LIMIT 1),"
                           " (SELECT substr(coalesce(c.context, ''), -2000) FROM pic_hook_run c WHERE c.event = 'GoalCheck'"
                           "  AND c.submission_id = ?1 AND c.ref = w.id ORDER BY c.id DESC LIMIT 1)"
                           " FROM pic_hook_run r JOIN pic_wake w ON w.id = r.ref WHERE r.event = 'StopPolicy' AND r.submission_id = ?1"
                           " AND r.ref = ?2 AND r.state = 'done' ORDER BY r.id LIMIT 1",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, goal);
    if (sqlite3_step(q) == SQLITE_ROW) {
        ok = 1;
        (void)snprintf(act, sizeof act, "%s", sqlite3_column_text(q, 0) ? (const char *)sqlite3_column_text(q, 0) : "");
        stall = sqlite3_column_int(q, 1);
        reason = sqlite3_column_text(q, 2) ? strdup((const char *)sqlite3_column_text(q, 2)) : NULL;
        prompt = strdup((const char *)sqlite3_column_text(q, 3));
        check = sqlite3_column_text(q, 4) ? strdup((const char *)sqlite3_column_text(q, 4)) : NULL;
        fires = sqlite3_column_int64(q, 5);
        stalls = sqlite3_column_int64(q, 6);
        max_rounds = sqlite3_column_int64(q, 7);
        max_stalls = sqlite3_column_int64(q, 8);
        (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 9));
        exit = sqlite3_column_type(q, 10) == SQLITE_NULL ? -1 : sqlite3_column_int64(q, 10);
        output = sqlite3_column_text(q, 11) ? strdup((const char *)sqlite3_column_text(q, 11)) : NULL;
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!ok || !prompt) { /* no answer (no policy, or it said nothing): the request just ends */
        goto out;
    }
    if (strcmp(act, "done") == 0) {
        rc = wake_state(s, goal, "ended", reason ? reason : "met", pic_wake_now_ms());
    } else if (strcmp(act, "needs") == 0) {
        rc = wake_state(s, goal, "needs", reason ? reason : "it needs you", pic_wake_now_ms());
    } else if (strcmp(act, "continue") == 0) {
        long long now_stalls = stall ? stalls + 1 : 0;
        char why[160];
        if (max_stalls && now_stalls >= max_stalls) { /* the bounds are core's: they stop a runaway whatever the policy says */
            (void)snprintf(why, sizeof why, "%lld rounds in a row made no progress", now_stalls);
            rc = wake_state(s, goal, "needs", why, pic_wake_now_ms());
            if (rc == 0) {
                char n[24];
                (void)snprintf(n, sizeof n, "%lld", now_stalls);
                rc = wake_exec1(s, "UPDATE pic_wake SET stalls = CAST(?2 AS INTEGER) WHERE id = ?1", goal, n);
            }
        } else if (max_rounds && fires >= max_rounds) {
            (void)snprintf(why, sizeof why, "reached %lld rounds; the goal is not met yet", fires);
            rc = wake_state(s, goal, "needs", why, pic_wake_now_ms());
        } else {
            char key[96], sender[48], got[96], st[16];
            pic_inbox_msg m;
            if (!(line = wake_goal_round(s, goal, fires + 1, max_rounds, prompt, check, check ? exit : -2, output))) {
                rc = wake_fail(s, -1, "out of memory");
                goto out;
            }
            (void)snprintf(key, sizeof key, "wake:%lld:%lld", goal, fires + 1);
            (void)snprintf(sender, sizeof sender, "wake:%lld", goal);
            memset(&m, 0, sizeof m);
            m.session = session;
            m.key = key;
            m.line = line;
            m.sender = sender;
            rc = pic_inbox_accept(s, &m, got, sizeof got, st, sizeof st);
            if (rc == 1) {
                char refused[PIC_ERR_CAP + 40];
                (void)snprintf(refused, sizeof refused, "its message was refused: %s", s->err);
                rc = wake_state(s, goal, "needs", refused, pic_wake_now_ms());
            } else if (rc == 0) {
                char n[24];
                (void)snprintf(n, sizeof n, "%lld", now_stalls);
                rc = wake_exec1(s,
                                "UPDATE pic_wake SET fires = fires + 1, rounds = fires + 1, stalls = CAST(?2 AS INTEGER),"
                                " fired_ms = CAST(unixepoch('subsec') * 1000 AS INTEGER), updated_ms = CAST(unixepoch('subsec') * 1000"
                                " AS INTEGER) WHERE id = ?1",
                                goal, n);
                *fired = rc == 0;
            }
        }
    }
out:
    free(reason);
    free(prompt);
    free(check);
    free(output);
    free(line);
    return rc;
}

int pic_wake_loop_next(pic_store *s, long long submission, long long ms) {
    long long id = 0;
    sqlite3_stmt *q = NULL;
    int rc;
    if (ms < 60000 || ms > 3600000) {
        return wake_fail(s, 1, "seconds is 60 to 3600");
    }
    if (wake_int(s,
                 "SELECT coalesce((SELECT w.id FROM pic_submission u JOIN pic_wake w ON w.id = " PIC_WAKE_OF_SQL("u")
                 " WHERE u.id = ?1 AND w.kind = 'loop' AND w.state = 'active'), 0)",
                 submission, NULL, &id) != 0) {
        return -1;
    }
    if (!id) {
        return wake_fail(s, 1, "this request was not started by a loop that is running");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET due_ms = ?2, updated_ms = ?3 WHERE id = ?1", -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int64(q, 2, pic_wake_now_ms() + ms);
    sqlite3_bind_int64(q, 3, pic_wake_now_ms());
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    if (rc != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

int pic_wake_goal_declare(pic_store *s, long long submission, const char *state, const char *reason) {
    long long goal = wake_goal_of(s, submission);
    sqlite3_stmt *q = NULL;
    int rc;
    if (goal <= 0) {
        return goal < 0 ? -1 : wake_fail(s, 1, "this conversation has no goal running");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET options = json_set(coalesce(options, '{}'), '$.declared', json_object('state', ?2,"
                           " 'reason', ?3, 'submission', ?4)) WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, goal);
    sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, reason ? reason : "", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, submission);
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    if (rc != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* ---- listing ---------------------------------------------------------------------------------- */

/* SQL: wake W's spend, summed from the journal's usage rows of the requests it started. */
#define WAKE_SPEND_SQL(W, FIELD)                                                                                       \
    "(SELECT coalesce(sum(json_extract(g.usage, '$." FIELD "')), 0) FROM pic_generation g JOIN pic_submission u"       \
    " ON u.id = g.submission_id WHERE u.session_id = " W ".session_id AND " PIC_WAKE_OF_SQL("u") " = " W ".id)"

char *pic_wake_list(pic_store *s, const char *session, int all) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    int rc;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_group_array(json_object('id', w.id, 'name', upper(substr(w.kind, 1, 1)) || w.id, 'kind', w.kind,"
            " 'session', w.session_id, 'prompt', w.prompt, 'command', w.command, 'everyMs', w.every_ms, 'state', w.state, 'why', w.why,"
            " 'creator', w.creator, 'fires', w.fires, 'dueMs', w.due_ms, 'firedMs', w.fired_ms, 'createdMs', w.created_ms,"
            " 'expiresMs', w.expires_ms, 'asking', json(iif(w.state = 'needs' AND coalesce(json_extract(w.options, '$.approval'), '')"
            " = 'asked', 'true', 'false')), 'rounds', w.rounds, 'maxRounds', w.max_rounds, 'stalls', w.stalls, 'cost', " WAKE_SPEND_SQL("w", "pic_cost.total") ", 'tokens',"
            " " WAKE_SPEND_SQL("w", "pic_tokens.totalTokens") ", 'waiting', json(iif(" WAKE_WAITING_SQL("w") ", 'true', 'false')),"
            " 'late', json(iif(w.state = 'active' AND NOT " WAKE_WAITING_SQL("w") " AND w.due_ms < ?1 - ?3, 'true', 'false'))))"
            " FROM (SELECT * FROM pic_wake WHERE (?2 IS NULL OR session_id = ?2) AND (?4 OR state != 'ended') ORDER BY id) w",
            -1, &q, NULL) != SQLITE_OK) {
        (void)wake_sql_fail(s);
        return NULL;
    }
    sqlite3_bind_int64(q, 1, pic_wake_now_ms());
    if (session) {
        sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 3, PIC_WAKE_LATE_MS);
    sqlite3_bind_int(q, 4, all);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!out) {
        (void)(rc == SQLITE_ROW ? wake_fail(s, -1, "out of memory") : wake_sql_fail(s));
    }
    return out;
}

int pic_usage_by_wake(pic_store *s, int json, FILE *out) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT upper(substr(w.kind, 1, 1)) || w.id, w.kind, w.state, w.fires,"
                           " (SELECT count(*) FROM pic_submission u WHERE u.session_id = w.session_id AND " PIC_WAKE_OF_SQL("u") " = w.id),"
                           " " WAKE_SPEND_SQL("w", "pic_tokens.totalTokens") ", " WAKE_SPEND_SQL("w", "pic_cost.total") ","
                           " w.session_id, pic_line(w.prompt, 40) FROM pic_wake w ORDER BY w.id",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    if (!json) {
        fprintf(out, "%-6s %-8s %-7s %6s %9s %10s %9s  %s\n", "WAKE", "KIND", "STATE", "FIRES", "REQUESTS", "TOKENS", "COST", "PROMPT");
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        if (json) {
            sqlite3_str *t = sqlite3_str_new(NULL);
            char *line;
            sqlite3_str_appendall(t, "{\"wake\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 0));
            sqlite3_str_appendall(t, ",\"kind\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 1));
            sqlite3_str_appendall(t, ",\"state\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 2));
            sqlite3_str_appendf(t, ",\"fires\":%lld,\"requests\":%lld,\"tokens\":%lld,\"cost\":%.6f,\"session\":",
                                (long long)sqlite3_column_int64(q, 3), (long long)sqlite3_column_int64(q, 4),
                                (long long)sqlite3_column_int64(q, 5), sqlite3_column_double(q, 6));
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 7));
            sqlite3_str_appendall(t, "}");
            line = sqlite3_str_finish(t);
            if (line) {
                fprintf(out, "%s\n", line);
            }
            sqlite3_free(line);
        } else {
            fprintf(out, "%-6s %-8s %-7s %6lld %9lld %10lld %9.4f  %s\n", (const char *)sqlite3_column_text(q, 0),
                    (const char *)sqlite3_column_text(q, 1), (const char *)sqlite3_column_text(q, 2),
                    (long long)sqlite3_column_int64(q, 3), (long long)sqlite3_column_int64(q, 4),
                    (long long)sqlite3_column_int64(q, 5), sqlite3_column_double(q, 6),
                    sqlite3_column_text(q, 8) ? (const char *)sqlite3_column_text(q, 8) : "");
        }
    }
    sqlite3_finalize(q);
    return 0;
}

/* ---- RPC commands ----------------------------------------------------------------------------- */

/* The journal for a command, opened narrowly from the call's path; with CREATE, one not made yet
 * is made (a loop started before the conversation's first request). 0, or -1 with c->err. */
static int wake_open(pic_rpc_call *c, pic_store *s, int create) {
    if (!c->db || !*c->db) {
        (void)snprintf(c->err, sizeof c->err, "no journal");
        return -1;
    }
    if (create && pic_open_narrow(s, c->db) != 0) {
        pic_close(s);
        if (pic_open(s, c->db) == 0) {
            return 0;
        }
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
        pic_close(s);
        return -1;
    }
    if (create) {
        return 0;
    }
    if (pic_open_narrow(s, c->db) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
        pic_close(s);
        return -1;
    }
    return 0;
}

static int wake_flag(const pic_rpc_call *c, const char *path) {
    char *v = pic_rpc_text(c, path);
    int on = v && (strcmp(v, "1") == 0 || strcmp(v, "true") == 0);
    free(v);
    return on;
}

/* c->data: {"wake": THE ONE, "wakes": SESSION's} after an action on wake ID. */
static int wake_reply(pic_rpc_call *c, pic_store *s, long long id, const char *session, const char *extra) {
    sqlite3_stmt *q = NULL;
    char *list = pic_wake_list(s, session, 0), *all = id ? pic_wake_list(s, NULL, 1) : NULL;
    int rc = -1;
    if (!list || (id && !all)) {
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
    } else if (sqlite3_prepare_v2(s->db,
                                  "SELECT json_object('wake', json((SELECT value FROM json_each(?1) WHERE json_extract(value, '$.id') = ?2)),"
                                  " 'wakes', json(?3), 'session', ?4) || ''",
                                  -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, all ? all : "[]", -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, id);
        sqlite3_bind_text(q, 3, list, -1, SQLITE_STATIC);
        if (session) {
            sqlite3_bind_text(q, 4, session, -1, SQLITE_STATIC);
        }
        if (sqlite3_step(q) == SQLITE_ROW) {
            const char *j = (const char *)sqlite3_column_text(q, 0);
            size_t n = strlen(j), e = extra ? strlen(extra) : 0;
            if ((c->data = malloc(n + e + 2))) {
                memcpy(c->data, j, n - 1); /* without its closing brace, for EXTRA */
                (void)snprintf(c->data + n - 1, e + 3, "%s}", extra ? extra : "");
                rc = 0;
            }
        }
    }
    sqlite3_finalize(q);
    free(list);
    free(all);
    return rc;
}

static int rpc_get_wakes(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), extra[160] = "";
    const char *which = session ? (strcmp(session, "all") == 0 ? NULL : session) : (c->session[0] ? c->session : NULL);
    int fired = 0, rc;
    long long next = 0;
    if (wake_open(c, &s, 0) != 0) {
        free(session);
        if (strncmp(c->err, "no journal", 10) == 0) { /* nothing run here yet: none */
            c->data = strdup("{\"wake\":null,\"wakes\":[],\"session\":null,\"fired\":0,\"nextDueMs\":0}");
            return c->data ? 0 : -1;
        }
        return -1;
    }
    if (wake_flag(c, "$.fire") ? pic_wake_due(&s, c->workspace, NULL, 1, &fired, &next) != 0 || wake_next(&s, which, &next) != 0
                               : wake_next(&s, which, &next) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        pic_close(&s);
        free(session);
        return -1;
    }
    (void)snprintf(extra, sizeof extra, ",\"fired\":%d,\"nextDueMs\":%lld,\"nowMs\":%lld", fired, next, pic_wake_now_ms());
    rc = wake_reply(c, &s, 0, which, extra);
    pic_close(&s);
    free(session);
    return rc;
}

static int rpc_create_wake(pic_rpc_call *c) {
    pic_store s;
    pic_wake_new w;
    char *prompt = pic_rpc_text(c, "$.prompt"), *every = pic_rpc_text(c, "$.every"), *kind = pic_rpc_text(c, "$.kind"),
         *session = pic_rpc_text(c, "$.session"), *command = pic_rpc_text(c, "$.command"), *check = pic_rpc_text(c, "$.check"),
         *rounds = pic_rpc_text(c, "$.rounds"), sid[64] = "";
    long long id = 0, ms = 0;
    int rc = -1;
    memset(&w, 0, sizeof w);
    if (every && *every && pic_wake_parse_every(every, &ms) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%.60s is not an interval (5m, 90s, 2h, 1d)", every);
    } else if (wake_open(c, &s, 1) == 0) {
        w.session = session ? session : c->session;
        w.kind = kind ? kind : "loop";
        w.prompt = prompt;
        w.every_ms = ms;
        w.creator = "user";
        w.model = c->model;
        w.command = command;
        w.workspace = c->workspace;
        w.done = wake_flag(c, "$.done");
        w.restart = wake_flag(c, "$.restart");
        w.check = check;
        w.rounds = rounds ? strtol(rounds, NULL, 10) : 0;
        rc = pic_wake_create(&s, &w, &id, sid, sizeof sid);
        if (rc != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
            rc = -1;
        } else {
            rc = wake_reply(c, &s, id, sid, NULL);
        }
        pic_close(&s);
    }
    free(prompt);
    free(every);
    free(kind);
    free(session);
    free(command);
    free(check);
    free(rounds);
    return rc;
}

static int wake_action(pic_rpc_call *c, const char *action) {
    pic_store s;
    char *name = pic_rpc_text(c, "$.id"), sid[64] = "";
    long long id = 0;
    int rc = -1;
    if (!name) {
        (void)snprintf(c->err, sizeof c->err, "id is required (L1, M2, G3)");
        return -1;
    }
    if (wake_open(c, &s, 0) == 0) {
        if (pic_wake_resolve(&s, name, &id) != 0 ||
            (strcmp(action, "approve") == 0 || strcmp(action, "decline") == 0 ? pic_wake_decide(&s, id, action[0] == 'a')
                                                                                : pic_wake_set(&s, id, action, NULL)) != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        } else {
            sqlite3_stmt *q = NULL;
            if (sqlite3_prepare_v2(s.db, "SELECT session_id FROM pic_wake WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_int64(q, 1, id);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
            rc = wake_reply(c, &s, id, sid, NULL);
        }
        pic_close(&s);
    }
    free(name);
    return rc;
}

static int rpc_pause_wake(pic_rpc_call *c) { return wake_action(c, "pause"); }
static int rpc_resume_wake(pic_rpc_call *c) { return wake_action(c, "resume"); }
static int rpc_stop_wake(pic_rpc_call *c) { return wake_action(c, "stop"); }
static int rpc_approve_wake(pic_rpc_call *c) { return wake_action(c, "approve"); }
static int rpc_decline_wake(pic_rpc_call *c) { return wake_action(c, "decline"); }

static int rpc_pause_wakes(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), extra[40];
    const char *which = session ? session : c->session;
    int count = 0, rc = -1;
    if (!which || !*which) { /* a conversation not begun has none */
        free(session);
        c->data = strdup("{\"wake\":null,\"wakes\":[],\"session\":null,\"paused\":0}");
        return c->data ? 0 : -1;
    }
    if (wake_open(c, &s, 0) == 0) {
        if (pic_wake_pause_all(&s, which, NULL, &count) != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        } else {
            (void)snprintf(extra, sizeof extra, ",\"paused\":%d", count);
            rc = wake_reply(c, &s, 0, which, extra);
        }
        pic_close(&s);
    }
    free(session);
    return rc;
}

const pic_rpc_command pic_get_wakes_rpc = {"get_wakes", "the conversation's loops, monitors and goals; fire: true fires what is due",
                                           PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_wakes};
const pic_rpc_command pic_create_wake_rpc = {"create_wake", "start a loop (prompt, every) or a monitor (kind monitor, command, done, restart)",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_create_wake};
const pic_rpc_command pic_pause_wake_rpc = {"pause_wake", "pause a loop, monitor or goal by id",
                                            PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_pause_wake};
const pic_rpc_command pic_resume_wake_rpc = {"resume_wake", "resume a paused loop, monitor or goal by id",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_resume_wake};
const pic_rpc_command pic_stop_wake_rpc = {"stop_wake", "end a loop, monitor or goal by id",
                                           PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_stop_wake};
const pic_rpc_command pic_approve_wake_rpc = {"approve_wake", "start a loop or goal the model asked for, by id",
                                              PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_approve_wake};
const pic_rpc_command pic_decline_wake_rpc = {"decline_wake", "refuse a loop or goal the model asked for, by id",
                                              PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_decline_wake};
const pic_rpc_command pic_pause_wakes_rpc = {"pause_wakes", "pause every loop, monitor and goal of the conversation (/stop)",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_pause_wakes};