Skip to content
pi-c Artifact [e2addac465]
Login

Artifact [e2addac465]

Artifact e2addac465676076c2989a8475daae10f215c8673f601484af8587d1cf6d2e32:


/* Command hooks (hooks.h): the configuration, the runner, and their journal.
 * A hook's command runs outside any transaction; what it decided is then
 * journaled, with its effect where it has one, so a resumed run acts on the
 * journal and never runs a hook a second time for the same thing. */
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <regex.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#include "hooks.h"
#include "input.h"
#include "net.h"
#include "pic.h"
#include "platform.h"
#include "userdb.h"

#define HOOK_FILE_MAX (1u << 20)
#define HOOK_OUT_MAX (1u << 20) /* bytes kept from a run's stdout, and from its stderr */
#define HOOK_DEFAULT_SECONDS 10
#define HOOK_MAX_SECONDS 60

typedef struct {
    char *event, *matcher, *command, *file;
    int seconds, async;
    int any;   /* no matcher, or "*" */
    int exact; /* names separated by |, compared whole */
    int bad;   /* a pattern that does not compile: matches nothing */
    regex_t re;
} hook;

struct pic_hooks {
    hook *list;
    size_t n, cap;
    char workspace[PATH_MAX]; /* real path: cwd */
    char userdb[PATH_MAX];    /* transcript_path: ~/.pic/pic.sqlite, where the conversation's Pi lines are */
    char owner[96];
    int owned;
};

static char *dup_str(const char *s) {
    size_t n;
    char *p;
    if (!s) {
        return NULL;
    }
    n = strlen(s) + 1;
    if ((p = malloc(n))) {
        memcpy(p, s, n);
    }
    return p;
}

static char *fmt(const char *f, ...) {
    va_list ap;
    char *out;
    va_start(ap, f);
    out = sqlite3_vmprintf(f, ap);
    va_end(ap);
    if (out) { /* callers free() it */
        char *copy = dup_str(out);
        sqlite3_free(out);
        return copy;
    }
    return NULL;
}

/* ---- configuration -------------------------------------------------------- */

static void hook_clear(hook *k) {
    free(k->event);
    free(k->matcher);
    free(k->command);
    free(k->file);
    if (!k->any && !k->exact && !k->bad) {
        regfree(&k->re);
    }
}

void pic_hooks_free(pic_hooks *h) {
    if (!h) {
        return;
    }
    for (size_t i = 0; i < h->n; i++) {
        hook_clear(&h->list[i]);
    }
    free(h->list);
    free(h);
}

/* Claude Code compares a matcher of plain names (Write, Edit|Write) whole,
 * and searches with any other as a regular expression. */
static void classify(hook *k, FILE *warn) {
    const char *m = k->matcher;
    k->any = !*m || strcmp(m, "*") == 0;
    if (k->any) {
        return;
    }
    k->exact = strspn(m, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_|") == strlen(m);
    if (!k->exact && regcomp(&k->re, m, REG_EXTENDED | REG_NOSUB) != 0) {
        k->bad = 1;
        if (warn) {
            fprintf(warn, "pic: %s: matcher %s is not a regular expression pic reads; it matches nothing\n", k->file, m);
        }
    }
}

static int name_in(const char *list, const char *name) {
    size_t n = name ? strlen(name) : 0;
    for (const char *p = list; name && *p;) {
        size_t len = strcspn(p, "|");
        if (len == n && strncmp(p, name, n) == 0) {
            return 1;
        }
        p += len + (p[len] == '|');
    }
    return 0;
}

static int matches(const hook *k, const char *name, const char *alt) {
    if (k->any || (!name && !alt)) {
        return 1;
    }
    if (k->bad) {
        return 0;
    }
    if (k->exact) {
        return name_in(k->matcher, name) || name_in(k->matcher, alt);
    }
    return (name && regexec(&k->re, name, 0, NULL, 0) == 0) || (alt && regexec(&k->re, alt, 0, NULL, 0) == 0);
}

/* The command hooks of one file, in its order. A file that is missing adds
 * nothing; one that does not parse is skipped with a warning. */
static int load_file(pic_hooks *h, const char *path, FILE *warn) {
    sqlite3 *db = NULL;
    sqlite3_stmt *q = NULL;
    size_t len = 0;
    char *raw = pic_input_read(path, HOOK_FILE_MAX, 0, &len, NULL);
    int rc = 0;
    if (!raw) {
        if (errno != ENOENT && warn) {
            fprintf(warn, "pic: cannot read %s: %s\n", path, strerror(errno));
        }
        return 0;
    }
    if (sqlite3_open(":memory:", &db) != SQLITE_OK ||
        sqlite3_prepare_v2(
            db,
            /* Every element is checked before it is read as JSON: a string
             * where an object belongs is passed over, not an error. */
            "SELECT ev.key, CASE WHEN json_type(m.value,'$.matcher') = 'text' THEN json_extract(m.value,'$.matcher') ELSE '' END,"
            " json_extract(h.value,'$.command'), json_extract(h.value,'$.timeout'),"
            " coalesce(json_extract(h.value,'$.async') IN (1, 'true'), 0)"
            " FROM json_each(?1,'$.hooks') ev,"
            " json_each(CASE WHEN ev.type = 'array' THEN ev.value ELSE '[]' END) m,"
            " json_each(coalesce(CASE WHEN m.type = 'object' THEN CASE WHEN json_type(m.value,'$.hooks') = 'array'"
            "   THEN json_extract(m.value,'$.hooks') END END, '[]')) h"
            " WHERE CASE WHEN h.type = 'object' THEN json_extract(h.value,'$.type') = 'command'"
            "   AND json_type(h.value,'$.command') = 'text' ELSE 0 END"
            " AND json_valid(?1) AND json_type(?1,'$.hooks') = 'object'"
            " ORDER BY ev.id, m.id, h.id",
            -1, &q, NULL) != SQLITE_OK) {
        free(raw);
        sqlite3_close(db);
        return -1;
    }
    sqlite3_bind_text(q, 1, raw, (int)len, SQLITE_STATIC);
    {
        sqlite3_stmt *v = NULL;
        int ok = 0;
        if (sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1,'$.hooks') = 'object'", -1, &v, NULL) == SQLITE_OK) {
            sqlite3_bind_text(v, 1, raw, (int)len, SQLITE_STATIC);
            ok = sqlite3_step(v) == SQLITE_ROW && sqlite3_column_int(v, 0);
        }
        sqlite3_finalize(v);
        if (!ok && warn) {
            fprintf(warn, "pic: %s is not a hooks file (a JSON object with a \"hooks\" object); skipped\n", path);
        }
    }
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        hook *k;
        double t = sqlite3_column_double(q, 3);
        if (h->n == h->cap) {
            size_t cap = h->cap ? h->cap * 2 : 8;
            hook *grown = realloc(h->list, cap * sizeof *grown);
            if (!grown) {
                rc = -1;
                break;
            }
            h->list = grown;
            h->cap = cap;
        }
        k = &h->list[h->n];
        memset(k, 0, sizeof *k);
        k->event = dup_str((const char *)sqlite3_column_text(q, 0));
        k->matcher = dup_str((const char *)sqlite3_column_text(q, 1));
        k->command = dup_str((const char *)sqlite3_column_text(q, 2));
        k->file = dup_str(path);
        k->seconds = sqlite3_column_type(q, 3) == SQLITE_NULL || t <= 0 ? HOOK_DEFAULT_SECONDS
                     : t >= HOOK_MAX_SECONDS                            ? HOOK_MAX_SECONDS
                                                                        : (int)(t + 0.999);
        k->async = sqlite3_column_int(q, 4);
        if (!k->event || !k->matcher || !k->command || !k->file) {
            k->any = 1;
            hook_clear(k);
            rc = -1;
            break;
        }
        classify(k, warn);
        h->n++;
    }
    sqlite3_finalize(q);
    sqlite3_close(db);
    free(raw);
    return rc;
}

static int load_all(pic_hooks *h, const char *workspace, FILE *warn) {
    const char *home = getenv("HOME");
    char path[PATH_MAX];
    if (home && *home && snprintf(path, sizeof path, "%s/.pic/hooks.json", home) < (int)sizeof path &&
        load_file(h, path, warn) != 0) {
        return -1;
    }
    if (pic_trust_get(h->workspace) == 1 && snprintf(path, sizeof path, "%s/.pic/hooks.json", workspace) < (int)sizeof path &&
        load_file(h, path, warn) != 0) {
        return -1;
    }
    return 0;
}

static pic_hooks *hooks_new(const char *workspace) {
    pic_hooks *h = calloc(1, sizeof *h);
    if (h && !realpath(workspace, h->workspace)) {
        (void)snprintf(h->workspace, sizeof h->workspace, "%s", workspace);
    }
    return h;
}

pic_hooks *pic_hooks_load(const char *workspace, const char *owner, FILE *warn) {
    pic_hooks *h = hooks_new(workspace);
    if (!h || load_all(h, workspace, warn) != 0 || h->n == 0) {
        pic_hooks_free(h);
        return NULL;
    }
    if (pic_userdb_path(h->userdb, sizeof h->userdb) != 0) {
        h->userdb[0] = '\0';
    }
    if (owner && *owner) {
        (void)snprintf(h->owner, sizeof h->owner, "%s", owner);
        h->owned = 1;
    } else {
        (void)snprintf(h->owner, sizeof h->owner, "pic-%ld-%lld", (long)getpid(), (long long)pic_platform_get()->wall_ns());
    }
    return h;
}

int pic_hooks_list(const char *workspace, FILE *out) {
    pic_hooks *h = hooks_new(workspace);
    if (!h || load_all(h, workspace, stderr) != 0) {
        pic_hooks_free(h);
        return -1;
    }
    for (size_t i = 0; i < h->n; i++) {
        const hook *k = &h->list[i];
        fprintf(out, "%s\t%s\t%d\t%s\t%s\t%s\n", k->event, k->matcher, k->seconds, k->async ? "async" : "sync", k->command,
                k->file);
    }
    pic_hooks_free(h);
    return 0;
}

int pic_hooks_has(const pic_hooks *h, const char *event) {
    for (size_t i = 0; h && i < h->n; i++) {
        if (strcmp(h->list[i].event, event) == 0) {
            return 1;
        }
    }
    return 0;
}

int pic_hooks_owned(const pic_hooks *h) { return h && h->owned; }

/* ---- running a command ------------------------------------------------------ */

typedef struct {
    char *p;
    size_t n, cap;
} obuf;

static void obuf_add(obuf *b, const char *src, size_t n) {
    if (b->n + n > HOOK_OUT_MAX) {
        n = HOOK_OUT_MAX - b->n;
    }
    if (n == 0) {
        return;
    }
    if (b->n + n + 1 > b->cap) {
        size_t cap = (b->n + n + 1) * 2;
        char *grown = realloc(b->p, cap);
        if (!grown) {
            return;
        }
        b->p = grown;
        b->cap = cap;
    }
    memcpy(b->p + b->n, src, n);
    b->n += n;
    b->p[b->n] = '\0';
}

typedef struct {
    int started, exited, code, timed_out, interrupted;
    long ms;
    obuf out, err;
    char why[160];
} proc;

static long now_ms(void) { return (long)(pic_platform_get()->mono_ns() / 1000000u); }

/* Closes every descriptor above stderr but KEEP and KEEP2: the journal's
 * lock and files must not outlive pic in a hook's process. The open ones
 * are listed from /dev/fd, so only they are closed. */
static void close_inherited(int keep, int keep2) {
    int fds[1024];
    size_t n = 0;
    DIR *d = opendir("/dev/fd");
    if (d) {
        struct dirent *e;
        int self = dirfd(d);
        while ((e = readdir(d)) != NULL && n < sizeof fds / sizeof fds[0]) {
            char *end;
            long fd = strtol(e->d_name, &end, 10);
            if (*end == '\0' && end != e->d_name && fd > 2 && fd != self && fd != keep && fd != keep2) {
                fds[n++] = (int)fd;
            }
        }
        closedir(d);
        for (size_t i = 0; i < n; i++) {
            (void)close(fds[i]);
        }
        return;
    }
    for (int fd = 3; fd < 1024; fd++) {
        if (fd != keep && fd != keep2) {
            (void)close(fd);
        }
    }
}

/* Reads what FD has, at most BUDGET bytes (a background child may write
 * without end); closes it at EOF or on an error. */
static void pump(int *fd, obuf *b, size_t budget) {
    while (*fd >= 0 && budget > 0) {
        char buf[4096];
        ssize_t n = read(*fd, buf, budget < sizeof buf ? budget : sizeof buf);
        if (n > 0) {
            obuf_add(b, buf, (size_t)n);
            budget -= (size_t)n;
        } else if (n < 0 && errno == EINTR) {
            continue;
        } else {
            if (n == 0 || errno != EAGAIN) {
                close(*fd);
                *fd = -1;
            }
            return;
        }
    }
}

static void close_fd(int *fd) {
    if (*fd >= 0) {
        close(*fd);
        *fd = -1;
    }
}

static void write_all(int fd, const void *p, size_t n) {
    const char *c = p;
    while (n > 0) {
        ssize_t w = write(fd, c, n);
        if (w < 0 && errno == EINTR) {
            continue;
        }
        if (w <= 0) {
            return;
        }
        c += w;
        n -= (size_t)w;
    }
}

/* The watchdog: a process of its own (stdin, stdout and stderr already the
 * hook's) that starts the command in a process group of its own and kills
 * that group at the deadline, or when LIFE closes or is written to (pic
 * died, or Ctrl-C), so no hook outlives its timeout or pic. It reports on
 * REPORT: 'X' and the wait status, 'T' (timed out), 'D' (pic gone or
 * interrupted) or 'F' (no fork), then exits. */
static void watchdog(const char *command, const char *cwd, int seconds, int life, int report) {
    long deadline = now_ms() + seconds * 1000L;
    int status = 0, null;
    char tag = 'X';
    pid_t g;
    (void)signal(SIGINT, SIG_IGN); /* a terminal's Ctrl-C reaches pic, which says so on LIFE */
    (void)signal(SIGTERM, SIG_IGN);
    (void)signal(SIGHUP, SIG_IGN);
    (void)signal(SIGPIPE, SIG_IGN);
    g = fork();
    if (g == 0) {
        sigset_t none;
        (void)setpgid(0, 0);
        close(life);
        close(report);
        (void)signal(SIGPIPE, SIG_DFL);
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGTERM, SIG_DFL);
        (void)signal(SIGHUP, SIG_DFL);
        (void)signal(SIGQUIT, SIG_DFL);
        sigemptyset(&none);
        (void)sigprocmask(SIG_SETMASK, &none, NULL);
        if (chdir(cwd) != 0) {
            _exit(126);
        }
        (void)setenv("PIC_HOOK", "1", 1);
        execl("/bin/sh", "sh", "-c", command, (char *)NULL);
        _exit(127);
    }
    if (g < 0) {
        tag = 'F';
        write_all(report, &tag, 1);
        _exit(0);
    }
    (void)setpgid(g, g);
    /* pic sees the end of the output from the command alone. */
    if ((null = open("/dev/null", O_RDWR)) >= 0) {
        (void)dup2(null, STDIN_FILENO);
        (void)dup2(null, STDOUT_FILENO);
        (void)dup2(null, STDERR_FILENO);
        close(null);
    }
    for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) {
        struct pollfd p = {life, POLLIN, 0};
        long left;
        if (waitpid(g, &status, WNOHANG) == g) {
            break;
        }
        if ((left = deadline - now_ms()) <= 0) {
            tag = 'T';
            break;
        }
        if (poll(&p, 1, (int)(left < wait_ms ? left : wait_ms)) > 0 && p.revents) {
            tag = 'D';
            break;
        }
    }
    if (tag != 'X') {
        (void)kill(-g, SIGKILL);
        while (waitpid(g, &status, 0) < 0 && errno == EINTR) {
        }
    }
    write_all(report, &tag, 1);
    write_all(report, &status, sizeof status);
    _exit(0);
}

static void run_command(const char *command, const char *cwd, const char *input, int seconds, proc *r) {
    int in[2] = {-1, -1}, out[2] = {-1, -1}, err[2] = {-1, -1}, life[2] = {-1, -1}, report[2] = {-1, -1};
    size_t sent = 0, len = strlen(input);
    long start = now_ms(), backstop = start + seconds * 1000L + 5000;
    pid_t pid;
    memset(r, 0, sizeof *r);
    if (pipe(in) != 0 || pipe(out) != 0 || pipe(err) != 0 || pipe(life) != 0 || pipe(report) != 0) {
        (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno));
        close_fd(&in[0]), close_fd(&in[1]), close_fd(&out[0]), close_fd(&out[1]), close_fd(&err[0]), close_fd(&err[1]);
        close_fd(&life[0]), close_fd(&life[1]), close_fd(&report[0]), close_fd(&report[1]);
        return;
    }
    pid = fork();
    if (pid == 0) {
        (void)dup2(in[0], STDIN_FILENO);
        (void)dup2(out[1], STDOUT_FILENO);
        (void)dup2(err[1], STDERR_FILENO);
        close_inherited(life[0], report[1]);
        watchdog(command, cwd, seconds, life[0], report[1]);
    }
    close_fd(&in[0]), close_fd(&out[1]), close_fd(&err[1]), close_fd(&life[0]), close_fd(&report[1]);
    if (pid < 0) {
        (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno));
        close_fd(&in[1]), close_fd(&out[0]), close_fd(&err[0]), close_fd(&life[1]), close_fd(&report[0]);
        return;
    }
    r->started = 1;
    (void)fcntl(in[1], F_SETFL, fcntl(in[1], F_GETFL) | O_NONBLOCK);
    (void)fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL) | O_NONBLOCK);
    (void)fcntl(err[0], F_SETFL, fcntl(err[0], F_GETFL) | O_NONBLOCK);
    if (len == 0) {
        close_fd(&in[1]);
    }
    for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) {
        struct pollfd p[3] = {{in[1], POLLOUT, 0}, {out[0], POLLIN, 0}, {err[0], POLLIN, 0}};
        if (waitpid(pid, NULL, WNOHANG) == pid) {
            break;
        }
        if (pic_interrupted && life[1] >= 0) { /* Ctrl-C: the watchdog ends the hook */
            write_all(life[1], "c", 1);
            close_fd(&life[1]);
        }
        if (now_ms() > backstop) { /* the watchdog itself is stuck */
            (void)kill(pid, SIGKILL);
            while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) {
            }
            break;
        }
        if (poll(p, 3, wait_ms) < 0 && errno != EINTR) {
            (void)snprintf(r->why, sizeof r->why, "poll: %s", strerror(errno));
        }
        if (in[1] >= 0 && p[0].revents) {
            ssize_t w = write(in[1], input + sent, len - sent);
            if (w > 0) {
                sent += (size_t)w;
            }
            if (sent == len || (w < 0 && errno != EAGAIN && errno != EINTR)) {
                close_fd(&in[1]); /* all of it, or the hook stopped reading */
            }
        }
        pump(&out[0], &r->out, HOOK_OUT_MAX);
        pump(&err[0], &r->err, HOOK_OUT_MAX);
    }
    /* What it wrote before it exited; a background child holding the pipes
     * is neither waited for nor read without end. */
    pump(&out[0], &r->out, HOOK_OUT_MAX);
    pump(&err[0], &r->err, HOOK_OUT_MAX);
    {
        char tag = 0;
        int status = 0;
        ssize_t got;
        while ((got = read(report[0], &tag, 1)) < 0 && errno == EINTR) {
        }
        if (got == 1 && tag == 'X' && read(report[0], &status, sizeof status) == (ssize_t)sizeof status) {
            if (WIFEXITED(status)) {
                r->exited = 1;
                r->code = WEXITSTATUS(status);
            } else {
                (void)snprintf(r->why, sizeof r->why, "terminated by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0);
            }
        } else if (got == 1 && tag == 'T') {
            r->timed_out = 1;
        } else if (got == 1 && tag == 'D') {
            r->interrupted = 1;
            (void)snprintf(r->why, sizeof r->why, "interrupted (Ctrl-C); its process group was killed");
        } else {
            (void)snprintf(r->why, sizeof r->why, got == 1 && tag == 'F' ? "cannot start: fork failed" : "its watchdog died");
        }
    }
    close_fd(&in[1]), close_fd(&out[0]), close_fd(&err[0]), close_fd(&life[1]), close_fd(&report[0]);
    r->ms = now_ms() - start;
}

/* An async hook runs on its own, watchdog and all, in a process that holds
 * neither pic's journal nor its output: pic goes on at once. */
static void run_async(const char *command, const char *cwd, const char *input, int seconds) {
    pid_t a = fork();
    if (a == 0) {
        proc r;
        int null = open("/dev/null", O_RDWR);
        if (null >= 0) {
            (void)dup2(null, STDIN_FILENO);
            (void)dup2(null, STDOUT_FILENO);
            (void)dup2(null, STDERR_FILENO);
        }
        close_inherited(-1, -1);
        (void)setsid();
        (void)signal(SIGINT, SIG_IGN);
        (void)signal(SIGHUP, SIG_IGN);
        pic_interrupted = 0;
        if (fork() != 0) {
            _exit(0);
        }
        run_command(command, cwd, input, seconds, &r);
        _exit(0);
    }
    if (a > 0) {
        while (waitpid(a, NULL, 0) < 0 && errno == EINTR) {
        }
    }
}

/* ---- firing an event ---------------------------------------------------------- */

static int is(const char *a, const char *b) { return strcmp(a, b) == 0; }

static char *trimmed(const obuf *b) {
    const char *p = b->p ? b->p : "";
    size_t n;
    while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') {
        p++;
    }
    n = strlen(p);
    while (n > 0 && (p[n - 1] == ' ' || p[n - 1] == '\t' || p[n - 1] == '\n' || p[n - 1] == '\r')) {
        n--;
    }
    {
        char *out = malloc(n + 1);
        if (out) {
            memcpy(out, p, n);
            out[n] = '\0';
        }
        return out;
    }
}

static void note(pic_store *s, const char *event, const char *text) {
    char line[600];
    (void)snprintf(line, sizeof line, "%s hook: %s", event, text);
    pic_ev_note(s, line);
}

/* How one run ended, read as Claude Code reads it. */
static void judge(pic_store *s, const char *event, const proc *p, int seconds, pic_hook_run *r) {
    char *out = NULL, *err = trimmed(&p->err);
    int blocks = is(event, "UserPromptSubmit") || is(event, "Stop") || is(event, "PostToolUse");
    int context_events = is(event, "SessionStart") || is(event, "UserPromptSubmit") || is(event, "PostToolUse") ||
                         is(event, "PreCompact");
    r->ms = p->ms;
    r->exited = p->exited;
    r->code = p->code;
    r->interrupted = p->interrupted;
    if (!p->started || (!p->exited && !p->timed_out)) {
        r->error = dup_str(p->why);
    } else if (p->timed_out) {
        r->error = fmt("timed out after %d s (its process group was killed)", seconds);
    } else if (p->code == 2) {
        if (is(event, "PreToolUse") || blocks) {
            r->outcome = is(event, "PreToolUse") ? "deny" : "block";
            r->reason = err && *err ? dup_str(err) : fmt("blocked by a %s hook", event);
        } else {
            r->error = fmt("exit 2, which does not block %s: %.200s", event, err ? err : "");
        }
    } else if (p->code != 0) {
        r->error = fmt("exit %d%s%.200s", p->code, err && *err ? ": " : "", err ? err : "");
    } else if ((out = trimmed(&p->out)) && out[0] == '{') {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT CASE WHEN json_type(?1,'$.hookSpecificOutput.additionalContext') = 'text'"
                               " THEN json_extract(?1,'$.hookSpecificOutput.additionalContext') END,"
                               " json_extract(?1,'$.hookSpecificOutput.permissionDecision'),"
                               " json_extract(?1,'$.hookSpecificOutput.permissionDecisionReason'),"
                               " json_extract(?1,'$.decision'), json_extract(?1,'$.reason'), json_extract(?1,'$.systemMessage')"
                               " WHERE json_valid(?1) AND json_type(?1) = 'object'",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, out, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                const char *context = (const char *)sqlite3_column_text(q, 0);
                const char *perm = (const char *)sqlite3_column_text(q, 1);
                const char *perm_reason = (const char *)sqlite3_column_text(q, 2);
                const char *decision = (const char *)sqlite3_column_text(q, 3);
                const char *reason = (const char *)sqlite3_column_text(q, 4);
                const char *message = (const char *)sqlite3_column_text(q, 5);
                if (context && *context && context_events) {
                    r->context = dup_str(context);
                }
                if (is(event, "PreToolUse")) {
                    /* "ask" runs the call: pic has no permission prompts. */
                    if ((perm && is(perm, "deny")) || (!perm && decision && is(decision, "block"))) {
                        r->outcome = "deny";
                        r->reason = perm_reason && *perm_reason ? dup_str(perm_reason)
                                    : reason && *reason         ? dup_str(reason)
                                                                : dup_str("denied by a PreToolUse hook");
                    } else if (perm && (is(perm, "allow") || is(perm, "ask"))) {
                        r->outcome = is(perm, "allow") ? "allow" : "ask";
                    } else if (!perm && decision && is(decision, "approve")) {
                        r->outcome = "allow";
                    }
                } else if (blocks && decision && is(decision, "block")) {
                    r->outcome = "block";
                    r->reason = reason && *reason ? dup_str(reason) : fmt("blocked by a %s hook", event);
                }
                if (message && *message) {
                    note(s, event, message);
                }
            } else {
                r->error = dup_str("stdout is not valid JSON; ignored");
            }
        }
        sqlite3_finalize(q);
    } else if (out && *out && (is(event, "SessionStart") || is(event, "UserPromptSubmit"))) {
        r->context = dup_str(out); /* plain stdout is context for these two */
    }
    if (r->error) {
        note(s, event, r->error);
    }
    free(out);
    free(err);
}

/* The common fields, then EXTRA's members. */
static char *input_json(pic_store *s, const pic_hook_fire *f, const char *extra) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('session_id', ?1, 'transcript_path', ?2, 'cwd', ?3, 'hook_event_name', ?4,"
                           " 'harness', 'pic', 'permission_mode', 'bypassPermissions')",
                           -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, f->session, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, s->hooks->userdb, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, s->hooks->workspace, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, f->event, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *base = (const char *)sqlite3_column_text(q, 0);
        size_t n = strlen(base);
        if (extra && extra[0] == '{' && strcmp(extra, "{}") != 0) {
            out = fmt("%.*s,%s", (int)(n - 1), base, extra + 1);
        } else {
            out = dup_str(base);
        }
    }
    sqlite3_finalize(q);
    return out;
}

static void bind_opt_text(sqlite3_stmt *q, int i, const char *t) {
    if (t) {
        sqlite3_bind_text(q, i, t, -1, SQLITE_STATIC);
    } else {
        sqlite3_bind_null(q, i);
    }
}

/* Journals a run of COMMAND as started (a marker, done, when COMMAND is
 * NULL), in its own transaction; its row id, or -1. */
static int64_t row_start(pic_store *s, const pic_hook_fire *f, const char *command) {
    sqlite3_stmt *q = NULL;
    int64_t id = -1;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, owner, command, duration_ms, state,"
                           " created_ms) VALUES(?1, nullif(?2, ''), nullif(?3, 0), ?4, ?5, ?6, 0,"
                           " CASE WHEN ?6 IS NULL THEN 'done' ELSE 'started' END, CAST(unixepoch('subsec') * 1000 AS INTEGER))",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, f->event, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, f->session, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 3, f->submission);
        sqlite3_bind_int64(q, 4, f->ref);
        bind_opt_text(q, 5, s->hooks ? s->hooks->owner : NULL);
        bind_opt_text(q, 6, command);
        if (sqlite3_step(q) == SQLITE_DONE) {
            id = sqlite3_last_insert_rowid(s->db);
        }
    }
    if (id < 0) {
        (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    }
    sqlite3_finalize(q);
    if (id < 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return id;
}

/* Journals how run ID ended, in its own transaction. */
static int row_finish(pic_store *s, int64_t id, const pic_hook_run *r) {
    sqlite3_stmt *q = NULL;
    int ok = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_hook_run SET exit_code = ?2, duration_ms = ?3, error = ?4, outcome = ?5, reason = ?6,"
                           " context = ?7, state = CASE WHEN ?8 THEN 'interrupted' ELSE 'done' END WHERE id = ?1 AND state = 'started'",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, id);
        if (r->exited) {
            sqlite3_bind_int(q, 2, r->code);
        } else {
            sqlite3_bind_null(q, 2);
        }
        sqlite3_bind_int64(q, 3, r->ms);
        bind_opt_text(q, 4, r->error);
        bind_opt_text(q, 5, r->outcome);
        bind_opt_text(q, 6, r->reason);
        bind_opt_text(q, 7, r->context);
        sqlite3_bind_int(q, 8, r->interrupted);
        ok = sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(s->db) == 1;
    }
    if (!ok) {
        (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    }
    sqlite3_finalize(q);
    if (!ok || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* SESSION's Pi lines exported through its latest entry, when it exists yet
 * (a new conversation's first prompt has no entries to read). */
static int exported(pic_store *s, const char *session) {
    sqlite3_stmt *q = NULL;
    int exists = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_session WHERE id = ? AND head_seq IS NOT NULL", -1, &q, NULL) ==
        SQLITE_OK) {
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
        exists = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) > 0;
    }
    sqlite3_finalize(q);
    return exists ? pic_export_pi_head(s, s->hooks->workspace, session) : 0;
}

static int matches_any(const hook *k, const char *const *names) {
    if (!names || !names[0]) {
        return matches(k, NULL, NULL);
    }
    for (; *names; names++) {
        if (matches(k, *names, NULL)) {
            return 1;
        }
    }
    return 0;
}

int pic_hook_fire_run(pic_store *s, pic_hook_fire *f, const char *const *names, const char *extra) {
    pic_hooks *h = s->hooks;
    char *input = NULL;
    int rc = 0;
    for (size_t i = 0; h && i < h->n && rc == 0 && !pic_interrupted; i++) {
        const hook *k = &h->list[i];
        int seen = 0;
        int64_t id;
        pic_hook_run *r;
        proc p;
        if (!is(k->event, f->event) || !matches_any(k, names)) {
            continue;
        }
        for (size_t j = 0; j < f->n; j++) { /* the same command twice runs once, as in Claude Code */
            seen |= is(f->runs[j].command, k->command);
        }
        if (seen) {
            continue;
        }
        if (!input) {
            /* What the hook may read of the conversation is committed first:
             * its Pi lines in ~/.pic/pic.sqlite, through its latest entry. */
            if (f->session[0] && exported(s, f->session) != 0) {
                char why[PIC_ERR_CAP];
                (void)snprintf(why, sizeof why, "conversation lines not written for the hook: %s", s->err);
                note(s, f->event, why);
                s->err[0] = '\0';
            }
            if (!(input = input_json(s, f, extra))) {
                (void)snprintf(s->err, sizeof s->err, "out of memory");
                return -1;
            }
        }
        {
            pic_hook_run *grown = realloc(f->runs, (f->n + 1) * sizeof *grown);
            if (!grown) {
                free(input);
                (void)snprintf(s->err, sizeof s->err, "out of memory");
                return -1;
            }
            f->runs = grown;
        }
        r = &f->runs[f->n++];
        memset(r, 0, sizeof *r);
        r->command = dup_str(k->command);
        if ((id = row_start(s, f, k->command)) < 0) {
            rc = -1;
            break;
        }
        if (!f->first) {
            f->first = id;
        }
        if (k->async) {
            run_async(k->command, h->workspace, input, k->seconds);
            r->error = dup_str("async: not waited for");
        } else {
            run_command(k->command, h->workspace, input, k->seconds, &p);
            pic_fault("after-hook-run");
            judge(s, f->event, &p, k->seconds, r);
            free(p.out.p);
            free(p.err.p);
        }
        rc = row_finish(s, id, r);
        if (r->outcome && (is(r->outcome, "deny") || is(r->outcome, "block"))) {
            char *joined = f->reason ? fmt("%s\n%s", f->reason, r->reason) : dup_str(r->reason);
            free(f->reason);
            f->reason = joined;
            f->blocked = 1;
        }
    }
    free(input);
    if (rc == 0 && f->marker && f->n == 0) {
        int64_t id = row_start(s, f, NULL);
        rc = id < 0 ? -1 : 0;
        f->first = id > 0 ? id : f->first;
    }
    return rc;
}

void pic_hook_fire_free(pic_hook_fire *f) {
    for (size_t i = 0; i < f->n; i++) {
        free(f->runs[i].command);
        free(f->runs[i].error);
        free(f->runs[i].reason);
        free(f->runs[i].context);
    }
    free(f->runs);
    free(f->reason);
    f->runs = NULL;
    f->reason = NULL;
    f->n = 0;
}

/* ---- journal helpers -------------------------------------------------------------- */

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

/* One text value from SQL with up to three text parameters and one integer
 * (?4), malloc'd; NULL when it is NULL or there is no row. */
static char *sql_text(pic_store *s, const char *sql, const char *a, const char *b, const char *c, int64_t i) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    for (int k = 1; k <= sqlite3_bind_parameter_count(q); k++) {
        if (k == 4) {
            sqlite3_bind_int64(q, k, i);
        } else {
            bind_opt_text(q, k, k == 1 ? a : k == 2 ? b : c);
        }
    }
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = dup_str((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

static int64_t sql_int(pic_store *s, const char *sql, const char *a, const char *b, int64_t i, int64_t j) {
    sqlite3_stmt *q = NULL;
    int64_t out = 0;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    for (int k = 1; k <= sqlite3_bind_parameter_count(q); k++) {
        if (k == 3 || k == 4) {
            sqlite3_bind_int64(q, k, k == 3 ? i : j);
        } else {
            bind_opt_text(q, k, k == 1 ? a : b);
        }
    }
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

static void fire_init(pic_hook_fire *f, const char *event, const char *session, int64_t submission, int64_t ref) {
    memset(f, 0, sizeof *f);
    f->event = event;
    (void)snprintf(f->session, sizeof f->session, "%s", session ? session : "");
    f->submission = submission;
    f->ref = ref;
}

/* One-name list for a matcher. */
#define NAMES(name) ((const char *const[]){(name), NULL})

static void session_of(pic_store *s, int64_t submission, char out[64]) {
    char *id = sql_text(s, "SELECT session_id FROM pic_submission WHERE id = ?4", NULL, NULL, NULL, submission);
    (void)snprintf(out, 64, "%s", id ? id : "");
    free(id);
}

/* ---- the firings ----------------------------------------------------------------- */

/* Whether owner ?1 has conversation ?2 open: a SessionStart since its last
 * SessionEnd. */
#define OPEN_SQL                                                                                                   \
    "EXISTS (SELECT 1 FROM pic_hook_run o WHERE o.event = 'SessionStart' AND o.owner = ?1 AND o.session_id = ?2" \
    " AND o.id > coalesce((SELECT max(x.id) FROM pic_hook_run x WHERE x.event = 'SessionEnd' AND x.owner = ?1"    \
    " AND x.session_id = ?2), 0))"

int pic_hooks_session_start(pic_store *s, const char *session, const char *source) {
    pic_hook_fire f;
    char *extra;
    int rc;
    if (!s->hooks || sql_int(s, "SELECT " OPEN_SQL, s->hooks->owner, session, 0, 0) != 0) {
        return 0;
    }
    fire_init(&f, "SessionStart", session, 0, 0);
    f.marker = 1;
    extra = sql_text(s, "SELECT json_object('source', ?1)", source, NULL, NULL, 0);
    rc = extra ? pic_hook_fire_run(s, &f, NAMES(source), extra) : -1;
    free(extra);
    pic_hook_fire_free(&f);
    return rc;
}

int pic_hooks_prompt(pic_store *s, const char *session, const char *prompt, int64_t *first) {
    pic_hook_fire f;
    char *extra;
    int rc;
    *first = 0;
    if (!s->hooks || !pic_hooks_has(s->hooks, "UserPromptSubmit")) {
        return 0;
    }
    fire_init(&f, "UserPromptSubmit", session, 0, 0);
    extra = sql_text(s, "SELECT json_object('prompt', ?1)", prompt, NULL, NULL, 0);
    rc = extra ? pic_hook_fire_run(s, &f, NULL, extra) : -1;
    free(extra);
    *first = f.first;
    if (rc == 0 && pic_interrupted) {
        (void)snprintf(s->err, sizeof s->err, "interrupted");
        rc = 1;
    } else if (rc == 0 && f.blocked) { /* the prompt is never admitted, so its context is never claimed */
        (void)snprintf(s->err, sizeof s->err, "prompt blocked by a UserPromptSubmit hook: %s", f.reason);
        rc = 1;
    }
    pic_hook_fire_free(&f);
    return rc;
}

int pic_hooks_session_end(pic_store *s, const char *session, const char *reason) {
    pic_hook_fire f;
    char *extra;
    int rc;
    if (!s->hooks || sql_int(s, "SELECT " OPEN_SQL, s->hooks->owner, session, 0, 0) != 1) {
        return 0;
    }
    fire_init(&f, "SessionEnd", session, 0, 0);
    f.marker = 1;
    extra = sql_text(s, "SELECT json_object('reason', ?1)", reason, NULL, NULL, 0);
    rc = extra ? pic_hook_fire_run(s, &f, NAMES(reason), extra) : -1;
    free(extra);
    pic_hook_fire_free(&f);
    return rc;
}

int pic_hooks_end_owned(pic_store *s, const char *reason) {
    sqlite3_stmt *q = NULL;
    char **ids = NULL;
    size_t n = 0;
    int rc = 0;
    if (!s->hooks) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT session_id FROM pic_hook_run r WHERE event = 'SessionStart' AND owner = ?1"
                           " AND EXISTS (SELECT 1 FROM pic_session WHERE id = r.session_id)"
                           " GROUP BY session_id ORDER BY min(id)",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_text(q, 1, s->hooks->owner, -1, SQLITE_STATIC);
    while (sqlite3_step(q) == SQLITE_ROW) {
        char **grown = realloc(ids, (n + 1) * sizeof *grown);
        if (!grown) {
            break;
        }
        ids = grown;
        if ((ids[n] = dup_str((const char *)sqlite3_column_text(q, 0)))) {
            n++;
        }
    }
    sqlite3_finalize(q);
    for (size_t i = 0; i < n; i++) {
        if (rc == 0) {
            rc = pic_hooks_session_end(s, ids[i], reason);
        }
        free(ids[i]);
    }
    free(ids);
    return rc;
}

static const char *const cc_names[][2] = {{"bash", "Bash"}, {"read", "Read"}, {"edit", "Edit"}, {"write", "Write"},
                                          {"grep", "Grep"}, {"find", "Glob"},  {"ls", "LS"}};

void pic_hooks_tool_names(const char *tool, const char *names[4]) {
    size_t n = 0;
    names[n++] = tool;
    if ((names[n] = pic_hooks_cc_name(tool)) != NULL) {
        n++;
    }
    if (is(tool, "edit")) { /* pic's edit takes several edits: Claude Code's MultiEdit too */
        names[n++] = "MultiEdit";
    }
    names[n] = NULL;
}

const char *pic_hooks_cc_name(const char *tool) {
    for (size_t i = 0; i < sizeof cc_names / sizeof cc_names[0]; i++) {
        if (is(cc_names[i][0], tool)) {
            return cc_names[i][1];
        }
    }
    return NULL;
}

char *pic_hooks_tool_extra(pic_store *s, const char *tool, const char *input, const char *call_id, const char *result,
                           int is_error) {
    sqlite3_stmt *q = NULL;
    const char *cc = pic_hooks_cc_name(tool);
    char *out = NULL;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_object('tool_name', ?1, 'tool_input', json(CASE WHEN ?5 AND json_type(?2) = 'object'"
            "   AND json_type(?2,'$.path') = 'text' THEN json_set(?2,'$.file_path',json_extract(?2,'$.path')) ELSE ?2 END),"
            " 'tool_use_id', ?3),"
            " CASE WHEN ?4 IS NOT NULL THEN json_object('content', ?4, 'is_error', json(CASE WHEN ?6 THEN 'true' ELSE 'false' END)) END",
            -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, cc ? cc : tool, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, input && *input ? input : "null", -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, call_id, -1, SQLITE_STATIC);
    bind_opt_text(q, 4, result);
    sqlite3_bind_int(q, 5, is(tool, "read") || is(tool, "edit") || is(tool, "write"));
    sqlite3_bind_int(q, 6, is_error);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *base = (const char *)sqlite3_column_text(q, 0), *response = (const char *)sqlite3_column_text(q, 1);
        out = response ? fmt("%.*s,\"tool_response\":%s}", (int)(strlen(base) - 1), base, response) : dup_str(base);
    }
    sqlite3_finalize(q);
    return out;
}

int pic_hooks_post_tools(pic_store *s, int64_t submission) {
    sqlite3_stmt *q = NULL;
    struct call {
        int64_t effect;
        char *tool, *input, *call_id, *result;
        int is_error;
    } *calls = NULL;
    size_t n = 0;
    int rc = 0;
    char session[64];
    if (!s->hooks || !pic_hooks_has(s->hooks, "PostToolUse")) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT f.id, f.tool, f.input, f.call_id, f.result, f.is_error FROM pic_effect f"
                           " WHERE f.entry_seq = (SELECT max(seq) FROM pic_entry WHERE submission_id = ?1 AND kind = 'assistant')"
                           " AND f.state = 'done'"
                           " AND NOT EXISTS (SELECT 1 FROM pic_hook_run r WHERE r.event = 'PostToolUse' AND r.ref = f.id)"
                           " ORDER BY f.ordinal",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    while (sqlite3_step(q) == SQLITE_ROW) {
        struct call *grown = realloc(calls, (n + 1) * sizeof *grown);
        if (!grown) {
            break;
        }
        calls = grown;
        calls[n].effect = sqlite3_column_int64(q, 0);
        calls[n].tool = dup_str((const char *)sqlite3_column_text(q, 1));
        calls[n].input = dup_str((const char *)sqlite3_column_text(q, 2));
        calls[n].call_id = dup_str((const char *)sqlite3_column_text(q, 3));
        calls[n].result = dup_str(sqlite3_column_text(q, 4) ? (const char *)sqlite3_column_text(q, 4) : "");
        calls[n].is_error = sqlite3_column_int(q, 5);
        n++;
    }
    sqlite3_finalize(q);
    session_of(s, submission, session);
    for (size_t i = 0; i < n; i++) {
        struct call *c = &calls[i];
        if (rc == 0 && c->tool && c->input && c->call_id && c->result) {
            pic_hook_fire f;
            char *extra = pic_hooks_tool_extra(s, c->tool, c->input, c->call_id, c->result, c->is_error);
            const char *names[4];
            pic_hooks_tool_names(c->tool, names);
            fire_init(&f, "PostToolUse", session, submission, c->effect);
            rc = extra ? pic_hook_fire_run(s, &f, names, extra) : -1;
            free(extra);
            pic_hook_fire_free(&f);
        }
        free(c->tool);
        free(c->input);
        free(c->call_id);
        free(c->result);
    }
    free(calls);
    return rc;
}

int pic_hooks_compact_start(pic_store *s, int64_t submission) {
    pic_hook_fire f;
    int64_t seq;
    char session[64];
    int rc;
    if (!s->hooks || !pic_hooks_has(s->hooks, "SessionStart")) {
        return 0;
    }
    seq = sql_int(s,
                  "SELECT coalesce(max(seq), 0) FROM pic_entry WHERE submission_id = ?3 AND kind = 'compaction' AND seq >"
                  " coalesce((SELECT max(seq) FROM pic_entry WHERE submission_id = ?3 AND kind IN ('assistant','answer')), 0)"
                  " AND NOT EXISTS (SELECT 1 FROM pic_hook_run r WHERE r.event = 'SessionStart' AND r.ref = pic_entry.seq"
                  "   AND r.submission_id = ?3)",
                  NULL, NULL, submission, 0);
    if (seq <= 0) {
        return seq < 0 ? sql_fail(s) : 0;
    }
    session_of(s, submission, session);
    fire_init(&f, "SessionStart", session, submission, seq);
    f.marker = 1;
    rc = pic_hook_fire_run(s, &f, NAMES("compact"), "{\"source\":\"compact\"}");
    pic_hook_fire_free(&f);
    return rc;
}

int pic_hooks_pre_compact(pic_store *s, int64_t submission, int64_t turn, const char *trigger, const char *instructions,
                          char **extra) {
    pic_hook_fire f;
    char session[64], *fields;
    int rc;
    *extra = NULL;
    if (sql_int(s, "SELECT count(*) FROM pic_hook_run WHERE event = 'PreCompact' AND submission_id = ?3 AND ref = ?4", NULL, NULL,
                submission, turn) > 0) {
        {
            sqlite3_stmt *q = NULL;
            if (sqlite3_prepare_v2(s->db,
                                   "SELECT group_concat(context, char(10) || char(10)) FROM (SELECT context FROM pic_hook_run"
                                   " WHERE event = 'PreCompact' AND submission_id = ?1 AND ref = ?2 AND context IS NOT NULL ORDER BY id)",
                                   -1, &q, NULL) != SQLITE_OK) {
                return sql_fail(s);
            }
            sqlite3_bind_int64(q, 1, submission);
            sqlite3_bind_int64(q, 2, turn);
            if (sqlite3_step(q) == SQLITE_ROW) {
                *extra = dup_str((const char *)sqlite3_column_text(q, 0));
            }
            sqlite3_finalize(q);
        }
        return 0;
    }
    if (!s->hooks || !pic_hooks_has(s->hooks, "PreCompact")) {
        return 0;
    }
    session_of(s, submission, session);
    fire_init(&f, "PreCompact", session, submission, turn);
    f.marker = 1;
    fields = sql_text(s, "SELECT json_object('trigger', ?1, 'custom_instructions', coalesce(?2, ''))", trigger, instructions, NULL, 0);
    rc = fields ? pic_hook_fire_run(s, &f, NAMES(trigger), fields) : -1;
    free(fields);
    if (rc == 0) {
        for (size_t i = 0; i < f.n; i++) {
            if (f.runs[i].context) {
                char *joined = *extra ? fmt("%s\n\n%s", *extra, f.runs[i].context) : dup_str(f.runs[i].context);
                free(*extra);
                *extra = joined;
            }
        }
    }
    pic_hook_fire_free(&f);
    return rc;
}

char *pic_hooks_stop_feedback(const char *reason) { return fmt("Stop hook feedback:\n%s", reason); }

int pic_hooks_deliver(pic_store *s, int64_t submission) {
    sqlite3_stmt *q = NULL;
    struct pending {
        int64_t id;
        char *body;
    } *rows = NULL;
    size_t n = 0;
    int rc = 0, step;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT id, event, context, CASE WHEN outcome = 'block' THEN reason END FROM pic_hook_run"
                           " WHERE entry_seq IS NULL AND state = 'done'"
                           " AND (context IS NOT NULL OR (event = 'PostToolUse' AND outcome = 'block'))"
                           " AND (submission_id = ?1 AND event IN ('UserPromptSubmit','PostToolUse')"
                           "   OR event = 'SessionStart' AND session_id = (SELECT session_id FROM pic_submission WHERE id = ?1))"
                           " ORDER BY id",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *event = (const char *)sqlite3_column_text(q, 1), *context = (const char *)sqlite3_column_text(q, 2);
        const char *feedback = (const char *)sqlite3_column_text(q, 3);
        struct pending *grown = realloc(rows, (n + 1) * sizeof *grown);
        if (!grown) {
            rc = -1;
            break;
        }
        rows = grown;
        rows[n].id = sqlite3_column_int64(q, 0);
        rows[n].body = fmt("<system-reminder>\n%s%s%s%s%s%s\n</system-reminder>", context ? event : "",
                           context ? " hook additional context: " : "", context ? context : "",
                           context && feedback ? "\n" : "", feedback ? "PostToolUse hook feedback:\n" : "",
                           feedback ? feedback : "");
        if (!rows[n].body) {
            rc = -1;
            break;
        }
        n++;
    }
    sqlite3_finalize(q);
    if (rc == 0 && step != SQLITE_DONE) {
        rc = sql_fail(s);
    } else if (rc != 0) {
        (void)snprintf(s->err, sizeof s->err, "out of memory");
    }
    for (size_t i = 0; i < n; i++) {
        if (rc == 0) {
            sqlite3_stmt *ins = NULL, *up = NULL;
            if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_entry(submission_id, kind, body) VALUES(?1, 'hook', ?2)", -1, &ins, NULL) !=
                    SQLITE_OK ||
                sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET entry_seq = ?1 WHERE id = ?2", -1, &up, NULL) != SQLITE_OK) {
                rc = sql_fail(s);
            } else {
                sqlite3_bind_int64(ins, 1, submission);
                sqlite3_bind_text(ins, 2, rows[i].body, -1, SQLITE_STATIC);
                if (sqlite3_step(ins) != SQLITE_DONE) {
                    rc = sql_fail(s);
                } else {
                    sqlite3_bind_int64(up, 1, sqlite3_last_insert_rowid(s->db));
                    sqlite3_bind_int64(up, 2, rows[i].id);
                    if (sqlite3_step(up) != SQLITE_DONE) {
                        rc = sql_fail(s);
                    }
                }
            }
            sqlite3_finalize(ins);
            sqlite3_finalize(up);
        }
        free(rows[i].body);
    }
    free(rows);
    return rc;
}

int pic_hooks_claim(pic_store *s, int64_t first, int64_t submission, int64_t queued) {
    sqlite3_stmt *q = NULL;
    int ok;
    if (first <= 0) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_hook_run SET submission_id = nullif(?2, 0), ref = ?3 WHERE event = 'UserPromptSubmit'"
                           " AND id >= ?1 AND submission_id IS NULL AND ref = 0",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, first);
    sqlite3_bind_int64(q, 2, submission);
    sqlite3_bind_int64(q, 3, queued);
    ok = sqlite3_step(q) == SQLITE_DONE;
    sqlite3_finalize(q);
    return ok ? 0 : sql_fail(s);
}

int pic_hooks_claim_queued(pic_store *s, int64_t queued, int64_t submission) {
    sqlite3_stmt *q = NULL;
    int ok;
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_hook_run SET submission_id = ?2 WHERE event = 'UserPromptSubmit' AND ref = ?1"
                           " AND submission_id IS NULL",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, queued);
    sqlite3_bind_int64(q, 2, submission);
    ok = sqlite3_step(q) == SQLITE_DONE;
    sqlite3_finalize(q);
    return ok ? 0 : sql_fail(s);
}