Skip to content
pi-c Artifact [bb97b1b36a]
Login

Artifact [bb97b1b36a]

Artifact bb97b1b36a5153dbe3589282f1c3ca637f08cfd39e6929f02dfa826ae6964984:


/* A Claude Code transcript (JSONL) into a new pic conversation, so a long
 * real session can be continued (pic import --claude).
 *
 * The transcript is a tree of records (uuid, parentUuid). Its conversation
 * is the path to the last message before the cut, as Claude Code resumes
 * it: a compact boundary has no parent, so the path starts at the latest
 * compact summary; parallel tool calls and their results, which hang off the
 * path as siblings, are taken with it; abandoned branches and sidechains
 * (subagents) are not. Meta, synthetic and non-message records are left
 * out, and so is thinking.
 *
 * Each user text opens a request; the assistant records up to the next user
 * record are one reply. Calls of the tools pic has become its tool calls,
 * already done with their recorded results; any other call (or one whose
 * result is not in the transcript) is text in the reply, "[tool NAME:
 * INPUT]", and its result text after the batch's last result, or the next
 * request when the batch has none: "[result: TEXT]". Images are a
 * placeholder. The replies are marked as from an unknown model, so they are
 * always rebuilt from the neutral form. Nothing is logged of the content. */
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

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

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

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

/* S after SEP when B already holds something. */
static int buf_join(buf *b, const char *sep, const char *s) {
    return (b->len && buf_add(b, sep, strlen(sep)) != 0) || buf_add(b, s, strlen(s)) != 0 ? -1 : 0;
}

static void buf_clear(buf *b) {
    b->len = 0;
    if (b->buf) {
        b->buf[0] = '\0';
    }
}

typedef struct {
    pic_store *s;
    char session[16];
    long long now_ns;
    sqlite3_int64 sub;   /* the open request (0: none) */
    sqlite3_int64 last;  /* the latest request */
    long turn;           /* its replies so far */
    int answered;        /* it ended with its answer */
    buf user;            /* user text for the next request */
    buf reply;           /* the reply being gathered: its JSON items, comma-separated */
    long reply_calls;    /* its tool calls (rows of claude_call) */
    sqlite3_int64 batch; /* the written reply whose results are gathering (0: none) */
    buf extra;           /* text for after the batch's last result */
    pic_claude_import *out;
} importer;

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

/* A statement with text (t), integer (i) and SQL-null-when-NULL text
 * parameters; its first column, when it has one, into *row (malloc'd text). */
static int 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 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 && sqlite3_column_text(q, 0)) {
        *row = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
        return sql_fail(s);
    }
    return 0;
}

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

static const char tables_sql[] =
    "CREATE TEMP TABLE claude_rec(n INTEGER PRIMARY KEY, uuid TEXT, parent TEXT, type TEXT, mid TEXT, line TEXT NOT NULL,"
    " kept INTEGER NOT NULL DEFAULT 0);"
    "CREATE INDEX temp.claude_rec_uuid ON claude_rec(uuid);"
    "CREATE INDEX temp.claude_rec_mid ON claude_rec(mid);"
    "CREATE TEMP TABLE claude_use(id TEXT PRIMARY KEY);"  /* tool_use ids on the path */
    "CREATE TEMP TABLE claude_res(id TEXT PRIMARY KEY);"  /* tool_result ids on the path */
    "CREATE TEMP TABLE claude_seen(id TEXT PRIMARY KEY);" /* call ids journaled */
    "CREATE TEMP TABLE claude_call(id TEXT PRIMARY KEY, ordinal INTEGER NOT NULL, tool TEXT NOT NULL, input TEXT NOT NULL,"
    " result TEXT, is_error INTEGER NOT NULL DEFAULT 0);";

static void drop_tables(pic_store *s) {
    (void)sqlite3_exec(s->db,
                       "DROP TABLE IF EXISTS temp.claude_rec; DROP TABLE IF EXISTS temp.claude_use;"
                       " DROP TABLE IF EXISTS temp.claude_res; DROP TABLE IF EXISTS temp.claude_seen;"
                       " DROP TABLE IF EXISTS temp.claude_call;",
                       NULL, NULL, NULL);
}

/* The elements of a record's content, or of a string content as one text. */
#define CONTENT(line) \
    "json_each(CASE WHEN json_type(" line ", '$.message.content') = 'array' THEN json_extract(" line ", '$.message.content')" \
    " ELSE json_array(json_object('type', 'text', 'text', json_extract(" line ", '$.message.content'))) END)"
/* An element's type, when it is an object. */
#define BLOCK_TYPE(x) "CASE WHEN " x ".type = 'object' THEN json_extract(" x ".value, '$.type') END"

/* Records of IN before UNTIL into claude_rec: those with a uuid, sidechains
 * left out. */
static int load(pic_store *s, FILE *in, const char *until) {
    sqlite3_stmt *head = NULL, *add = NULL;
    char *line = NULL;
    size_t cap = 0;
    int rc = -1, found = 0;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_extract(?1, '$.uuid'), coalesce(json_extract(?1, '$.isSidechain'), 0)"
                           " WHERE json_valid(?1)",
                           -1, &head, NULL) != SQLITE_OK ||
        sqlite3_prepare_v2(s->db,
                           "INSERT INTO claude_rec(uuid, parent, type, mid, line) VALUES(json_extract(?1, '$.uuid'),"
                           " json_extract(?1, '$.parentUuid'), json_extract(?1, '$.type'), json_extract(?1, '$.message.id'), ?1)",
                           -1, &add, NULL) != SQLITE_OK) {
        sql_fail(s);
        goto out;
    }
    while (getline(&line, &cap, in) >= 0) {
        const char *uuid;
        int side;
        sqlite3_reset(head);
        sqlite3_bind_text(head, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(head) != SQLITE_ROW || !(uuid = (const char *)sqlite3_column_text(head, 0))) {
            continue; /* torn, or not a record of the conversation tree */
        }
        if (until && strcmp(uuid, until) == 0) {
            found = 1;
            break;
        }
        side = sqlite3_column_int(head, 1);
        if (side) {
            continue;
        }
        sqlite3_reset(add);
        sqlite3_bind_text(add, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(add) != SQLITE_DONE) {
            sql_fail(s);
            goto out;
        }
    }
    if (until && !found) {
        (void)snprintf(s->err, sizeof s->err, "no record %s in the transcript", until);
        goto out;
    }
    rc = 0;
out:
    sqlite3_finalize(head);
    sqlite3_finalize(add);
    free(line);
    return rc;
}

/* Marks the conversation's records kept: the path to the last message, from
 * its latest compact summary, and the siblings of its parallel tool calls. */
static int choose(pic_store *s) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 *rest = NULL;
    size_t n = 0, cap = 0;
    char *leaf = NULL;
    int step;
    if (run(s, "SELECT max(n) FROM claude_rec WHERE type IN ('user', 'assistant')", "", &leaf) != 0) {
        return -1;
    }
    if (!leaf) {
        (void)snprintf(s->err, sizeof s->err, "no messages in the transcript (a Claude Code session JSONL is expected)");
        return -1;
    }
    if (run(s,
            "WITH RECURSIVE a(n, parent) AS (SELECT n, parent FROM claude_rec WHERE n = CAST(?1 AS INTEGER)"
            " UNION SELECT r.n, r.parent FROM claude_rec r JOIN a ON r.uuid = a.parent AND r.n < a.n)"
            " UPDATE claude_rec SET kept = 1 WHERE n IN (SELECT n FROM a)",
            "t", NULL, leaf) != 0 ||
        run(s,
            "UPDATE claude_rec SET kept = 0 WHERE n < (SELECT max(n) FROM claude_rec WHERE kept AND"
            " coalesce(json_extract(line, '$.isCompactSummary'), 0))",
            "", NULL) != 0 ||
        run(s,
            "INSERT OR IGNORE INTO claude_use SELECT json_extract(x.value, '$.id') FROM claude_rec r, " CONTENT("r.line") " x"
            " WHERE r.kept AND r.type = 'assistant' AND " BLOCK_TYPE("x") " = 'tool_use'",
            "", NULL) != 0) {
        free(leaf);
        return -1;
    }
    free(leaf);
    if (sqlite3_prepare_v2(s->db,
                           "SELECT n FROM claude_rec WHERE NOT kept AND n > (SELECT min(n) FROM claude_rec WHERE kept) ORDER BY n",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        if (n == cap) {
            sqlite3_int64 *grown = realloc(rest, (cap = cap ? cap * 2 : 256) * sizeof *rest);
            if (!grown) {
                sqlite3_finalize(q);
                free(rest);
                return oom(s);
            }
            rest = grown;
        }
        rest[n++] = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        free(rest);
        return sql_fail(s);
    }
    /* In file order, so a sibling's own siblings follow it in. */
    for (size_t i = 0; i < n; i++) {
        if (run(s,
                "UPDATE claude_rec SET kept = 1 WHERE n = ?1 AND EXISTS (SELECT 1 FROM claude_rec p WHERE p.uuid = claude_rec.parent"
                " AND p.kept) AND (type NOT IN ('user', 'assistant')"
                " OR (type = 'assistant' AND EXISTS (SELECT 1 FROM claude_rec m WHERE m.mid = claude_rec.mid AND m.kept"
                "   AND m.type = 'assistant'))"
                " OR (type = 'user' AND EXISTS (SELECT 1 FROM " CONTENT("claude_rec.line") " x WHERE " BLOCK_TYPE("x")
                "   = 'tool_result' AND json_extract(x.value, '$.tool_use_id') IN (SELECT id FROM claude_use))))",
                "i", NULL, rest[i]) != 0 ||
            (sqlite3_changes(s->db) > 0 &&
             run(s,
                 "INSERT OR IGNORE INTO claude_use SELECT json_extract(x.value, '$.id') FROM claude_rec r, " CONTENT("r.line") " x"
                 " WHERE r.n = ?1 AND r.type = 'assistant' AND " BLOCK_TYPE("x") " = 'tool_use'",
                 "i", NULL, rest[i]) != 0)) {
            free(rest);
            return -1;
        }
    }
    free(rest);
    return run(s,
               "INSERT OR IGNORE INTO claude_res SELECT json_extract(x.value, '$.tool_use_id') FROM claude_rec r, " CONTENT("r.line")
               " x WHERE r.kept AND r.type = 'user' AND " BLOCK_TYPE("x") " = 'tool_result'",
               "", NULL);
}


/* ---- writing the journal ------------------------------------------------- */

static int close_request(importer *im) {
    sqlite3_int64 sub = im->sub;
    if (!sub) {
        return 0;
    }
    im->sub = 0;
    im->out->requests++;
    return im->answered ? run(im->s, "UPDATE pic_submission SET status = 'answered' WHERE id = ?", "i", NULL, sub)
                        : run(im->s, "UPDATE pic_submission SET status = 'failed', error = 'imported without a reply' WHERE id = ?",
                              "i", NULL, sub);
}

/* The user text gathered as a new request, the open one finished. */
static int open_request(importer *im) {
    char key[96];
    if (close_request(im) != 0) {
        return -1;
    }
    (void)snprintf(key, sizeof key, "import-claude-%s-%lld-%ld", im->session, im->now_ns, im->out->requests);
    if (run(im->s, "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES(?, ?, 'admitted', ?)", "ttt",
            NULL, key, im->user.buf, im->session) != 0) {
        return -1;
    }
    im->sub = sqlite3_last_insert_rowid(im->s->db);
    im->last = im->sub;
    im->turn = 0;
    im->answered = 0;
    if (run(im->s, "INSERT INTO pic_entry(submission_id, kind, body) VALUES(?, 'user', ?)", "it", NULL, im->sub, im->user.buf) !=
        0) {
        return -1;
    }
    buf_clear(&im->user);
    return 0;
}

/* The gathered reply as an entry: with tool calls, a turn whose results
 * follow; without, the request's answer. */
static int write_reply(importer *im) {
    const char *kind = im->reply_calls ? "assistant" : "answer";
    buf body = {NULL, 0, 0};
    sqlite3_int64 seq;
    int rc;
    if (!im->reply.len) {
        return 0; /* only thinking */
    }
    if (buf_add(&body, "[", 1) != 0 || buf_add(&body, im->reply.buf, im->reply.len) != 0 || buf_add(&body, "]", 1) != 0) {
        free(body.buf);
        return oom(im->s);
    }
    rc = run(im->s,
             "INSERT INTO pic_entry(submission_id, kind, body, native, provider, api, model)"
             " VALUES(?1, ?2, ?3, ?3, 'anthropic', 'anthropic-messages', 'unknown')",
             "itt", NULL, im->sub, kind, body.buf);
    free(body.buf);
    if (rc != 0) {
        return -1;
    }
    seq = sqlite3_last_insert_rowid(im->s->db);
    if (run(im->s,
            "INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, stop_reason, purpose)"
            " VALUES(?, ?, 1, 'done', ?, ?, 'reply')",
            "iiit", NULL, im->sub, (sqlite3_int64)++im->turn, seq, im->reply_calls ? "toolUse" : "stop") != 0) {
        return -1;
    }
    if (im->reply_calls) {
        im->batch = seq;
    } else {
        im->answered = 1;
    }
    buf_clear(&im->reply);
    im->reply_calls = 0;
    return 0;
}

/* The open batch's effects, done, and their results in call order; the
 * extra text after the last. */
static int close_batch(importer *im) {
    if (!im->batch) {
        return 0;
    }
    if (run(im->s, "UPDATE claude_call SET result = 'error: no result in the transcript', is_error = 1 WHERE result IS NULL", "",
            NULL) != 0 ||
        (im->extra.len && run(im->s,
                              "UPDATE claude_call SET result = result || char(10) || char(10) || ?1"
                              " WHERE ordinal = (SELECT max(ordinal) FROM claude_call)",
                              "t", NULL, im->extra.buf) != 0) ||
        run(im->s,
            "INSERT INTO pic_effect(entry_seq, ordinal, call_id, tool, input, replay_safe, state, result, is_error)"
            " SELECT ?1, ordinal, id, tool, input, tool IN ('read', 'write', 'edit'), 'done', result, is_error FROM claude_call"
            " ORDER BY ordinal",
            "i", NULL, im->batch) != 0 ||
        run(im->s,
            "INSERT INTO pic_entry(submission_id, kind, body, effect_id) SELECT ?1, 'tool_result', result, id FROM pic_effect"
            " WHERE entry_seq = ?2 ORDER BY ordinal",
            "ii", NULL, im->sub, im->batch) != 0 ||
        run(im->s, "DELETE FROM claude_call", "", NULL) != 0) {
        return -1;
    }
    im->batch = 0;
    buf_clear(&im->extra);
    return 0;
}

/* Claude Code's tool calls as pic's: the tool and its arguments (Pi's
 * schemas) as {"tool","args"}, NULL when the tool is not one of pic's or
 * the call lacks what pic's tool requires. ?1 is the tool_use block. */
static const char map_sql[] =
    "WITH i(v) AS (SELECT CASE WHEN json_type(?1, '$.input') = 'object' THEN json_extract(?1, '$.input') END),"
    " m(tool, args) AS (SELECT CASE json_extract(?1, '$.name') WHEN 'Bash' THEN 'bash' WHEN 'Read' THEN 'read'"
    "   WHEN 'Edit' THEN 'edit' WHEN 'MultiEdit' THEN 'edit' WHEN 'Write' THEN 'write' WHEN 'Grep' THEN 'grep'"
    "   WHEN 'Glob' THEN 'find' WHEN 'LS' THEN 'ls' END,"
    "  CASE json_extract(?1, '$.name')"
    "   WHEN 'Bash' THEN json_patch('{}', json_object('command', json_extract(v, '$.command'), 'timeout',"
    "     CASE WHEN json_type(v, '$.timeout') IN ('integer', 'real') THEN CAST((json_extract(v, '$.timeout') + 999) / 1000 AS INTEGER) END))"
    "   WHEN 'Read' THEN json_patch('{}', json_object('path', json_extract(v, '$.file_path'), 'offset', json_extract(v, '$.offset'),"
    "     'limit', json_extract(v, '$.limit')))"
    "   WHEN 'Edit' THEN json_object('path', json_extract(v, '$.file_path'), 'edits', json_array(json_object("
    "     'oldText', json_extract(v, '$.old_string'), 'newText', json_extract(v, '$.new_string'))))"
    "   WHEN 'MultiEdit' THEN json_object('path', json_extract(v, '$.file_path'), 'edits', json((SELECT json_group_array(json_object("
    "     'oldText', CASE WHEN e.type = 'object' THEN json_extract(e.value, '$.old_string') END,"
    "     'newText', CASE WHEN e.type = 'object' THEN json_extract(e.value, '$.new_string') END)) FROM json_each(v, '$.edits') e)))"
    "   WHEN 'Write' THEN json_object('path', json_extract(v, '$.file_path'), 'content', json_extract(v, '$.content'))"
    "   WHEN 'Grep' THEN json_patch('{}', json_object('pattern', json_extract(v, '$.pattern'), 'path', json_extract(v, '$.path'),"
    "     'glob', json_extract(v, '$.glob'), 'ignoreCase', CASE WHEN json_extract(v, '$.\"-i\"') THEN json('true') END,"
    "     'context', coalesce(json_extract(v, '$.\"-C\"'), json_extract(v, '$.context')), 'limit', json_extract(v, '$.head_limit')))"
    "   WHEN 'Glob' THEN json_patch('{}', json_object('pattern', json_extract(v, '$.pattern'), 'path', json_extract(v, '$.path')))"
    "   WHEN 'LS' THEN json_patch('{}', json_object('path', json_extract(v, '$.path')))"
    "  END FROM i WHERE v IS NOT NULL)"
    " SELECT json_object('tool', tool, 'args', json(args)) FROM m WHERE tool IS NOT NULL AND CASE tool"
    "  WHEN 'bash' THEN json_type(args, '$.command') = 'text'"
    "  WHEN 'read' THEN json_type(args, '$.path') = 'text'"
    "  WHEN 'write' THEN json_type(args, '$.path') = 'text' AND json_type(args, '$.content') = 'text'"
    "  WHEN 'edit' THEN json_type(args, '$.path') = 'text' AND json_array_length(args, '$.edits') > 0 AND NOT EXISTS"
    "   (SELECT 1 FROM json_each(args, '$.edits') e WHERE json_type(e.value, '$.oldText') IS NOT 'text'"
    "    OR json_type(e.value, '$.newText') IS NOT 'text')"
    "  WHEN 'grep' THEN json_type(args, '$.pattern') = 'text'"
    "  WHEN 'find' THEN json_type(args, '$.pattern') = 'text'"
    "  ELSE 1 END";

/* A tool_use block into the gathered reply: pic's tool call when pic has the
 * tool and the transcript its result, else text. */
static int add_call(importer *im, const char *block) {
    char *mapped = NULL, *hit = NULL, *item = NULL;
    int rc = -1, known = 0;
    if (run(im->s, map_sql, "t", &mapped, block) != 0 ||
        run(im->s, "SELECT 1 FROM claude_res WHERE id = json_extract(?1, '$.id')", "t", &hit, block) != 0) {
        goto out;
    }
    if (mapped && hit) {
        if (run(im->s, "INSERT OR IGNORE INTO claude_seen VALUES(json_extract(?1, '$.id'))", "t", NULL, block) != 0) {
            goto out;
        }
        known = sqlite3_changes(im->s->db) == 1; /* a repeated id is text */
    }
    if (known) {
        if (run(im->s,
                "INSERT INTO claude_call(id, ordinal, tool, input) VALUES(json_extract(?1, '$.id'), ?2, json_extract(?3, '$.tool'),"
                " json(json_extract(?3, '$.args')))",
                "tit", NULL, block, (sqlite3_int64)im->reply_calls, mapped) != 0 ||
            run(im->s,
                "SELECT json_object('type', 'toolCall', 'id', json_extract(?1, '$.id'), 'name', json_extract(?2, '$.tool'),"
                " 'arguments', json(json_extract(?2, '$.args')))",
                "tt", &item, block, mapped) != 0) {
            goto out;
        }
        im->reply_calls++;
        im->out->calls++;
    } else {
        if (run(im->s,
                "SELECT json_object('type', 'text', 'text', '[tool ' || coalesce(json_extract(?1, '$.name'), '?') || ': ' ||"
                " CASE WHEN json_type(?1, '$.input') IN ('object', 'array') THEN json_extract(?1, '$.input')"
                " ELSE json_quote(json_extract(?1, '$.input')) END || ']')",
                "t", &item, block) != 0) {
            goto out;
        }
        im->out->text_calls++;
    }
    if (!item || buf_join(&im->reply, ",", item) != 0) {
        oom(im->s);
        goto out;
    }
    rc = 0;
out:
    free(mapped);
    free(hit);
    free(item);
    return rc;
}

/* An assistant record: its text and tool calls join the reply being
 * gathered, which a pending user text first makes a request for. */
static int assistant_record(importer *im, const char *line) {
    sqlite3_stmt *q = NULL;
    int step, rc = 0;
    if (close_batch(im) != 0 || (im->user.len && open_request(im) != 0)) {
        return -1;
    }
    if (!im->sub || im->answered) {
        return 0; /* no request to reply to: before the first user text */
    }
    if (sqlite3_prepare_v2(im->s->db, "SELECT " BLOCK_TYPE("x") ", x.value FROM " CONTENT("?1") " x ORDER BY x.key", -1, &q,
                           NULL) != SQLITE_OK) {
        return sql_fail(im->s);
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *type = (const char *)sqlite3_column_text(q, 0);
        const char *block = (const char *)sqlite3_column_text(q, 1);
        if (!type || !block) {
            continue;
        }
        if (strcmp(type, "tool_use") == 0) {
            rc = add_call(im, block);
        } else if (strcmp(type, "text") == 0) { /* thinking and the rest are left out */
            char *item = NULL;
            rc = run(im->s,
                     "SELECT json_object('type', 'text', 'text', json_extract(?1, '$.text'))"
                     " WHERE json_type(?1, '$.text') = 'text' AND json_extract(?1, '$.text') != ''",
                     "t", &item, block);
            if (rc == 0 && item && buf_join(&im->reply, ",", item) != 0) {
                rc = oom(im->s);
            }
            free(item);
        }
    }
    if (rc == 0 && step != SQLITE_DONE) {
        rc = sql_fail(im->s);
    }
    sqlite3_finalize(q);
    return rc;
}

/* A user record: results of the batch's calls are kept for it, and the rest
 * becomes text, after the batch's results when the record carries results,
 * else the next request's. */
static int user_record(importer *im, const char *line) {
    sqlite3_stmt *q = NULL;
    buf parts = {NULL, 0, 0};
    int step, rc = 0, results = 0, matched = 0;
    if (sqlite3_prepare_v2(
            im->s->db,
            "SELECT " BLOCK_TYPE("x") ", CASE WHEN x.type = 'text' THEN x.value WHEN x.type != 'object' THEN NULL"
            " WHEN " BLOCK_TYPE("x") " = 'text' THEN json_extract(x.value, '$.text')"
            " WHEN " BLOCK_TYPE("x") " = 'tool_result' THEN CASE json_type(x.value, '$.content')"
            "   WHEN 'text' THEN json_extract(x.value, '$.content')"
            "   WHEN 'array' THEN coalesce((SELECT group_concat(CASE WHEN c.type = 'text' THEN c.value WHEN c.type != 'object' THEN NULL"
            "     WHEN json_extract(c.value, '$.type') = 'text' THEN json_extract(c.value, '$.text')"
            "     ELSE '[' || coalesce(json_extract(c.value, '$.type'), 'content') || ' omitted]' END, char(10))"
            "     FROM json_each(x.value, '$.content') c), '')"
            "   ELSE '' END"
            " ELSE '[' || coalesce(" BLOCK_TYPE("x") ", 'content') || ' omitted]' END,"
            " CASE WHEN x.type = 'object' THEN json_extract(x.value, '$.tool_use_id') END,"
            " CASE WHEN x.type = 'object' THEN coalesce(json_extract(x.value, '$.is_error'), 0) END"
            " FROM " CONTENT("?1") " x ORDER BY x.key",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(im->s);
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *type = (const char *)sqlite3_column_text(q, 0);
        const char *text = (const char *)sqlite3_column_text(q, 1);
        const char *id = (const char *)sqlite3_column_text(q, 2);
        int is_error = sqlite3_column_int(q, 3) != 0;
        if (type && strcmp(type, "tool_result") == 0) {
            results = 1;
            if (id && run(im->s, "UPDATE claude_call SET result = ?1, is_error = ?2 WHERE id = ?3 AND result IS NULL", "tit", NULL,
                          text ? text : "", (sqlite3_int64)is_error, id) != 0) {
                rc = -1;
                break;
            }
            if (id && sqlite3_changes(im->s->db) == 1) {
                matched = 1;
                continue;
            }
            if (buf_join(&parts, "\n", is_error ? "[result (error): " : "[result: ") != 0 ||
                buf_add(&parts, text ? text : "", text ? strlen(text) : 0) != 0 || buf_add(&parts, "]", 1) != 0) {
                rc = oom(im->s);
            }
        } else if (text && *text && buf_join(&parts, "\n", text) != 0) {
            rc = oom(im->s);
        }
    }
    if (rc == 0 && step != SQLITE_DONE) {
        rc = sql_fail(im->s);
    }
    sqlite3_finalize(q);
    if (rc == 0 && (matched || parts.len)) {
        if (im->reply.len) {
            rc = write_reply(im);
        }
        if (rc == 0 && im->batch && results) {
            rc = parts.len && buf_join(&im->extra, "\n\n", parts.buf) != 0 ? oom(im->s) : 0;
        } else if (rc == 0) {
            rc = close_batch(im) != 0 || (parts.len && buf_join(&im->user, "\n\n", parts.buf) != 0) ? -1 : 0;
        }
    }
    free(parts.buf);
    return rc;
}

/* The kept messages, in file order, into the conversation. */
static int replay(importer *im) {
    sqlite3_stmt *q = NULL;
    int step, rc = 0;
    if (sqlite3_prepare_v2(im->s->db,
                           "SELECT type, line FROM claude_rec WHERE kept AND type IN ('user', 'assistant')"
                           " AND NOT coalesce(json_extract(line, '$.isMeta'), 0)"
                           " AND NOT (type = 'assistant' AND (coalesce(json_extract(line, '$.isApiErrorMessage'), 0)"
                           "   OR json_extract(line, '$.message.model') IS '<synthetic>')) ORDER BY n",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(im->s);
    }
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *type = (const char *)sqlite3_column_text(q, 0);
        const char *line = (const char *)sqlite3_column_text(q, 1);
        rc = strcmp(type, "user") == 0 ? user_record(im, line) : assistant_record(im, line);
    }
    if (rc == 0 && step != SQLITE_DONE) {
        rc = sql_fail(im->s);
    }
    sqlite3_finalize(q);
    if (rc == 0 && im->reply.len && im->sub && !im->answered) {
        rc = write_reply(im);
    }
    if (rc == 0) {
        rc = close_batch(im) != 0 || (im->user.len && open_request(im) != 0) || close_request(im) != 0 ? -1 : 0;
    }
    return rc;
}

int pic_import_claude(pic_store *s, FILE *in, const char *until, char *session_out, size_t cap, pic_claude_import *out) {
    importer im;
    char *session = NULL, *usage = NULL;
    int rc = -1;
    memset(&im, 0, sizeof im);
    memset(out, 0, sizeof *out);
    out->usage = -1;
    im.s = s;
    im.out = out;
    im.now_ns = (long long)pic_platform_get()->wall_ns();
    drop_tables(s);
    if (pic_exec(s, tables_sql) != 0) {
        return -1;
    }
    if (pic_begin(s) != 0) {
        drop_tables(s);
        return -1;
    }
    if (run(s,
            "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4))),"
            " CAST(unixepoch('subsec') * 1000 AS INTEGER), CAST(unixepoch('subsec') * 1000 AS INTEGER)) RETURNING id",
            "", &session) != 0 ||
        !session) {
        goto out;
    }
    (void)snprintf(im.session, sizeof im.session, "%s", session);
    if (load(s, in, until) != 0 || choose(s) != 0 || replay(&im) != 0) {
        goto out;
    }
    if (out->requests == 0) {
        (void)snprintf(s->err, sizeof s->err, "no user messages in the transcript (a Claude Code session JSONL is expected)");
        goto out;
    }
    /* The transcript's own context at the cut: its last reply's input. */
    if (run(s,
            "SELECT coalesce(json_extract(line, '$.message.usage.input_tokens'), 0)"
            " + coalesce(json_extract(line, '$.message.usage.cache_read_input_tokens'), 0)"
            " + coalesce(json_extract(line, '$.message.usage.cache_creation_input_tokens'), 0) FROM claude_rec"
            " WHERE kept AND type = 'assistant' AND json_type(line, '$.message.usage') = 'object'"
            " AND json_extract(line, '$.message.model') IS NOT '<synthetic>' ORDER BY n DESC LIMIT 1",
            "", &usage) != 0) {
        goto out;
    }
    if (usage) {
        out->usage = strtoll(usage, NULL, 10);
    }
    if (pic_context_tokens(s->db, im.last, &out->context_tokens) != 0) {
        sql_fail(s);
        goto out;
    }
    if (pic_commit(s) != 0) {
        goto out;
    }
    (void)snprintf(session_out, cap, "%s", im.session);
    rc = 0;
out:
    if (rc != 0) {
        pic_rollback(s);
    }
    drop_tables(s);
    free(session);
    free(usage);
    free(im.user.buf);
    free(im.reply.buf);
    free(im.extra.buf);
    return rc;
}

/* ---- the workspace -------------------------------------------------------- */

int pic_claude_cwd(const char *path, const char *until, char *out, size_t cap, char *err, size_t errcap) {
    sqlite3 *db = NULL;
    sqlite3_stmt *q = NULL;
    FILE *in = fopen(path, "r");
    char *line = NULL;
    size_t linecap = 0;
    int found = 0;
    out[0] = '\0';
    if (!in) {
        (void)snprintf(err, errcap, "cannot read %s", path);
        return -1;
    }
    if (sqlite3_open(":memory:", &db) != SQLITE_OK ||
        sqlite3_prepare_v2(db, "SELECT json_extract(?1, '$.uuid'), json_extract(?1, '$.cwd') WHERE json_valid(?1)", -1, &q,
                           NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "sql: %s", db ? sqlite3_errmsg(db) : "out of memory");
        sqlite3_close(db);
        fclose(in);
        return -1;
    }
    while (getline(&line, &linecap, in) >= 0) {
        const char *uuid, *cwd;
        sqlite3_reset(q);
        sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) != SQLITE_ROW) {
            continue;
        }
        uuid = (const char *)sqlite3_column_text(q, 0);
        if (until && uuid && strcmp(uuid, until) == 0) {
            found = 1;
            break;
        }
        if ((cwd = (const char *)sqlite3_column_text(q, 1)) && *cwd) {
            (void)snprintf(out, cap, "%s", cwd);
        }
    }
    sqlite3_finalize(q);
    sqlite3_close(db);
    free(line);
    fclose(in);
    if (until && !found) {
        (void)snprintf(err, errcap, "no record %s in the transcript", until);
        return -1;
    }
    if (!out[0]) {
        (void)snprintf(err, errcap, "the transcript records no cwd; name the workspace with --workspace");
        return -1;
    }
    return 0;
}