Skip to content
pi-c Artifact [7ae7cb1714]
Login

Artifact [7ae7cb1714]

Artifact 7ae7cb1714b8a254a778f8d8753394fb1f2dd25ccc5ee5943a5bfdb19ac322f3:


/* Pi v3 session JSONL into a new pic conversation (pic import, /import).
 * Preserves the full Pi session structure: user messages and images, assistant
 * neutral content arrays (text, thinking with opaque signature/redacted,
 * toolCall) with origin and stopReason, paired toolResult entries with text
 * and images, bashExecution messages, compaction and branch_summary entries,
 * custom_message (pic.instructions and extensions), session_info names,
 * per-reply usage (marked imported so calibration works without inflating pic
 * usage totals), and multi-branch parentId trees with session heads on every
 * branch leaf. Pi v1/v2 and partial or malformed lines are handled cleanly. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pic.h"
#include "platform.h"

/* Bound total input and single-line sizes so malformed streams never OOM or
 * overflow SQLite's int length arguments. */
#define IPI_MAX_INPUT (256u * 1024u * 1024u)
#define IPI_MAX_LINE (64u * 1024u * 1024u)

typedef struct {
    char *buf;
    size_t len, cap;
} ipi_buf;

static int ipi_buf_add(ipi_buf *b, const char *s, size_t n) {
    if (n > SIZE_MAX - b->len - 1) {
        return -1;
    }
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 256;
        char *grown;
        while (cap < b->len + n + 1) {
            if (cap > SIZE_MAX / 2) {
                cap = b->len + n + 1;
                break;
            }
            cap *= 2;
        }
        if (!(grown = realloc(b->buf, cap))) {
            return -1;
        }
        b->buf = grown;
        b->cap = cap;
    }
    if (n) {
        memcpy(b->buf + b->len, s, n);
    }
    b->len += n;
    b->buf[b->len] = '\0';
    return 0;
}

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

static int ipi_oom(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "out of memory");
    return -1;
}

/* A statement with text (t) and integer (i) parameters; NULL text binds null.
 * When ROW is non-NULL, column 0 (when non-null) is strdup'd into *ROW. */
static int ipi_run(pic_store *s, const char *sql, const char *fmt, char **row, ...) {
    sqlite3_stmt *q = NULL;
    va_list ap;
    int rc;
    if (row) {
        *row = NULL;
    }
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return ipi_sql_fail(s);
    }
    va_start(ap, row);
    for (int i = 1; *fmt; fmt++, i++) {
        if (*fmt == 't') {
            const char *t = va_arg(ap, const char *);
            if (t) {
                sqlite3_bind_text(q, i, t, -1, SQLITE_STATIC);
            }
        } else {
            sqlite3_bind_int64(q, i, va_arg(ap, sqlite3_int64));
        }
    }
    va_end(ap);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW && row) {
        const char *t = (const char *)sqlite3_column_text(q, 0);
        if (t) {
            *row = strdup(t);
            if (!*row) {
                sqlite3_finalize(q);
                return ipi_oom(s);
            }
        }
    }
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
        return ipi_sql_fail(s);
    }
    return 0;
}

static const char ipi_tables_sql[] =
    "CREATE TEMP TABLE ipi_raw("
    "  n INTEGER PRIMARY KEY,"
    "  file_idx INTEGER NOT NULL,"
    "  id TEXT NOT NULL,"
    "  parent_id TEXT,"
    "  type TEXT NOT NULL,"
    "  role TEXT,"
    "  line TEXT NOT NULL);"
    "CREATE INDEX temp.ipi_raw_id ON ipi_raw(id);"
    "CREATE INDEX temp.ipi_raw_parent ON ipi_raw(parent_id);"
    "CREATE TEMP TABLE ipi_map("
    "  id TEXT PRIMARY KEY,"
    "  seq INTEGER NOT NULL,"
    "  child_seq INTEGER NOT NULL,"
    "  sub INTEGER NOT NULL,"
    "  direct INTEGER NOT NULL);"
    "CREATE TEMP TABLE ipi_sub("
    "  id INTEGER PRIMARY KEY,"
    "  tip_seq INTEGER NOT NULL,"
    "  answered INTEGER NOT NULL DEFAULT 0,"
    "  is_bash INTEGER NOT NULL DEFAULT 0,"
    "  reply_turn INTEGER NOT NULL DEFAULT 0,"
    "  compact_turn INTEGER NOT NULL DEFAULT 0,"
    "  branch_turn INTEGER NOT NULL DEFAULT 0);"
    "CREATE TEMP TABLE ipi_handled(n INTEGER PRIMARY KEY);";

static void ipi_drop_tables(pic_store *s) {
    (void)sqlite3_exec(s->db,
                       "DROP TABLE IF EXISTS temp.ipi_raw; DROP TABLE IF EXISTS temp.ipi_map;"
                       " DROP TABLE IF EXISTS temp.ipi_sub; DROP TABLE IF EXISTS temp.ipi_handled;",
                       NULL, NULL, NULL);
}

typedef struct {
    pic_store *s;
    char session[16];
    long long now_ns;
    sqlite3_int64 now_ms;
    sqlite3_int64 last_seq;
    long turns;
    int is_v1;
    char *name;
} ipi_ctx;

typedef struct {
    sqlite3_int64 n;
    char *id;
    char *parent_id;
    char *type;
    char *role;
} ipi_row;

typedef struct {
    char *id;
    char *name;
    char *args;
    sqlite3_int64 tr_n;
    char *tr_id;
    char *tr_line;
    int tr_is_error;
    int matched;
    sqlite3_int64 rseq;
} ipi_call;

typedef struct {
    sqlite3_int64 n;
    char *id;
    sqlite3_int64 rseq;
} ipi_tr_seen;

static void ipi_free_rows(ipi_row *rows, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(rows[i].id);
        free(rows[i].parent_id);
        free(rows[i].type);
        free(rows[i].role);
    }
    free(rows);
}

static void ipi_free_calls(ipi_call *calls, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(calls[i].id);
        free(calls[i].name);
        free(calls[i].args);
        free(calls[i].tr_id);
        free(calls[i].tr_line);
    }
    free(calls);
}

/* Parse lines of INPUT into temp.ipi_raw before taking the journal write lock. */
static int ipi_load(ipi_ctx *c, const ipi_buf *input) {
    sqlite3_stmt *inspect = NULL, *add = NULL;
    char *prev_id = NULL;
    size_t at = 0;
    sqlite3_int64 seq_n = 0, file_idx = 0;
    int rc = -1;
    if (sqlite3_prepare_v2(
            c->s->db,
            "SELECT"
            " CASE WHEN json_type(?1, '$.type') = 'text' THEN json_extract(?1, '$.type') END,"
            " CASE WHEN json_type(?1, '$.id') = 'text' AND json_extract(?1, '$.id') != '' THEN json_extract(?1, '$.id') END,"
            " CASE WHEN json_type(?1, '$.parentId') = 'text' AND json_extract(?1, '$.parentId') != '' THEN json_extract(?1, '$.parentId') END,"
            " json_type(?1, '$.parentId') = 'null',"
            " CASE WHEN json_type(?1, '$.message') = 'object' AND json_type(?1, '$.message.role') = 'text'"
            "   THEN json_extract(?1, '$.message.role') END,"
            " CASE WHEN json_type(?1, '$.name') = 'text' THEN json_extract(?1, '$.name') END,"
            " CASE WHEN json_type(?1, '$.version') = 'integer' THEN json_extract(?1, '$.version') END"
            " WHERE json_valid(?1) AND json_type(?1) = 'object'",
            -1, &inspect, NULL) != SQLITE_OK ||
        sqlite3_prepare_v2(
            c->s->db,
            "INSERT INTO ipi_raw(n, file_idx, id, parent_id, type, role, line) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            -1, &add, NULL) != SQLITE_OK) {
        ipi_sql_fail(c->s);
        goto out;
    }
    while (at < input->len) {
        const char *start = input->buf + at;
        const char *nl = memchr(start, '\n', input->len - at);
        size_t raw_len = nl ? (size_t)(nl - start) + 1 : input->len - at;
        size_t len = raw_len;
        at += raw_len;
        while (len > 0 && (start[len - 1] == '\n' || start[len - 1] == '\r')) {
            len--;
        }
        if (len == 0 || len > IPI_MAX_LINE || memchr(start, '\0', len) != NULL) {
            continue;
        }
        sqlite3_reset(inspect);
        sqlite3_clear_bindings(inspect);
        sqlite3_bind_text(inspect, 1, start, (int)len, SQLITE_STATIC);
        if (sqlite3_step(inspect) != SQLITE_ROW) {
            continue;
        }
        const char *type = (const char *)sqlite3_column_text(inspect, 0);
        if (!type || !*type) {
            continue;
        }
        if (strcmp(type, "session") == 0) {
            if (sqlite3_column_type(inspect, 6) == SQLITE_NULL || sqlite3_column_int64(inspect, 6) < 2) {
                c->is_v1 = 1;
            }
            file_idx++;
            continue;
        }
        if (strcmp(type, "session_info") == 0) {
            const char *raw_name = (const char *)sqlite3_column_text(inspect, 5);
            if (raw_name) {
                char *nm = strdup(raw_name);
                if (!nm) {
                    ipi_oom(c->s);
                    goto out;
                }
                free(c->name);
                c->name = nm;
            }
        }
        {
            char synth[48];
            const char *raw_id = (const char *)sqlite3_column_text(inspect, 1);
            const char *raw_parent = (const char *)sqlite3_column_text(inspect, 2);
            int null_parent = sqlite3_column_int(inspect, 3);
            const char *role = (const char *)sqlite3_column_text(inspect, 4);
            const char *id, *parent_id;
            char *id_copy = NULL, *parent_copy = NULL, *type_copy = NULL, *role_copy = NULL;
            seq_n++;
            if (raw_id) {
                id = raw_id;
                parent_id = raw_parent ? raw_parent : (null_parent || !c->is_v1 ? NULL : prev_id);
            } else {
                (void)snprintf(synth, sizeof synth, "#%lld", (long long)seq_n);
                id = synth;
                parent_id = raw_parent ? raw_parent : (null_parent ? NULL : prev_id);
            }
            id_copy = strdup(id);
            type_copy = strdup(type);
            if (parent_id) {
                parent_copy = strdup(parent_id);
            }
            if (role) {
                role_copy = strdup(role);
            }
            sqlite3_reset(inspect);
            if (!id_copy || !type_copy || (parent_id && !parent_copy) || (role && !role_copy)) {
                free(id_copy);
                free(parent_copy);
                free(type_copy);
                free(role_copy);
                ipi_oom(c->s);
                goto out;
            }
            sqlite3_reset(add);
            sqlite3_clear_bindings(add);
            sqlite3_bind_int64(add, 1, seq_n);
            sqlite3_bind_int64(add, 2, file_idx);
            sqlite3_bind_text(add, 3, id_copy, -1, SQLITE_STATIC);
            if (parent_copy) {
                sqlite3_bind_text(add, 4, parent_copy, -1, SQLITE_STATIC);
            }
            sqlite3_bind_text(add, 5, type_copy, -1, SQLITE_STATIC);
            if (role_copy) {
                sqlite3_bind_text(add, 6, role_copy, -1, SQLITE_STATIC);
            }
            sqlite3_bind_text(add, 7, start, (int)len, SQLITE_STATIC);
            if (sqlite3_step(add) != SQLITE_DONE) {
                free(id_copy);
                free(parent_copy);
                free(type_copy);
                free(role_copy);
                ipi_sql_fail(c->s);
                goto out;
            }
            free(prev_id);
            prev_id = id_copy;
            free(parent_copy);
            free(type_copy);
            free(role_copy);
            file_idx++;
        }
    }
    rc = 0;
out:
    sqlite3_finalize(inspect);
    sqlite3_finalize(add);
    free(prev_id);
    return rc;
}

/* Text parts of JSON at PATH (a string, or text objects in an array joined by
 * newlines), malloc'd; "" when absent. */
static char *ipi_extract_text(pic_store *s, const char *line, const char *path) {
    char *out = NULL;
    if (ipi_run(s,
                "SELECT CASE json_type(?1, ?2)"
                " WHEN 'text' THEN json_extract(?1, ?2)"
                " WHEN 'array' THEN coalesce((SELECT group_concat(t, char(10)) FROM ("
                "   SELECT CASE WHEN x.type = 'object' AND json_extract(x.value, '$.type') = 'text'"
                "     AND json_type(x.value, '$.text') = 'text' THEN json_extract(x.value, '$.text') END AS t"
                "   FROM json_each(?1, ?2) x ORDER BY x.key) WHERE t IS NOT NULL), '')"
                " ELSE '' END",
                "tt", &out, line, path) != 0) {
        return NULL;
    }
    if (!out) {
        out = strdup("");
        if (!out) {
            ipi_oom(s);
        }
    }
    return out;
}

/* Text with a note for each image at PATH that fails its check (malloc'd), its
 * good images kept at the front of *list (*n of them). */
static char *ipi_with_images(pic_store *s, const char *base, const char *line, const char *path, pic_image **list, size_t *n,
                             unsigned char **bytes) {
    const char *error = NULL;
    char *ctype = NULL;
    size_t kept = 0;
    ipi_buf text = {NULL, 0, 0};
    *list = NULL;
    *bytes = NULL;
    *n = 0;
    if (ipi_run(s, "SELECT json_type(?1, ?2)", "tt", &ctype, line, path) != 0) {
        return NULL;
    }
    if (!ctype || strcmp(ctype, "array") != 0) {
        free(ctype);
        char *copy = strdup(base);
        if (!copy) {
            ipi_oom(s);
        }
        return copy;
    }
    free(ctype);
    if (pic_images_from_json(s->db, line, path, 0, list, n, bytes, &error) != 0) {
        *n = 0;
        if (ipi_buf_add(&text, base, strlen(base)) != 0 ||
            ipi_buf_add(&text, "\n\n" PIC_IMAGE_UNCONVERTIBLE, 2 + strlen(PIC_IMAGE_UNCONVERTIBLE)) != 0) {
            free(text.buf);
            ipi_oom(s);
            return NULL;
        }
        return text.buf;
    }
    if (ipi_buf_add(&text, base, strlen(base)) != 0) {
        free(text.buf);
        free(*list);
        free(*bytes);
        *list = NULL;
        *bytes = NULL;
        *n = 0;
        ipi_oom(s);
        return NULL;
    }
    for (size_t i = 0, noted = 0; i < *n; i++) {
        int rc = pic_image_check(&(*list)[i], (*list)[i].mime, NULL, 0);
        if (rc == PIC_IMAGE_OK) {
            (*list)[kept++] = (*list)[i];
        } else if (ipi_buf_add(&text, "\n\n", noted++ ? 1 : 2) != 0 ||
                   ipi_buf_add(&text, pic_image_note(rc), strlen(pic_image_note(rc))) != 0) {
            free(text.buf);
            free(*list);
            free(*bytes);
            *list = NULL;
            *bytes = NULL;
            *n = 0;
            ipi_oom(s);
            return NULL;
        }
    }
    *n = kept;
    return text.buf;
}

/* Imported usage JSON (marked "imported":true, no pic_cost), or NULL when the
 * entry has no usable token counts at PATH. */
static int ipi_parse_usage(pic_store *s, const char *line, const char *path, const char *model, char **out) {
#define IPI_UFIELD(a, b)                                                                                                  \
    "CASE WHEN json_type(u, '$." a "') = 'integer' AND json_extract(u, '$." a "') >= 0 THEN json_extract(u, '$." a "')"  \
    " WHEN json_type(u, '$." b "') = 'integer' AND json_extract(u, '$." b "') >= 0 THEN json_extract(u, '$." b "') END"
    return ipi_run(
        s,
        "WITH raw(u) AS (SELECT CASE WHEN json_type(?1, ?2) = 'object' THEN json_extract(?1, ?2) END),"
        " vals(i, r, w, o) AS (SELECT " IPI_UFIELD("input", "input_tokens") ", "
        IPI_UFIELD("cacheRead", "cache_read_input_tokens") ", " IPI_UFIELD("cacheWrite", "cache_creation_input_tokens") ", "
        IPI_UFIELD("output", "output_tokens") " FROM raw WHERE u IS NOT NULL)"
        " SELECT json_patch('{}', json_object('input_tokens', i, 'cache_read_input_tokens', r,"
        "   'cache_creation_input_tokens', w, 'output_tokens', o, 'model', nullif(?3, 'unknown'), 'imported', json('true')))"
        " FROM vals WHERE i IS NOT NULL OR r IS NOT NULL OR w IS NOT NULL OR o IS NOT NULL",
        "ttt", out, line, path, model ? model : "unknown");
#undef IPI_UFIELD
}

static int ipi_map_put(pic_store *s, const char *id, sqlite3_int64 seq, sqlite3_int64 child_seq, sqlite3_int64 sub,
                       int direct) {
    return ipi_run(s, "INSERT OR REPLACE INTO ipi_map(id, seq, child_seq, sub, direct) VALUES(?1, ?2, ?3, ?4, ?5)", "tiiii",
                   NULL, id, seq, child_seq, sub, (sqlite3_int64)direct);
}

static int ipi_map_get(pic_store *s, const char *id, sqlite3_int64 *seq, sqlite3_int64 *child_seq, sqlite3_int64 *sub,
                       int *direct) {
    sqlite3_stmt *q = NULL;
    int found = 0;
    if (seq) {
        *seq = 0;
    }
    if (child_seq) {
        *child_seq = 0;
    }
    if (sub) {
        *sub = 0;
    }
    if (direct) {
        *direct = 0;
    }
    if (!id) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT seq, child_seq, sub, direct FROM ipi_map WHERE id = ?1", -1, &q, NULL) !=
        SQLITE_OK) {
        return ipi_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        found = 1;
        if (seq) {
            *seq = sqlite3_column_int64(q, 0);
        }
        if (child_seq) {
            *child_seq = sqlite3_column_int64(q, 1);
        }
        if (sub) {
            *sub = sqlite3_column_int64(q, 2);
        }
        if (direct) {
            *direct = sqlite3_column_int(q, 3);
        }
    }
    sqlite3_finalize(q);
    return found;
}

static int ipi_sub_state(pic_store *s, sqlite3_int64 sub, sqlite3_int64 *tip_seq, int *answered, int *is_bash) {
    sqlite3_stmt *q = NULL;
    int found = 0;
    *tip_seq = 0;
    *answered = 0;
    *is_bash = 0;
    if (sub <= 0) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT tip_seq, answered, is_bash FROM ipi_sub WHERE id = ?1", -1, &q, NULL) !=
        SQLITE_OK) {
        return ipi_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, sub);
    if (sqlite3_step(q) == SQLITE_ROW) {
        found = 1;
        *tip_seq = sqlite3_column_int64(q, 0);
        *answered = sqlite3_column_int(q, 1);
        *is_bash = sqlite3_column_int(q, 2);
    }
    sqlite3_finalize(q);
    return found;
}

static int ipi_sub_next_turn(pic_store *s, sqlite3_int64 sub, const char *col, sqlite3_int64 *turn_out) {
    char sql[160];
    char *val = NULL;
    (void)snprintf(sql, sizeof sql, "UPDATE ipi_sub SET %s = %s + 1 WHERE id = ?1 RETURNING %s", col, col, col);
    if (ipi_run(s, sql, "i", &val, sub) != 0 || !val) {
        free(val);
        return -1;
    }
    *turn_out = strtoll(val, NULL, 10);
    free(val);
    return 0;
}

/* Insert a user entry as a new submission. If PARENT_SEQ == 0, clears the
 * session head first so pic_entry_link leaves parent_seq NULL. */
static int ipi_insert_user_sub(ipi_ctx *c, const char *body, const pic_image *images, size_t nimages,
                               sqlite3_int64 parent_seq, sqlite3_int64 *sub_out, sqlite3_int64 *seq_out) {
    char key[96];
    sqlite3_int64 sub, seq;
    (void)snprintf(key, sizeof key, "import-%s-%lld-%ld", c->session, c->now_ns, c->turns);
    if (ipi_run(c->s, "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES(?1, ?2, 'admitted', ?3)",
                "ttt", NULL, key, body, c->session) != 0) {
        return -1;
    }
    sub = sqlite3_last_insert_rowid(c->s->db);
    if (parent_seq == 0 && ipi_run(c->s, "UPDATE pic_session SET head_seq = NULL WHERE id = ?1", "t", NULL, c->session) != 0) {
        return -1;
    }
    if (parent_seq > 0) {
        if (ipi_run(c->s,
                    "INSERT INTO pic_entry(submission_id, kind, body, parent_seq, created_ms) VALUES(?1, 'user', ?2, ?3, ?4)",
                    "itii", NULL, sub, body, parent_seq, c->now_ms) != 0) {
            return -1;
        }
    } else {
        if (ipi_run(c->s, "INSERT INTO pic_entry(submission_id, kind, body, created_ms) VALUES(?1, 'user', ?2, ?3)", "iti",
                    NULL, sub, body, c->now_ms) != 0) {
            return -1;
        }
    }
    seq = sqlite3_last_insert_rowid(c->s->db);
    if (pic_attach_images(c->s, seq, 0, images, nimages) != 0 ||
        ipi_run(c->s, "INSERT INTO ipi_sub(id, tip_seq, answered, is_bash) VALUES(?1, ?2, 0, 0)", "ii", NULL, sub, seq) != 0) {
        return -1;
    }
    c->turns++;
    c->last_seq = seq;
    *sub_out = sub;
    *seq_out = seq;
    return 0;
}

static int ipi_handle_user(ipi_ctx *c, const ipi_row *r, const char *line, const char *path, sqlite3_int64 parent_seq) {
    char *raw = ipi_extract_text(c->s, line, path), *body = NULL;
    pic_image *images = NULL;
    unsigned char *bytes = NULL;
    size_t nimages = 0;
    sqlite3_int64 sub = 0, seq = 0;
    int rc = -1;
    if (!raw) {
        return -1;
    }
    body = ipi_with_images(c->s, raw, line, path, &images, &nimages, &bytes);
    free(raw);
    if (!body) {
        return -1;
    }
    rc = ipi_insert_user_sub(c, body, images, nimages, parent_seq, &sub, &seq);
    free(body);
    free(images);
    free(bytes);
    if (rc != 0) {
        return -1;
    }
    return ipi_map_put(c->s, r->id, seq, seq, sub, 1);
}

static int ipi_handle_bash(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 parent_seq) {
    sqlite3_stmt *q = NULL;
    pic_bash_msg bm;
    char *cmd = NULL, *out = NULL, *body = NULL;
    char key[96];
    sqlite3_int64 sub = 0, seq = 0;
    int rc = -1;
    memset(&bm, 0, sizeof bm);
    if (sqlite3_prepare_v2(
            c->s->db,
            "SELECT"
            " coalesce(CASE WHEN json_type(?1,'$.message.command')='text' THEN json_extract(?1,'$.message.command') END, ''),"
            " coalesce(CASE WHEN json_type(?1,'$.message.output')='text' THEN json_extract(?1,'$.message.output') END, ''),"
            " json_type(?1,'$.message.exitCode') = 'integer',"
            " coalesce(CASE WHEN json_type(?1,'$.message.exitCode')='integer' THEN json_extract(?1,'$.message.exitCode') END, 0),"
            " json_type(?1,'$.message.cancelled')='true' OR json_extract(?1,'$.message.cancelled')=1,"
            " json_type(?1,'$.message.truncated')='true' OR json_extract(?1,'$.message.truncated')=1,"
            " json_type(?1,'$.message.excludeFromContext')='true' OR json_extract(?1,'$.message.excludeFromContext')=1",
            -1, &q, NULL) != SQLITE_OK) {
        return ipi_sql_fail(c->s);
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *t0 = (const char *)sqlite3_column_text(q, 0);
        const char *t1 = (const char *)sqlite3_column_text(q, 1);
        cmd = t0 ? strdup(t0) : NULL;
        out = t1 ? strdup(t1) : NULL;
        bm.has_exit = sqlite3_column_int(q, 2);
        bm.exit_code = sqlite3_column_int(q, 3);
        bm.cancelled = sqlite3_column_int(q, 4) != 0;
        bm.truncated = sqlite3_column_int(q, 5) != 0;
        bm.exclude = sqlite3_column_int(q, 6) != 0;
    }
    sqlite3_finalize(q);
    if (!cmd || !out) {
        free(cmd);
        free(out);
        return ipi_oom(c->s);
    }
    bm.command = cmd;
    bm.output = out;
    if (!(body = pic_bash_text(&bm))) {
        free(cmd);
        free(out);
        return ipi_oom(c->s);
    }
    (void)snprintf(key, sizeof key, "import-%s-%lld-%ld", c->session, c->now_ns, c->turns);
    if (ipi_run(c->s, "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES(?1, ?2, 'answered', ?3)",
                "ttt", NULL, key, body, c->session) != 0) {
        goto out;
    }
    sub = sqlite3_last_insert_rowid(c->s->db);
    if (parent_seq == 0 && ipi_run(c->s, "UPDATE pic_session SET head_seq = NULL WHERE id = ?1", "t", NULL, c->session) != 0) {
        goto out;
    }
    if (parent_seq > 0) {
        rc = ipi_run(c->s,
                     "INSERT INTO pic_entry(submission_id, kind, body, parent_seq, created_ms) VALUES(?1, 'user', ?2, ?3, ?4)",
                     "itii", NULL, sub, body, parent_seq, c->now_ms);
    } else {
        rc = ipi_run(c->s, "INSERT INTO pic_entry(submission_id, kind, body, created_ms) VALUES(?1, 'user', ?2, ?3)", "iti",
                     NULL, sub, body, c->now_ms);
    }
    if (rc != 0) {
        goto out;
    }
    seq = sqlite3_last_insert_rowid(c->s->db);
    {
        sqlite3_stmt *bq = NULL;
        if (sqlite3_prepare_v2(
                c->s->db,
                "INSERT INTO pic_bash(entry_seq, command, output, exit_code, cancelled, truncated, exclude)"
                " VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                -1, &bq, NULL) != SQLITE_OK) {
            rc = ipi_sql_fail(c->s);
            goto out;
        }
        sqlite3_bind_int64(bq, 1, seq);
        sqlite3_bind_text(bq, 2, cmd, -1, SQLITE_STATIC);
        sqlite3_bind_text(bq, 3, out, -1, SQLITE_STATIC);
        if (bm.has_exit) {
            sqlite3_bind_int(bq, 4, bm.exit_code);
        }
        sqlite3_bind_int(bq, 5, bm.cancelled);
        sqlite3_bind_int(bq, 6, bm.truncated);
        sqlite3_bind_int(bq, 7, bm.exclude);
        rc = sqlite3_step(bq) == SQLITE_DONE ? 0 : ipi_sql_fail(c->s);
        sqlite3_finalize(bq);
    }
    if (rc != 0 ||
        ipi_run(c->s, "INSERT INTO ipi_sub(id, tip_seq, answered, is_bash) VALUES(?1, ?2, 1, 1)", "ii", NULL, sub, seq) != 0) {
        rc = -1;
        goto out;
    }
    c->turns++;
    c->last_seq = seq;
    rc = ipi_map_put(c->s, r->id, seq, seq, sub, 1);
out:
    free(cmd);
    free(out);
    free(body);
    return rc;
}

/* Build pic's neutral content JSON array from a Pi assistant message, plus the
 * extracted toolCall list. Returns 0 on success (with *body_out malloc'd). */
static int ipi_build_assistant_body(pic_store *s, sqlite3_int64 row_n, const char *line, char **body_out,
                                    ipi_call **calls_out, size_t *ncalls_out) {
    sqlite3_stmt *q = NULL;
    ipi_buf body = {NULL, 0, 0};
    ipi_call *calls = NULL;
    size_t ncalls = 0, cap = 0;
    int step, rc = -1, any = 0;
    char *ctype = NULL;
    *body_out = NULL;
    *calls_out = NULL;
    *ncalls_out = 0;
    if (ipi_buf_add(&body, "[", 1) != 0) {
        ipi_oom(s);
        goto out;
    }
    if (ipi_run(s, "SELECT json_type(?1, '$.message.content')", "t", &ctype, line) != 0) {
        goto out;
    }
    if (ctype && strcmp(ctype, "text") == 0) {
        char *item = NULL;
        free(ctype);
        ctype = NULL;
        if (ipi_run(s,
                    "SELECT json_object('type','text','text',json_extract(?1,'$.message.content'))"
                    " WHERE json_extract(?1,'$.message.content') != ''",
                    "t", &item, line) != 0) {
            goto out;
        }
        if (item) {
            if (ipi_buf_add(&body, item, strlen(item)) != 0) {
                free(item);
                ipi_oom(s);
                goto out;
            }
            free(item);
        }
        if (ipi_buf_add(&body, "]", 1) != 0) {
            ipi_oom(s);
            goto out;
        }
        *body_out = body.buf;
        return 0;
    }
    if (!ctype || strcmp(ctype, "array") != 0) {
        free(ctype);
        if (ipi_buf_add(&body, "]", 1) != 0) {
            ipi_oom(s);
            goto out;
        }
        *body_out = body.buf;
        return 0;
    }
    free(ctype);
    ctype = NULL;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT"
            " CASE WHEN x.type = 'object' AND json_type(x.value, '$.type') = 'text' THEN json_extract(x.value, '$.type') END,"
            " x.value"
            " FROM json_each(?1, '$.message.content') x ORDER BY x.key",
            -1, &q, NULL) != SQLITE_OK) {
        ipi_sql_fail(s);
        goto out;
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *btype = (const char *)sqlite3_column_text(q, 0);
        const char *block = (const char *)sqlite3_column_text(q, 1);
        char *item = NULL;
        if (!btype || !block) {
            continue;
        }
        if (strcmp(btype, "text") == 0) {
            if (ipi_run(
                    s,
                    "SELECT json_patch(json_object('type','text','text',"
                    " coalesce(CASE WHEN json_type(?1,'$.text')='text' THEN json_extract(?1,'$.text') END, '')),"
                    " json_object('textSignature', CASE WHEN json_type(?1,'$.textSignature')='text'"
                    "   AND json_extract(?1,'$.textSignature') != '' THEN json_extract(?1,'$.textSignature') END))",
                    "t", &item, block) != 0) {
                goto out;
            }
        } else if (strcmp(btype, "thinking") == 0) {
            if (ipi_run(
                    s,
                    "SELECT json_patch(json_object('type','thinking','thinking',"
                    " coalesce(CASE WHEN json_type(?1,'$.thinking')='text' THEN json_extract(?1,'$.thinking') END, '')),"
                    " json_object('signature', CASE"
                    "   WHEN json_type(?1,'$.thinkingSignature')='text' AND json_extract(?1,'$.thinkingSignature') != ''"
                    "     THEN json_extract(?1,'$.thinkingSignature')"
                    "   WHEN json_type(?1,'$.signature')='text' AND json_extract(?1,'$.signature') != ''"
                    "     THEN json_extract(?1,'$.signature') END,"
                    " 'redacted', CASE WHEN json_type(?1,'$.redacted')='true' OR json_extract(?1,'$.redacted')=1"
                    "   THEN json('true') END))",
                    "t", &item, block) != 0) {
                goto out;
            }
        } else if (strcmp(btype, "redacted_thinking") == 0) {
            if (ipi_run(
                    s,
                    "SELECT json_object('type','thinking','thinking','','signature',"
                    " coalesce(CASE WHEN json_type(?1,'$.data')='text' THEN json_extract(?1,'$.data') END, ''),"
                    " 'redacted', json('true'))",
                    "t", &item, block) != 0) {
                goto out;
            }
        } else if (strcmp(btype, "toolCall") == 0 || strcmp(btype, "tool_use") == 0) {
            char *cid = NULL, *cname = NULL, *cargs = NULL, *tsig = NULL;
            char synth_id[64];
            if (ipi_run(s,
                        "SELECT CASE WHEN json_type(?1,'$.name')='text' AND json_extract(?1,'$.name') != ''"
                        " THEN json_extract(?1,'$.name') END",
                        "t", &cname, block) != 0) {
                goto out;
            }
            if (!cname) {
                continue; /* malformed toolCall without a name */
            }
            if (ipi_run(s,
                        "SELECT CASE WHEN json_type(?1,'$.id')='text' AND json_extract(?1,'$.id') != ''"
                        " THEN json_extract(?1,'$.id') END",
                        "t", &cid, block) != 0 ||
                ipi_run(s,
                        "SELECT CASE"
                        " WHEN json_type(?1,'$.arguments')='object' THEN json_extract(?1,'$.arguments')"
                        " WHEN json_type(?1,'$.arguments')='text' AND json_valid(json_extract(?1,'$.arguments'))"
                        "   AND json_type(json_extract(?1,'$.arguments'))='object' THEN json(json_extract(?1,'$.arguments'))"
                        " WHEN json_type(?1,'$.arguments') IS NOT NULL AND json_type(?1,'$.arguments') != 'null'"
                        "   THEN json_object('pic_invalid_input', json_extract(?1,'$.arguments'))"
                        " WHEN json_type(?1,'$.input')='object' THEN json_extract(?1,'$.input')"
                        " WHEN json_type(?1,'$.input')='text' AND json_valid(json_extract(?1,'$.input'))"
                        "   AND json_type(json_extract(?1,'$.input'))='object' THEN json(json_extract(?1,'$.input'))"
                        " WHEN json_type(?1,'$.input') IS NOT NULL AND json_type(?1,'$.input') != 'null'"
                        "   THEN json_object('pic_invalid_input', json_extract(?1,'$.input'))"
                        " ELSE '{}' END",
                        "t", &cargs, block) != 0 ||
                ipi_run(s,
                        "SELECT CASE WHEN json_type(?1,'$.thoughtSignature')='text'"
                        " AND json_extract(?1,'$.thoughtSignature') != '' THEN json_extract(?1,'$.thoughtSignature') END",
                        "t", &tsig, block) != 0) {
                free(cid);
                free(cname);
                free(cargs);
                free(tsig);
                goto out;
            }
            if (!cid) {
                (void)snprintf(synth_id, sizeof synth_id, "import_call_%lld_%zu", (long long)row_n, ncalls);
                cid = strdup(synth_id);
            }
            if (!cid || !cargs) {
                free(cid);
                free(cname);
                free(cargs);
                free(tsig);
                ipi_oom(s);
                goto out;
            }
            if (ipi_run(s,
                        "SELECT json_patch(json_object('type','toolCall','id',?1,'name',?2,'arguments',json(?3)),"
                        " json_object('thoughtSignature',?4))",
                        "tttt", &item, cid, cname, cargs, tsig) != 0) {
                free(cid);
                free(cname);
                free(cargs);
                free(tsig);
                goto out;
            }
            free(tsig);
            if (ncalls == cap) {
                size_t ncap = cap ? cap * 2 : 8;
                ipi_call *grown = realloc(calls, ncap * sizeof *calls);
                if (!grown) {
                    free(cid);
                    free(cname);
                    free(cargs);
                    free(item);
                    ipi_oom(s);
                    goto out;
                }
                calls = grown;
                cap = ncap;
            }
            memset(&calls[ncalls], 0, sizeof calls[ncalls]);
            calls[ncalls].id = cid;
            calls[ncalls].name = cname;
            calls[ncalls].args = cargs;
            ncalls++;
        }
        if (item) {
            if ((any && ipi_buf_add(&body, ",", 1) != 0) || ipi_buf_add(&body, item, strlen(item)) != 0) {
                free(item);
                ipi_oom(s);
                goto out;
            }
            any = 1;
            free(item);
        }
    }
    if (step != SQLITE_DONE) {
        ipi_sql_fail(s);
        goto out;
    }
    if (ipi_buf_add(&body, "]", 1) != 0) {
        ipi_oom(s);
        goto out;
    }
    *body_out = body.buf;
    *calls_out = calls;
    *ncalls_out = ncalls;
    body.buf = NULL;
    calls = NULL;
    ncalls = 0;
    rc = 0;
out:
    sqlite3_finalize(q);
    free(ctype);
    free(body.buf);
    ipi_free_calls(calls, ncalls);
    return rc;
}

/* Reconstruct valid provider-native JSON for API from neutral BODY so same-model
 * continuations replay valid wire blocks on every bundled provider. */
static char *ipi_build_native(pic_store *s, const char *api, const char *model, const char *body) {
    char *native = NULL;
    if (strcmp(model, "unknown") != 0 && strcmp(api, "anthropic-messages") == 0) {
        if (ipi_run(
                s,
                "SELECT coalesce(json_group_array(json(y)), '[]') FROM ("
                " SELECT CASE json_extract(value,'$.type')"
                "  WHEN 'text' THEN json_object('type','text','text',json_extract(value,'$.text'))"
                "  WHEN 'thinking' THEN CASE"
                "    WHEN json_extract(value,'$.redacted') = 1 AND coalesce(json_extract(value,'$.signature'),'') != ''"
                "      THEN json_object('type','redacted_thinking','data',json_extract(value,'$.signature'))"
                "    WHEN coalesce(json_extract(value,'$.signature'),'') != ''"
                "      THEN json_object('type','thinking','thinking',coalesce(json_extract(value,'$.thinking'),''),"
                "        'signature',json_extract(value,'$.signature')) END"
                "  WHEN 'toolCall' THEN json_object('type','tool_use','id',json_extract(value,'$.id'),"
                "    'name',json_extract(value,'$.name'),'input',json(json_extract(value,'$.arguments')))"
                " END AS y FROM json_each(?1) ORDER BY key) WHERE y IS NOT NULL",
                "t", &native, body) != 0) {
            return NULL;
        }
    } else if (strcmp(model, "unknown") != 0 && strcmp(api, "openai-completions") == 0) {
        if (ipi_run(
                s,
                "WITH parts AS ("
                " SELECT"
                "  (SELECT group_concat(json_extract(value,'$.text'),'') FROM json_each(?1)"
                "   WHERE json_extract(value,'$.type')='text') AS t,"
                "  (SELECT count(*) FROM json_each(?1) WHERE json_extract(value,'$.type')='toolCall') AS n,"
                "  (SELECT json_group_array(json_object('id',json_extract(value,'$.id'),'type','function',"
                "    'function',json_object('name',json_extract(value,'$.name'),"
                "      'arguments',json_extract(value,'$.arguments') || '')))"
                "   FROM json_each(?1) WHERE json_extract(value,'$.type')='toolCall') AS calls,"
                "  (SELECT json_extract(value,'$.signature') FROM json_each(?1)"
                "   WHERE json_extract(value,'$.type')='thinking'"
                "     AND json_valid(json_extract(value,'$.signature'))"
                "     AND json_type(json_extract(value,'$.signature'))='array' LIMIT 1) AS rd,"
                "  (SELECT group_concat(json_extract(value,'$.thinking'),'') FROM json_each(?1)"
                "   WHERE json_extract(value,'$.type')='thinking'"
                "     AND coalesce(json_extract(value,'$.thinking'),'') != '') AS rt,"
                "  coalesce((SELECT json_extract(value,'$.signature') FROM json_each(?1)"
                "   WHERE json_extract(value,'$.type')='thinking'"
                "     AND json_extract(value,'$.signature') IN ('reasoning_content','reasoning','reasoning_text')"
                "   LIMIT 1), 'reasoning_content') AS rf)"
                " SELECT json_patch("
                "  json_object('role','assistant','content',CASE WHEN coalesce(t,'')='' AND n > 0 THEN NULL ELSE coalesce(t,'') END),"
                "  json_object('tool_calls',CASE WHEN n > 0 THEN json(calls) END,"
                "    'reasoning_details',CASE WHEN rd IS NOT NULL THEN json(rd) END,"
                "    rf,CASE WHEN rd IS NULL AND coalesce(rt,'') != '' THEN rt END)) FROM parts",
                "t", &native, body) != 0) {
            return NULL;
        }
    } else if (strcmp(model, "unknown") != 0 && strcmp(api, "openai-responses") == 0) {
        if (ipi_run(
                s,
                "SELECT coalesce(json_group_array(json(y)), '[]') FROM ("
                " SELECT key AS o, json(json_extract(value,'$.signature')) AS y FROM json_each(?1)"
                "  WHERE json_extract(value,'$.type')='thinking'"
                "    AND json_valid(json_extract(value,'$.signature'))"
                "    AND json_type(json_extract(value,'$.signature'))='object'"
                "    AND json_extract(json_extract(value,'$.signature'),'$.type')='reasoning'"
                " UNION ALL"
                " SELECT 1000000, json_object('role','assistant','content',"
                "   (SELECT group_concat(json_extract(value,'$.text'),'') FROM json_each(?1)"
                "    WHERE json_extract(value,'$.type')='text'))"
                "  WHERE EXISTS (SELECT 1 FROM json_each(?1) WHERE json_extract(value,'$.type')='text'"
                "    AND json_extract(value,'$.text') != '')"
                " UNION ALL"
                " SELECT 2000000 + key, json_object('type','function_call','call_id',"
                "   CASE WHEN instr(json_extract(value,'$.id'),'|') > 0"
                "     THEN substr(json_extract(value,'$.id'),1,instr(json_extract(value,'$.id'),'|')-1)"
                "     ELSE json_extract(value,'$.id') END,"
                "   'name',json_extract(value,'$.name'),'arguments',json_extract(value,'$.arguments') || '')"
                "  FROM json_each(?1) WHERE json_extract(value,'$.type')='toolCall'"
                " ORDER BY o)",
                "t", &native, body) != 0) {
            return NULL;
        }
    }
    if (!native) {
        native = strdup(body);
        if (!native) {
            ipi_oom(s);
        }
    }
    return native;
}

/* Whether another assistant message follows R directly (passing through skipped
 * metadata entries) without an intervening user/compaction/branch/custom entry. */
static int ipi_has_followup_assistant(pic_store *s, const ipi_row *r, int *out) {
    char *res = NULL;
    *out = 0;
    if (ipi_run(s,
                "WITH RECURSIVE d(n, id, skip) AS ("
                " SELECT n, id, type NOT IN ('message','compaction','branch_summary','custom_message')"
                " FROM ipi_raw WHERE parent_id = ?1 AND n > ?2"
                " UNION"
                " SELECT x.n, x.id, x.type NOT IN ('message','compaction','branch_summary','custom_message')"
                " FROM ipi_raw x JOIN d ON x.parent_id = d.id WHERE d.skip AND x.n > d.n)"
                " SELECT EXISTS (SELECT 1 FROM ipi_raw x JOIN d ON x.n = d.n"
                "   WHERE x.type = 'message' AND x.role = 'assistant')",
                "ti", &res, r->id, r->n) != 0) {
        return -1;
    }
    *out = res && strcmp(res, "1") == 0;
    free(res);
    return 0;
}

/* Clone an existing user entry's text and attachments as a sibling submission
 * (for mid-submission assistant branching off an already-replied user turn). */
static int ipi_clone_user_sub(ipi_ctx *c, sqlite3_int64 src_seq, sqlite3_int64 *sub_out, sqlite3_int64 *seq_out) {
    sqlite3_stmt *q = NULL;
    char *body = NULL;
    sqlite3_int64 src_parent = 0;
    int rc;
    if (sqlite3_prepare_v2(c->s->db, "SELECT body, coalesce(parent_seq, 0) FROM pic_entry WHERE seq = ?1", -1, &q, NULL) !=
        SQLITE_OK) {
        return ipi_sql_fail(c->s);
    }
    sqlite3_bind_int64(q, 1, src_seq);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *t0 = (const char *)sqlite3_column_text(q, 0);
        if (t0) {
            body = strdup(t0);
        }
        src_parent = sqlite3_column_int64(q, 1);
    }
    sqlite3_finalize(q);
    if (!body) {
        return ipi_oom(c->s);
    }
    rc = ipi_insert_user_sub(c, body, NULL, 0, src_parent, sub_out, seq_out);
    free(body);
    if (rc != 0) {
        return -1;
    }
    return ipi_run(c->s,
                   "INSERT INTO pic_attachment(entry_seq, queued_id, ordinal, image)"
                   " SELECT ?1, NULL, ordinal, image FROM pic_attachment WHERE entry_seq = ?2 ORDER BY ordinal",
                   "ii", NULL, *seq_out, src_seq);
}

static int ipi_handle_assistant(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 parent_seq,
                                sqlite3_int64 parent_sub) {
    char *body = NULL, *native = NULL, *provider = NULL, *api = NULL, *model = NULL, *stop = NULL, *usage = NULL;
    ipi_call *calls = NULL;
    ipi_tr_seen *seen = NULL;
    size_t ncalls = 0, nseen = 0, scap = 0;
    sqlite3_int64 sub = 0, tip = 0, aseq = 0, turn = 0, cur_parent = 0;
    int answered = 0, is_bash = 0, followup = 0, rc = -1;
    const char *kind;
    if (ipi_build_assistant_body(c->s, r->n, line, &body, &calls, &ncalls) != 0) {
        goto out;
    }
    if (strcmp(body, "[]") == 0 && ncalls == 0) {
        /* Empty assistant turn (e.g. aborted before emitting anything): pass parent through. */
        rc = ipi_map_put(c->s, r->id, parent_seq, parent_seq, parent_sub, 0);
        goto out;
    }
    if (ipi_run(c->s,
                "SELECT coalesce(nullif(CASE WHEN json_type(?1,'$.message.provider')='text'"
                " THEN json_extract(?1,'$.message.provider') END, ''), 'anthropic')",
                "t", &provider, line) != 0 ||
        ipi_run(c->s,
                "SELECT coalesce(nullif(CASE WHEN json_type(?1,'$.message.api')='text'"
                " THEN json_extract(?1,'$.message.api') END, ''), 'anthropic-messages')",
                "t", &api, line) != 0 ||
        ipi_run(c->s,
                "SELECT coalesce(nullif(CASE WHEN json_type(?1,'$.message.model')='text'"
                " THEN json_extract(?1,'$.message.model') END, ''), 'unknown')",
                "t", &model, line) != 0 ||
        ipi_run(c->s,
                "SELECT CASE WHEN json_type(?1,'$.message.stopReason')='text'"
                " AND json_extract(?1,'$.message.stopReason') != '' THEN json_extract(?1,'$.message.stopReason') END",
                "t", &stop, line) != 0 ||
        ipi_parse_usage(c->s, line, "$.message.usage", model, &usage) != 0) {
        goto out;
    }
    if (!stop && !(stop = strdup(ncalls ? "toolUse" : "stop"))) {
        ipi_oom(c->s);
        goto out;
    }
    if (!(native = ipi_build_native(c->s, api, model, body))) {
        goto out;
    }
    /* Attach to parent's submission when it is open and parent_seq is its chain tip;
     * otherwise start a new submission so pic_check's one-chain invariant holds. */
    if (parent_sub > 0 && ipi_sub_state(c->s, parent_sub, &tip, &answered, &is_bash) > 0 && !answered && !is_bash &&
        tip == parent_seq) {
        sub = parent_sub;
    } else {
        char *pkind = NULL;
        /* Never clone a bashExecution entry as a plain user prompt (would leak
         * excludeFromContext:true !! commands into model context). */
        if (parent_seq > 0 &&
            ipi_run(c->s,
                    "SELECT kind FROM pic_entry WHERE seq = ?1"
                    " AND NOT EXISTS (SELECT 1 FROM pic_bash WHERE entry_seq = ?1)",
                    "i", &pkind, parent_seq) != 0) {
            goto out;
        }
        if (pkind && strcmp(pkind, "user") == 0) {
            free(pkind);
            if (ipi_clone_user_sub(c, parent_seq, &sub, &parent_seq) != 0) {
                goto out;
            }
        } else {
            free(pkind);
            if (ipi_insert_user_sub(c, "", NULL, 0, parent_seq, &sub, &parent_seq) != 0) {
                goto out;
            }
        }
    }
    if (ncalls == 0 && ipi_has_followup_assistant(c->s, r, &followup) != 0) {
        goto out;
    }
    kind = (ncalls > 0 || followup) ? "assistant" : "answer";
    if (ipi_run(c->s,
                "INSERT INTO pic_entry(submission_id, kind, body, native, provider, api, model, parent_seq, created_ms)"
                " VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                "ittttttii", NULL, sub, kind, body, native, provider, api, model, parent_seq, c->now_ms) != 0) {
        goto out;
    }
    aseq = sqlite3_last_insert_rowid(c->s->db);
    if (ipi_sub_next_turn(c->s, sub, "reply_turn", &turn) != 0 ||
        ipi_run(c->s,
                "INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, stop_reason, usage, purpose)"
                " VALUES(?1, ?2, 1, 'done', ?3, ?4, ?5, 'reply')",
                "iiitt", NULL, sub, turn, aseq, stop, usage) != 0 ||
        ipi_run(c->s, "UPDATE ipi_sub SET tip_seq = ?1, answered = CASE WHEN ?2 THEN 1 ELSE answered END WHERE id = ?3",
                "iii", NULL, aseq, (sqlite3_int64)(strcmp(kind, "answer") == 0), sub) != 0) {
        goto out;
    }
    if (strcmp(kind, "answer") == 0 &&
        ipi_run(c->s, "UPDATE pic_submission SET status = 'answered' WHERE id = ?1", "i", NULL, sub) != 0) {
        goto out;
    }
    c->last_seq = aseq;
    if (ncalls == 0) {
        rc = ipi_map_put(c->s, r->id, aseq, aseq, sub, 1);
        goto out;
    }
    /* Pair toolResult descendants of R with R's toolCall blocks. */
    {
        sqlite3_stmt *q = NULL;
        int step;
        if (sqlite3_prepare_v2(
                c->s->db,
                "WITH RECURSIVE tr(n, id, role, type) AS ("
                " SELECT n, id, role, type FROM ipi_raw WHERE parent_id = ?1 AND n > ?2"
                "  AND ((type = 'message' AND role = 'toolResult')"
                "   OR type NOT IN ('message','compaction','branch_summary','custom_message'))"
                " UNION"
                " SELECT x.n, x.id, x.role, x.type FROM ipi_raw x JOIN tr ON x.parent_id = tr.id"
                " WHERE x.n > tr.n AND ((x.type = 'message' AND x.role = 'toolResult')"
                "   OR x.type NOT IN ('message','compaction','branch_summary','custom_message')))"
                " SELECT x.n, x.id, x.line,"
                "  CASE WHEN json_type(x.line,'$.message.toolCallId')='text' THEN json_extract(x.line,'$.message.toolCallId') END,"
                "  json_type(x.line,'$.message.isError')='true' OR json_extract(x.line,'$.message.isError')=1"
                " FROM ipi_raw x JOIN tr ON x.n = tr.n"
                " WHERE x.type = 'message' AND x.role = 'toolResult' AND x.n NOT IN (SELECT n FROM ipi_handled)"
                " ORDER BY x.n",
                -1, &q, NULL) != SQLITE_OK) {
            ipi_sql_fail(c->s);
            goto out;
        }
        sqlite3_bind_text(q, 1, r->id, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, r->n);
        while ((step = sqlite3_step(q)) == SQLITE_ROW) {
            sqlite3_int64 tr_n = sqlite3_column_int64(q, 0);
            const char *tr_id = (const char *)sqlite3_column_text(q, 1);
            const char *tr_line = (const char *)sqlite3_column_text(q, 2);
            const char *call_id = (const char *)sqlite3_column_text(q, 3);
            int is_err = sqlite3_column_int(q, 4) != 0;
            if (!call_id || !tr_id || !tr_line) {
                continue;
            }
            for (size_t j = 0; j < ncalls; j++) {
                if (!calls[j].matched && strcmp(calls[j].id, call_id) == 0) {
                    calls[j].matched = 1;
                    calls[j].tr_n = tr_n;
                    calls[j].tr_id = strdup(tr_id);
                    calls[j].tr_line = strdup(tr_line);
                    calls[j].tr_is_error = is_err;
                    if (!calls[j].tr_id || !calls[j].tr_line) {
                        sqlite3_finalize(q);
                        ipi_oom(c->s);
                        goto out;
                    }
                    if (nseen == scap) {
                        size_t ncap = scap ? scap * 2 : 8;
                        ipi_tr_seen *grown = realloc(seen, ncap * sizeof *seen);
                        if (!grown) {
                            sqlite3_finalize(q);
                            ipi_oom(c->s);
                            goto out;
                        }
                        seen = grown;
                        scap = ncap;
                    }
                    seen[nseen].n = tr_n;
                    seen[nseen].id = calls[j].tr_id;
                    seen[nseen].rseq = 0;
                    nseen++;
                    break;
                }
            }
        }
        sqlite3_finalize(q);
        if (step != SQLITE_DONE) {
            ipi_sql_fail(c->s);
            goto out;
        }
    }
    cur_parent = aseq;
    for (size_t j = 0; j < ncalls; j++) {
        char *rbody = NULL;
        pic_image *images = NULL;
        unsigned char *bytes = NULL;
        size_t nimages = 0;
        int is_error = 1, replay_safe;
        sqlite3_int64 eff_id, rseq;
        if (calls[j].matched) {
            char *raw = ipi_extract_text(c->s, calls[j].tr_line, "$.message.content");
            if (!raw) {
                goto out;
            }
            rbody = ipi_with_images(c->s, raw, calls[j].tr_line, "$.message.content", &images, &nimages, &bytes);
            free(raw);
            if (!rbody) {
                goto out;
            }
            is_error = calls[j].tr_is_error;
        } else {
            rbody = strdup("No result in the imported session");
            if (!rbody) {
                ipi_oom(c->s);
                goto out;
            }
        }
        replay_safe = strcmp(calls[j].name, "read") == 0 || strcmp(calls[j].name, "write") == 0 ||
                      strcmp(calls[j].name, "edit") == 0;
        if (ipi_run(c->s,
                    "INSERT INTO pic_effect(entry_seq, ordinal, call_id, tool, input, replay_safe, state, result, is_error)"
                    " VALUES(?1, ?2, ?3, ?4, ?5, ?6, 'done', ?7, ?8)",
                    "iitttiti", NULL, aseq, (sqlite3_int64)j, calls[j].id, calls[j].name, calls[j].args,
                    (sqlite3_int64)replay_safe, rbody, (sqlite3_int64)is_error) != 0) {
            free(rbody);
            free(images);
            free(bytes);
            goto out;
        }
        eff_id = sqlite3_last_insert_rowid(c->s->db);
        if (ipi_run(c->s,
                    "INSERT INTO pic_entry(submission_id, kind, body, effect_id, parent_seq, created_ms)"
                    " VALUES(?1, 'tool_result', ?2, ?3, ?4, ?5)",
                    "itiii", NULL, sub, rbody, eff_id, cur_parent, c->now_ms) != 0) {
            free(rbody);
            free(images);
            free(bytes);
            goto out;
        }
        rseq = sqlite3_last_insert_rowid(c->s->db);
        if (pic_attach_images(c->s, rseq, 0, images, nimages) != 0) {
            free(rbody);
            free(images);
            free(bytes);
            goto out;
        }
        free(rbody);
        free(images);
        free(bytes);
        calls[j].rseq = rseq;
        cur_parent = rseq;
        c->last_seq = rseq;
        if (ipi_run(c->s, "UPDATE ipi_sub SET tip_seq = ?1 WHERE id = ?2", "ii", NULL, rseq, sub) != 0) {
            goto out;
        }
    }
    /* Map R (its own seq is aseq; when no results matched, children attach after
     * the synthesized tool_results) and each consumed toolResult. */
    if (ipi_map_put(c->s, r->id, aseq, nseen == 0 ? cur_parent : aseq, sub, 1) != 0) {
        goto out;
    }
    for (size_t k = 0; k < nseen; k++) {
        sqlite3_int64 own_seq = cur_parent;
        for (size_t j = 0; j < ncalls; j++) {
            if (calls[j].matched && calls[j].tr_n == seen[k].n) {
                own_seq = calls[j].rseq;
                break;
            }
        }
        /* The final consumed toolResult in file order carries cur_parent as its
         * child_seq so later turns attach after all results even if results were
         * out of call order or some calls were synthesized. */
        sqlite3_int64 cseq = (k + 1 == nseen) ? cur_parent : own_seq;
        if (ipi_run(c->s, "INSERT OR IGNORE INTO ipi_handled(n) VALUES(?1)", "i", NULL, seen[k].n) != 0 ||
            ipi_map_put(c->s, seen[k].id, own_seq, cseq, sub, 1) != 0) {
            goto out;
        }
    }
    rc = 0;
out:
    free(body);
    free(native);
    free(provider);
    free(api);
    free(model);
    free(stop);
    free(usage);
    free(seen);
    ipi_free_calls(calls, ncalls);
    return rc;
}

/* Resolve a compaction's firstKeptEntryId (or v1 firstKeptEntryIndex) to the
 * first imported pic_entry.seq on R's path at or after that target; 0 if none. */
static int ipi_resolve_first_kept(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 *out_seq) {
    char *fk_id = NULL, *best = NULL;
    *out_seq = 0;
    if (ipi_run(c->s,
                "SELECT CASE WHEN json_type(?1,'$.firstKeptEntryId')='text'"
                " AND json_extract(?1,'$.firstKeptEntryId') != '' THEN json_extract(?1,'$.firstKeptEntryId') END",
                "t", &fk_id, line) != 0) {
        return -1;
    }
    if (!fk_id) {
        /* Pi v1 compaction: firstKeptEntryIndex indexes the raw entries array. */
        if (ipi_run(c->s,
                    "SELECT r.id FROM ipi_raw r WHERE json_type(?1,'$.firstKeptEntryIndex')='integer'"
                    " AND r.file_idx = json_extract(?1,'$.firstKeptEntryIndex') AND r.n < ?2 LIMIT 1",
                    "ti", &fk_id, line, r->n) != 0) {
            return -1;
        }
    }
    if (!fk_id || !r->parent_id) {
        free(fk_id);
        return 0;
    }
    /* Verify fk_id lies on R's ancestor path and pick the earliest directly
     * imported entry on that path at or after fk_id (handles both direct
     * targets and skipped metadata targets such as model_change). */
    if (ipi_run(c->s,
                "WITH RECURSIVE anc(n, id, parent_id, hit) AS ("
                " SELECT n, id, parent_id, id = ?2 FROM ipi_raw WHERE id = ?1 AND n < ?3"
                " UNION"
                " SELECT p.n, p.id, p.parent_id, p.id = ?2 FROM ipi_raw p JOIN anc ON p.id = anc.parent_id"
                " WHERE NOT anc.hit AND p.n < anc.n)"
                " SELECT min(m.seq) FROM anc JOIN ipi_map m ON m.id = anc.id"
                " WHERE m.direct = 1 AND m.seq > 0 AND EXISTS (SELECT 1 FROM anc WHERE hit)",
                "tti", &best, r->parent_id, fk_id, r->n) != 0) {
        free(fk_id);
        return -1;
    }
    if (best) {
        *out_seq = strtoll(best, NULL, 10);
        free(best);
    }
    free(fk_id);
    return 0;
}

static int ipi_handle_compaction(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 parent_seq,
                                 sqlite3_int64 parent_sub) {
    char *summary = NULL, *details = NULL, *tb_str = NULL, *usage = NULL;
    sqlite3_int64 first_kept = 0, tokens_before = 0, tip = 0, from_seq = 0, cseq = 0, cturn = 0;
    int answered = 0, is_bash = 0, rc = -1;
    if (parent_seq == 0 || parent_sub == 0) {
        return ipi_map_put(c->s, r->id, 0, 0, 0, 0);
    }
    if (ipi_run(c->s,
                "SELECT coalesce(CASE WHEN json_type(?1,'$.summary')='text' THEN json_extract(?1,'$.summary') END, '')",
                "t", &summary, line) != 0 ||
        ipi_run(c->s,
                "SELECT json_object("
                " 'readFiles', CASE WHEN json_type(?1,'$.details.readFiles')='array'"
                "   THEN json(json_extract(?1,'$.details.readFiles')) ELSE json('[]') END,"
                " 'modifiedFiles', CASE WHEN json_type(?1,'$.details.modifiedFiles')='array'"
                "   THEN json(json_extract(?1,'$.details.modifiedFiles')) ELSE json('[]') END)",
                "t", &details, line) != 0 ||
        ipi_run(c->s,
                "SELECT CASE"
                " WHEN json_type(?1,'$.tokensBefore')='integer' AND json_extract(?1,'$.tokensBefore') >= 0"
                "   THEN json_extract(?1,'$.tokensBefore')"
                " WHEN json_type(?1,'$.tokensBefore')='real' AND json_extract(?1,'$.tokensBefore') >= 0"
                "   AND json_extract(?1,'$.tokensBefore') <= 9007199254740992.0"
                "   THEN CAST(json_extract(?1,'$.tokensBefore') AS INTEGER)"
                " ELSE 0 END",
                "t", &tb_str, line) != 0 ||
        ipi_parse_usage(c->s, line, "$.usage", NULL, &usage) != 0 ||
        ipi_resolve_first_kept(c, r, line, &first_kept) != 0) {
        goto out;
    }
    if (tb_str) {
        tokens_before = strtoll(tb_str, NULL, 10);
    }
    if (ipi_sub_state(c->s, parent_sub, &tip, &answered, &is_bash) > 0 && !answered && !is_bash && tip == parent_seq) {
        from_seq = 0;
    } else {
        from_seq = parent_seq;
    }
    if (ipi_run(c->s,
                "INSERT INTO pic_entry(submission_id, kind, body, native, parent_seq, created_ms, first_kept_seq,"
                " tokens_before, from_seq) VALUES(?1, 'compaction', ?2, ?3, ?4, ?5, nullif(?6, 0), ?7, nullif(?8, 0))",
                "ittiiiii", NULL, parent_sub, summary ? summary : "", details ? details : "{\"readFiles\":[],\"modifiedFiles\":[]}",
                parent_seq, c->now_ms, first_kept, tokens_before, from_seq) != 0) {
        goto out;
    }
    cseq = sqlite3_last_insert_rowid(c->s->db);
    if (first_kept == 0 &&
        ipi_run(c->s, "UPDATE pic_entry SET first_kept_seq = ?1 WHERE seq = ?1", "i", NULL, cseq) != 0) {
        goto out;
    }
    if (from_seq == 0 && ipi_run(c->s, "UPDATE ipi_sub SET tip_seq = ?1 WHERE id = ?2", "ii", NULL, cseq, parent_sub) != 0) {
        goto out;
    }
    if (ipi_sub_next_turn(c->s, parent_sub, "compact_turn", &cturn) != 0 ||
        ipi_run(c->s,
                "INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, usage, purpose, reason,"
                " context_tokens) VALUES(?1, ?2, 1, 'done', ?3, ?4, 'compaction', 'manual', ?5)",
                "iiiti", NULL, parent_sub, cturn, cseq, usage, tokens_before) != 0) {
        goto out;
    }
    c->last_seq = cseq;
    rc = ipi_map_put(c->s, r->id, cseq, cseq, parent_sub, 1);
out:
    free(summary);
    free(details);
    free(tb_str);
    free(usage);
    return rc;
}

static int ipi_handle_branch_summary(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 parent_seq,
                                     sqlite3_int64 parent_sub) {
    char *summary = NULL, *details = NULL, *from_id = NULL, *usage = NULL;
    sqlite3_int64 owner_seq = parent_seq, owner_sub = parent_sub, from_seq = 0, bseq = 0, bturn = 0;
    int rc = -1;
    /* pic_check requires branch_summary's parent to be a non-branch_summary
     * entry in the same submission. Walk up if parent is itself a branch_summary. */
    while (owner_seq > 0) {
        sqlite3_stmt *q = NULL;
        int is_bs = 0;
        sqlite3_int64 up_parent = 0, up_sub = 0;
        if (sqlite3_prepare_v2(c->s->db, "SELECT kind = 'branch_summary', coalesce(parent_seq, 0), submission_id FROM pic_entry WHERE seq = ?1",
                               -1, &q, NULL) != SQLITE_OK) {
            return ipi_sql_fail(c->s);
        }
        sqlite3_bind_int64(q, 1, owner_seq);
        if (sqlite3_step(q) == SQLITE_ROW) {
            is_bs = sqlite3_column_int(q, 0);
            up_parent = sqlite3_column_int64(q, 1);
            up_sub = sqlite3_column_int64(q, 2);
        }
        sqlite3_finalize(q);
        if (!is_bs) {
            owner_sub = up_sub;
            break;
        }
        owner_seq = up_parent;
    }
    if (owner_seq == 0 || owner_sub == 0) {
        return ipi_map_put(c->s, r->id, parent_seq, parent_seq, parent_sub, 0);
    }
    if (ipi_run(c->s,
                "SELECT coalesce(CASE WHEN json_type(?1,'$.summary')='text' THEN json_extract(?1,'$.summary') END, '')",
                "t", &summary, line) != 0 ||
        ipi_run(c->s,
                "SELECT json_object("
                " 'readFiles', CASE WHEN json_type(?1,'$.details.readFiles')='array'"
                "   THEN json(json_extract(?1,'$.details.readFiles')) ELSE json('[]') END,"
                " 'modifiedFiles', CASE WHEN json_type(?1,'$.details.modifiedFiles')='array'"
                "   THEN json(json_extract(?1,'$.details.modifiedFiles')) ELSE json('[]') END)",
                "t", &details, line) != 0 ||
        ipi_run(c->s,
                "SELECT CASE WHEN json_type(?1,'$.fromId')='text' AND json_extract(?1,'$.fromId') != ''"
                " THEN json_extract(?1,'$.fromId') END",
                "t", &from_id, line) != 0 ||
        ipi_parse_usage(c->s, line, "$.usage", NULL, &usage) != 0) {
        goto out;
    }
    if (from_id && ipi_map_get(c->s, from_id, &from_seq, NULL, NULL, NULL) < 0) {
        goto out;
    }
    if (from_seq <= 0) {
        from_seq = owner_seq;
    }
    if (ipi_run(c->s,
                "INSERT INTO pic_entry(submission_id, kind, body, native, parent_seq, from_seq, created_ms)"
                " VALUES(?1, 'branch_summary', ?2, ?3, ?4, ?5, ?6)",
                "ittiii", NULL, owner_sub, summary ? summary : "",
                details ? details : "{\"readFiles\":[],\"modifiedFiles\":[]}", owner_seq, from_seq, c->now_ms) != 0) {
        goto out;
    }
    bseq = sqlite3_last_insert_rowid(c->s->db);
    if (usage) {
        if (ipi_sub_next_turn(c->s, owner_sub, "branch_turn", &bturn) != 0 ||
            ipi_run(c->s,
                    "INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, usage, purpose)"
                    " VALUES(?1, ?2, 1, 'done', ?3, ?4, 'branch_summary')",
                    "iiit", NULL, owner_sub, bturn, bseq, usage) != 0) {
            goto out;
        }
    }
    c->last_seq = bseq;
    rc = ipi_map_put(c->s, r->id, bseq, bseq, owner_sub, 1);
out:
    free(summary);
    free(details);
    free(from_id);
    free(usage);
    return rc;
}

static int ipi_handle_custom_message(ipi_ctx *c, const ipi_row *r, const char *line, sqlite3_int64 parent_seq,
                                     sqlite3_int64 parent_sub) {
    char *ctype = NULL, *text = NULL;
    sqlite3_int64 tip = 0, from_seq = 0, iseq = 0;
    int answered = 0, is_bash = 0, display = 0, has_img = 0, rc = -1;
    {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(
                c->s->db,
                "SELECT"
                " coalesce(CASE WHEN json_type(?1,'$.customType')='text' THEN json_extract(?1,'$.customType') END, ''),"
                " json_type(?1,'$.display')='true' OR json_extract(?1,'$.display')=1,"
                " json_type(?1,'$.content')='array' AND EXISTS (SELECT 1 FROM json_each(?1,'$.content') x"
                "   WHERE x.type='object' AND json_extract(x.value,'$.type')='image')",
                -1, &q, NULL) != SQLITE_OK) {
            return ipi_sql_fail(c->s);
        }
        sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            const char *t0 = (const char *)sqlite3_column_text(q, 0);
            ctype = t0 ? strdup(t0) : NULL;
            display = sqlite3_column_int(q, 1);
            has_img = sqlite3_column_int(q, 2);
        }
        sqlite3_finalize(q);
    }
    if (!ctype) {
        return ipi_oom(c->s);
    }
    /* pic.instructions (and text-only hidden custom_messages) inside a tree
     * become instructions entries; displayed or image-bearing or root custom
     * messages become user submissions so images and root text are preserved. */
    if (parent_seq > 0 && parent_sub > 0 && (strcmp(ctype, "pic.instructions") == 0 || (!display && !has_img))) {
        text = ipi_extract_text(c->s, line, "$.content");
        if (!text) {
            goto out;
        }
        if (ipi_sub_state(c->s, parent_sub, &tip, &answered, &is_bash) > 0 && !answered && !is_bash && tip == parent_seq) {
            from_seq = 0;
        } else {
            from_seq = parent_seq;
        }
        if (ipi_run(c->s,
                    "INSERT INTO pic_entry(submission_id, kind, body, parent_seq, created_ms, from_seq)"
                    " VALUES(?1, 'instructions', ?2, ?3, ?4, nullif(?5, 0))",
                    "itiii", NULL, parent_sub, text, parent_seq, c->now_ms, from_seq) != 0) {
            goto out;
        }
        iseq = sqlite3_last_insert_rowid(c->s->db);
        if (from_seq == 0 &&
            ipi_run(c->s, "UPDATE ipi_sub SET tip_seq = ?1 WHERE id = ?2", "ii", NULL, iseq, parent_sub) != 0) {
            goto out;
        }
        c->last_seq = iseq;
        rc = ipi_map_put(c->s, r->id, iseq, iseq, parent_sub, 1);
    } else if (has_img) {
        rc = ipi_handle_user(c, r, line, "$.content", parent_seq);
    } else {
        text = ipi_extract_text(c->s, line, "$.content");
        if (!text) {
            goto out;
        }
        if (*text) {
            rc = ipi_handle_user(c, r, line, "$.content", parent_seq);
        } else {
            rc = ipi_map_put(c->s, r->id, parent_seq, parent_seq, parent_sub, 0);
        }
    }
out:
    free(ctype);
    free(text);
    return rc;
}

static int ipi_finalize_heads(ipi_ctx *c) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 *leaves = NULL;
    size_t n = 0, cap = 0;
    int step, rc = -1;
    if (ipi_run(c->s,
                "UPDATE pic_submission SET status = 'failed', error = 'imported without a reply'"
                " WHERE id IN (SELECT id FROM ipi_sub) AND status = 'admitted'",
                "", NULL) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(
            c->s->db,
            "SELECT e.seq FROM pic_entry e WHERE e.submission_id IN (SELECT id FROM ipi_sub)"
            " AND NOT EXISTS (SELECT 1 FROM pic_entry ch WHERE ch.parent_seq = e.seq) ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        return ipi_sql_fail(c->s);
    }
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        if (n == cap) {
            size_t ncap = cap ? cap * 2 : 8;
            sqlite3_int64 *grown = realloc(leaves, ncap * sizeof *leaves);
            if (!grown) {
                sqlite3_finalize(q);
                free(leaves);
                return ipi_oom(c->s);
            }
            leaves = grown;
            cap = ncap;
        }
        leaves[n++] = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        free(leaves);
        return ipi_sql_fail(c->s);
    }
    /* Every additional branch leaf gets a forked session head so /tree and
     * /fork can switch to or fork from any branch; the active leaf (last_seq)
     * stays the main session with the newest updated_ms and the session name. */
    for (size_t i = 0; i < n; i++) {
        if (leaves[i] == c->last_seq) {
            continue;
        }
        if (ipi_run(c->s,
                    "INSERT INTO pic_session(id, created_ms, updated_ms, head_seq, forked_from)"
                    " VALUES(lower(hex(randomblob(4))), ?1, ?2, ?3, ?4)",
                    "iiit", NULL, c->now_ms, c->now_ms - 1, leaves[i], c->session) != 0) {
            goto out;
        }
    }
    if (ipi_run(c->s, "UPDATE pic_session SET head_seq = ?1, updated_ms = ?2, name = coalesce(nullif(?3, ''), name) WHERE id = ?4",
                "iitt", NULL, c->last_seq, c->now_ms, c->name, c->session) != 0) {
        goto out;
    }
    rc = 0;
out:
    free(leaves);
    return rc;
}

int pic_import_pi(pic_store *s, FILE *in, char *session_out, size_t cap, long *turns) {
    ipi_ctx c;
    ipi_buf input = {NULL, 0, 0};
    ipi_row *rows = NULL;
    size_t nrows = 0, rcap = 0;
    char *sid = NULL;
    int rc = -1, in_tx = 0;
    memset(&c, 0, sizeof c);
    c.s = s;
    c.now_ns = (long long)pic_platform_get()->wall_ns();
    c.now_ms = (sqlite3_int64)(c.now_ns / 1000000LL);
    /* Read all input first: it may be a slow pipe, and no write transaction is
     * held while waiting on anything outside the journal. */
    for (;;) {
        char chunk[65536];
        size_t r = fread(chunk, 1, sizeof chunk, in);
        if (r) {
            if (r > IPI_MAX_INPUT - input.len) {
                (void)snprintf(s->err, sizeof s->err, "session file exceeds %u MB limit",
                               (unsigned)(IPI_MAX_INPUT / (1024u * 1024u)));
                goto out;
            }
            if (ipi_buf_add(&input, chunk, r) != 0) {
                ipi_oom(s);
                goto out;
            }
        }
        if (r < sizeof chunk) {
            break;
        }
    }
    if (ferror(in)) {
        (void)snprintf(s->err, sizeof s->err, "cannot read session: %s", strerror(errno));
        goto out;
    }
    ipi_drop_tables(s);
    if (pic_exec(s, ipi_tables_sql) != 0 || ipi_load(&c, &input) != 0) {
        goto out;
    }
    free(input.buf);
    input.buf = NULL;
    input.len = input.cap = 0;
    /* Load row metadata before starting the write transaction. */
    {
        sqlite3_stmt *q = NULL;
        int step;
        if (sqlite3_prepare_v2(s->db, "SELECT n, id, parent_id, type, role FROM ipi_raw ORDER BY n", -1, &q, NULL) !=
            SQLITE_OK) {
            ipi_sql_fail(s);
            goto out;
        }
        while ((step = sqlite3_step(q)) == SQLITE_ROW) {
            if (nrows == rcap) {
                size_t ncap = rcap ? rcap * 2 : 64;
                ipi_row *grown = realloc(rows, ncap * sizeof *rows);
                if (!grown) {
                    sqlite3_finalize(q);
                    ipi_oom(s);
                    goto out;
                }
                rows = grown;
                rcap = ncap;
            }
            {
                const char *t1 = (const char *)sqlite3_column_text(q, 1);
                const char *t2 = (const char *)sqlite3_column_text(q, 2);
                const char *t3 = (const char *)sqlite3_column_text(q, 3);
                const char *t4 = (const char *)sqlite3_column_text(q, 4);
                int has_t2 = sqlite3_column_type(q, 2) != SQLITE_NULL;
                int has_t4 = sqlite3_column_type(q, 4) != SQLITE_NULL;
                rows[nrows].n = sqlite3_column_int64(q, 0);
                rows[nrows].id = t1 ? strdup(t1) : NULL;
                rows[nrows].parent_id = t2 ? strdup(t2) : NULL;
                rows[nrows].type = t3 ? strdup(t3) : NULL;
                rows[nrows].role = t4 ? strdup(t4) : NULL;
                if (!rows[nrows].id || !rows[nrows].type || (has_t2 && !rows[nrows].parent_id) ||
                    (has_t4 && !rows[nrows].role)) {
                    nrows++;
                    sqlite3_finalize(q);
                    ipi_oom(s);
                    goto out;
                }
            }
            nrows++;
        }
        sqlite3_finalize(q);
        if (step != SQLITE_DONE) {
            ipi_sql_fail(s);
            goto out;
        }
    }
    if (pic_begin(s) != 0) {
        goto out;
    }
    in_tx = 1;
    if (ipi_run(s,
                "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4))), ?1, ?1)"
                " RETURNING id",
                "i", &sid, c.now_ms) != 0 ||
        !sid) {
        goto out;
    }
    (void)snprintf(c.session, sizeof c.session, "%s", sid);
    free(sid);
    sid = NULL;
    for (size_t i = 0; i < nrows; i++) {
        const ipi_row *r = &rows[i];
        char *handled = NULL, *line = NULL;
        sqlite3_int64 parent_seq = 0, parent_sub = 0;
        int step_rc = 0;
        if (ipi_run(s, "SELECT 1 FROM ipi_handled WHERE n = ?1", "i", &handled, r->n) != 0) {
            goto out;
        }
        if (handled) {
            free(handled);
            continue;
        }
        if (r->parent_id && ipi_map_get(s, r->parent_id, NULL, &parent_seq, &parent_sub, NULL) < 0) {
            goto out;
        }
        if (strcmp(r->type, "message") == 0 && r->role &&
            (strcmp(r->role, "user") == 0 || strcmp(r->role, "assistant") == 0 ||
             strcmp(r->role, "bashExecution") == 0)) {
            if (ipi_run(s, "SELECT line FROM ipi_raw WHERE n = ?1", "i", &line, r->n) != 0 || !line) {
                free(line);
                goto out;
            }
            if (strcmp(r->role, "user") == 0) {
                step_rc = ipi_handle_user(&c, r, line, "$.message.content", parent_seq);
            } else if (strcmp(r->role, "bashExecution") == 0) {
                step_rc = ipi_handle_bash(&c, r, line, parent_seq);
            } else {
                step_rc = ipi_handle_assistant(&c, r, line, parent_seq, parent_sub);
            }
            free(line);
        } else if (strcmp(r->type, "compaction") == 0 || strcmp(r->type, "branch_summary") == 0 ||
                   strcmp(r->type, "custom_message") == 0) {
            if (ipi_run(s, "SELECT line FROM ipi_raw WHERE n = ?1", "i", &line, r->n) != 0 || !line) {
                free(line);
                goto out;
            }
            if (strcmp(r->type, "compaction") == 0) {
                step_rc = ipi_handle_compaction(&c, r, line, parent_seq, parent_sub);
            } else if (strcmp(r->type, "branch_summary") == 0) {
                step_rc = ipi_handle_branch_summary(&c, r, line, parent_seq, parent_sub);
            } else {
                step_rc = ipi_handle_custom_message(&c, r, line, parent_seq, parent_sub);
            }
            free(line);
        } else {
            /* session_info, model_change, thinking_level_change, label, custom,
             * usage, orphan toolResult, unknown types: preserve parent link. */
            step_rc = ipi_map_put(s, r->id, parent_seq, parent_seq, parent_sub, 0);
        }
        if (step_rc != 0) {
            goto out;
        }
    }
    if (c.turns == 0 || c.last_seq == 0) {
        (void)snprintf(s->err, sizeof s->err, "no user messages in the session file (a Pi v3 session JSONL is expected)");
        goto out;
    }
    if (ipi_finalize_heads(&c) != 0 || pic_commit(s) != 0) {
        goto out;
    }
    in_tx = 0;
    (void)snprintf(session_out, cap, "%s", c.session);
    if (turns) {
        *turns = c.turns;
    }
    rc = 0;
out:
    if (rc != 0 && in_tx) {
        pic_rollback(s);
    }
    ipi_drop_tables(s);
    free(sid);
    free(input.buf);
    free(c.name);
    ipi_free_rows(rows, nrows);
    return rc;
}