Skip to content
pi-c Artifact [d93b6810d5]
Login

Artifact [d93b6810d5]

Artifact d93b6810d50a4dc40c4a4f7a49f59f5e7aaa2bfc5115787ab03bbae63958a570:


/* Compaction planning: Pi's algorithm (packages/coding-agent/src/core/
 * compaction), over the conversation path in the journal. The loop runs the
 * plan: the summary requests, journaled like replies, then the entry. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "compact.h"
#include "userdb.h"

const char pic_summary_system_prompt[] =
    "You are a context summarization assistant. Your task is to read a conversation between a user and an AI "
    "assistant, then produce a structured summary following the exact format specified.\n\n"
    "Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the "
    "structured summary.";

static const char summarization_prompt[] =
    "The messages above are a conversation to summarize. Create a structured context checkpoint summary that "
    "another LLM will use to continue the work.\n\n"
    "Use this EXACT format:\n\n"
    "## Goal\n"
    "[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n"
    "## Constraints & Preferences\n"
    "- [Any constraints, preferences, or requirements mentioned by user]\n"
    "- [Or \"(none)\" if none were mentioned]\n\n"
    "## Progress\n"
    "### Done\n"
    "- [x] [Completed tasks/changes]\n\n"
    "### In Progress\n"
    "- [ ] [Current work]\n\n"
    "### Blocked\n"
    "- [Issues preventing progress, if any]\n\n"
    "## Key Decisions\n"
    "- **[Decision]**: [Brief rationale]\n\n"
    "## Next Steps\n"
    "1. [Ordered list of what should happen next]\n\n"
    "## Critical Context\n"
    "- [Any data, examples, or references needed to continue]\n"
    "- [Or \"(none)\" if not applicable]\n\n"
    "Keep each section concise. Preserve exact file paths, function names, and error messages.";

static const char update_summarization_prompt[] =
    "The messages above are NEW conversation messages to incorporate into the existing summary provided in "
    "<previous-summary> tags.\n\n"
    "Update the existing structured summary with new information. RULES:\n"
    "- PRESERVE all existing information from the previous summary\n"
    "- ADD new progress, decisions, and context from the new messages\n"
    "- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n"
    "- UPDATE \"Next Steps\" based on what was accomplished\n"
    "- PRESERVE exact file paths, function names, and error messages\n"
    "- If something is no longer relevant, you may remove it\n\n"
    "Use this EXACT format:\n\n"
    "## Goal\n"
    "[Preserve existing goals, add new ones if the task expanded]\n\n"
    "## Constraints & Preferences\n"
    "- [Preserve existing, add new ones discovered]\n\n"
    "## Progress\n"
    "### Done\n"
    "- [x] [Include previously done items AND newly completed items]\n\n"
    "### In Progress\n"
    "- [ ] [Current work - update based on progress]\n\n"
    "### Blocked\n"
    "- [Current blockers - remove if resolved]\n\n"
    "## Key Decisions\n"
    "- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n"
    "## Next Steps\n"
    "1. [Update based on current state]\n\n"
    "## Critical Context\n"
    "- [Preserve important context, add new if needed]\n\n"
    "Keep each section concise. Preserve exact file paths, function names, and error messages.";

static const char turn_prefix_prompt[] =
    "The messages above are earlier context from an ongoing conversation. Later messages are stored separately "
    "and do not need to be reconstructed.\n\n"
    "Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be "
    "placed before the later messages so the conversation can continue with the necessary context.\n\n"
    "## Original Request\n"
    "[What did the user ask for?]\n\n"
    "## Progress So Far\n"
    "- [Key decisions and work completed in these messages]\n\n"
    "## Context Needed to Continue\n"
    "- [Information from these messages needed to understand the later work]\n\n"
    "Only summarize information explicitly present above. Do not infer or recreate later messages.";

/* One entry of the context, in order (the summary itself is not a row). */
typedef struct {
    sqlite3_int64 seq, tokens, usage; /* usage: the reply's reported context, 0 if none or stale */
    int cut, turn_start;              /* Pi: a valid cut point; starts a turn */
    char *text;                       /* Pi's serialization, NULL when it serializes to nothing */
} row;

static void free_rows(row *rows, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(rows[i].text);
    }
    free(rows);
}

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

/* chars/4 rounded up, as Pi estimates, an image counting 4800 chars; a
 * reply's usage normalised across the APIs (Anthropic leaves cache tokens
 * out of input_tokens). */
#define TOKENS_SQL                                                                                                 \
    "(CASE WHEN e.kind IN ('user','tool_result') THEN length(e.body)"                                              \
    "   + 4800 * (SELECT count(*) FROM pic_attachment r WHERE r.entry_seq = e.seq)"                               \
    " WHEN e.kind IN ('instructions','hook','compaction','branch_summary') THEN length(e.body)"                                \
    " ELSE (SELECT coalesce(sum(CASE json_extract(value,'$.type') WHEN 'text' THEN length(json_extract(value,'$.text'))" \
    "   WHEN 'thinking' THEN length(coalesce(json_extract(value,'$.thinking'),''))"                                 \
    "   WHEN 'toolCall' THEN length(json_extract(value,'$.name')) + length(json(json_extract(value,'$.arguments')))" \
    "   ELSE 0 END), 0) FROM json_each(e.body)) END + 3) / 4"
#define USAGE_SQL                                                                                                  \
    "CASE WHEN v.fresh AND e.kind IN ('assistant','answer') THEN (SELECT coalesce(json_extract(g.usage,'$.total_tokens')," \
    " coalesce(json_extract(g.usage,'$.input_tokens'), json_extract(g.usage,'$.prompt_tokens'), 0)"               \
    " + coalesce(json_extract(g.usage,'$.output_tokens'), json_extract(g.usage,'$.completion_tokens'), 0)"        \
    " + coalesce(json_extract(g.usage,'$.cache_read_input_tokens'), 0)"                                            \
    " + coalesce(json_extract(g.usage,'$.cache_creation_input_tokens'), 0))"                                       \
    " FROM pic_generation g WHERE g.entry_seq = e.seq AND g.state = 'done' AND g.purpose = 'reply') END"
/* Pi's serializeConversation, one entry: thinking left out, tool results cut
 * at 2000 characters, tool calls as name(key=JSON, ...). */
#define SERIALIZE_SQL                                                                                              \
    "CASE e.kind"                                                                                                  \
    " WHEN 'user' THEN CASE WHEN e.body != '' THEN '[User]: ' || e.body END"                                       \
    " WHEN 'instructions' THEN '[User]: <project_instructions_update>' || char(10) || e.body || char(10) ||"       \
    "   '</project_instructions_update>'"                                                                          \
    " WHEN 'hook' THEN '[User]: ' || e.body"                                                                         \
    " WHEN 'compaction' THEN '[User]: ' || " PIC_SUMMARY_SQL("e.body")                                                \
    " WHEN 'branch_summary' THEN '[User]: ' || " PIC_BRANCH_SUMMARY_SQL("e.body")                                     \
    " WHEN 'tool_result' THEN CASE WHEN e.body != '' THEN '[Tool result]: ' || CASE WHEN length(e.body) <= 2000"   \
    "   THEN e.body ELSE substr(e.body, 1, 2000) || char(10) || char(10) || '[... ' || (length(e.body) - 2000) ||" \
    "   ' more characters truncated]' END END"                                                                     \
    " ELSE nullif(coalesce((SELECT '[Assistant]: ' || group_concat(json_extract(value,'$.text'), char(10))"              \
    "     FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text' HAVING count(*) > 0), '')"            \
    "   || CASE WHEN EXISTS (SELECT 1 FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text')"         \
    "     AND EXISTS (SELECT 1 FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'toolCall')"            \
    "     THEN char(10) || char(10) ELSE '' END"                                                                   \
    "   || coalesce((SELECT '[Assistant tool calls]: ' || group_concat(json_extract(c.value,'$.name') || '(' ||"   \
    "     coalesce((SELECT group_concat(a.key || '=' || CASE a.type WHEN 'text' THEN json_quote(a.value)"           \
    "       WHEN 'true' THEN 'true' WHEN 'false' THEN 'false' WHEN 'null' THEN 'null' ELSE a.value END, ', ')"     \
    "       FROM json_each(c.value, '$.arguments') a), '') || ')', '; ')"                                          \
    "     FROM json_each(e.body) c WHERE json_extract(c.value,'$.type') = 'toolCall' HAVING count(*) > 0), ''), '')" \
    " END"

static int load_rows(sqlite3 *db, int64_t submission, row **out, size_t *count) {
    sqlite3_stmt *q = NULL;
    row *rows = NULL;
    size_t n = 0, cap = 0;
    int step;
    *out = NULL;
    *count = 0;
    if (sqlite3_prepare_v2(db,
                           PIC_CONTEXT_CTE "SELECT e.seq, e.kind, " TOKENS_SQL ", " USAGE_SQL ", " SERIALIZE_SQL
                                           " FROM pic_entry e JOIN v ON v.seq = e.seq CROSS JOIN kk"
                                           " WHERE e.kind != 'compaction' ORDER BY e.seq",
                           -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, submission);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *kind = (const char *)sqlite3_column_text(q, 1);
        if (n == cap) {
            row *grown = realloc(rows, (cap = cap ? cap * 2 : 64) * sizeof *rows);
            if (!grown) {
                break;
            }
            rows = grown;
        }
        rows[n].seq = sqlite3_column_int64(q, 0);
        rows[n].tokens = sqlite3_column_int64(q, 2);
        rows[n].usage = sqlite3_column_int64(q, 3);
        rows[n].cut = strcmp(kind, "tool_result") != 0;
        rows[n].turn_start = strcmp(kind, "user") == 0 || strcmp(kind, "instructions") == 0 ||
                             strcmp(kind, "branch_summary") == 0;
        rows[n].text = dup_text(sqlite3_column_text(q, 4));
        n++;
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        free_rows(rows, n);
        return -1;
    }
    *out = rows;
    *count = n;
    return 0;
}

/* The latest compaction's summary and file lists, or NULLs. */
static int previous(sqlite3 *db, int64_t submission, char **summary, char **details) {
    sqlite3_stmt *q = NULL;
    *summary = *details = NULL;
    if (sqlite3_prepare_v2(db, PIC_CONTEXT_CTE "SELECT e.body, e.native FROM pic_entry e JOIN kk ON e.seq = kk.cseq", -1,
                           &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW) {
        *summary = dup_text(sqlite3_column_text(q, 0));
        *details = dup_text(sqlite3_column_text(q, 1));
    }
    sqlite3_finalize(q);
    return 0;
}

/* Pi's estimate: the last fresh reply's usage plus chars/4 for what followed;
 * without one, chars/4 for everything, the summary included. */
static sqlite3_int64 estimate(const row *rows, size_t n, const char *summary) {
    sqlite3_int64 tokens = 0;
    size_t i = n;
    while (i > 0 && rows[i - 1].usage <= 0) {
        i--;
    }
    if (i > 0) {
        tokens = rows[i - 1].usage;
    } else if (summary) {
        tokens = ((sqlite3_int64)strlen(summary) + 3) / 4;
    }
    for (; i < n; i++) {
        tokens += rows[i].tokens;
    }
    return tokens;
}

int pic_context_tokens(sqlite3 *db, int64_t submission, long *tokens) {
    row *rows;
    size_t n;
    char *summary, *details;
    if (load_rows(db, submission, &rows, &n) != 0 || previous(db, submission, &summary, &details) != 0) {
        return -1;
    }
    *tokens = (long)estimate(rows, n, summary);
    free_rows(rows, n);
    free(summary);
    free(details);
    return 0;
}

/* A builder's text in malloc'd memory (sqlite3_str uses SQLite's allocator). */
static char *finish(sqlite3_str *t) {
    int failed = sqlite3_str_errcode(t) != SQLITE_OK;
    char *s = sqlite3_str_finish(t), *out = failed ? NULL : dup_text((const unsigned char *)(s ? s : ""));
    sqlite3_free(s);
    return out;
}

static void serialize(sqlite3_str *out, const row *rows, size_t from, size_t to) {
    int any = 0;
    for (size_t i = from; i < to; i++) {
        if (rows[i].text) {
            sqlite3_str_appendall(out, any ? "\n\n" : "");
            sqlite3_str_appendall(out, rows[i].text);
            any = 1;
        }
    }
}

/* Pi's computeFileLists and formatFileOperations over ops(path, w), w for a
 * write or edit: the lists as JSON, then each section present. */
#define FILES_SQL                                                                                                  \
    " r(path) AS (SELECT DISTINCT path FROM ops WHERE path NOT IN (SELECT path FROM ops WHERE w) ORDER BY path),"   \
    " m(path) AS (SELECT DISTINCT path FROM ops WHERE w ORDER BY path)"                                            \
    " SELECT json_object('readFiles', json((SELECT json_group_array(path) FROM r)),"                               \
    "   'modifiedFiles', json((SELECT json_group_array(path) FROM m))),"                                           \
    " (SELECT '<read-files>' || char(10) || group_concat(path, char(10)) || char(10) || '</read-files>'"           \
    "   FROM r HAVING count(*) > 0),"                                                                              \
    " (SELECT '<modified-files>' || char(10) || group_concat(path, char(10)) || char(10) || '</modified-files>'"   \
    "   FROM m HAVING count(*) > 0)"

/* Steps a FILES_SQL query (and finalizes it): the JSON lists in *json, the
 * text appended to the summary in *suffix (both malloc'd). */
static int read_files(sqlite3 *db, sqlite3_stmt *q, char **json, char **suffix) {
    *json = *suffix = NULL;
    if (sqlite3_step(q) == SQLITE_ROW) {
        /* Pi: "\n\n" + the sections present, joined by a blank line. */
        sqlite3_str *t = sqlite3_str_new(db);
        for (int i = 1; i <= 2; i++) {
            if (sqlite3_column_text(q, i)) {
                sqlite3_str_appendf(t, "\n\n%s", (const char *)sqlite3_column_text(q, i));
            }
        }
        *json = dup_text(sqlite3_column_text(q, 0));
        *suffix = finish(t);
    }
    sqlite3_finalize(q);
    return *json && *suffix ? 0 : -1;
}

/* Read and modified files, as Pi tracks them: the previous compaction's
 * lists plus read, write and edit calls in the entries summarized now. */
static int file_lists(sqlite3 *db, int64_t submission, sqlite3_int64 first_kept, const char *details, char **json,
                      char **suffix) {
    sqlite3_stmt *q = NULL;
    *json = *suffix = NULL;
    if (sqlite3_prepare_v2(
            db,
            PIC_CONTEXT_CTE
            ", ops(path, w) AS ("
            "  SELECT json_extract(c.value,'$.arguments.path'), json_extract(c.value,'$.name') != 'read'"
            "  FROM pic_entry e JOIN v ON v.seq = e.seq, json_each(e.body) c"
            "  WHERE e.kind IN ('assistant','answer') AND e.seq < ?2 AND json_extract(c.value,'$.type') = 'toolCall'"
            "   AND json_extract(c.value,'$.name') IN ('read','write','edit')"
            "   AND json_type(c.value,'$.arguments.path') = 'text'"
            "  UNION ALL SELECT value, 0 FROM json_each(coalesce(json_extract(?3, '$.readFiles'), '[]'))"
            "  UNION ALL SELECT value, 1 FROM json_each(coalesce(json_extract(?3, '$.modifiedFiles'), '[]'))),"
            /* Lists from before 2026-11-19 were stored as JSON text inside the
             * object; json_extract gives the array text either way. */
            FILES_SQL,
            -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, first_kept);
    if (details) {
        sqlite3_bind_text(q, 3, details, -1, SQLITE_STATIC);
    }
    return read_files(db, q, json, suffix);
}

void pic_compaction_free(pic_compaction *c) {
    free(c->history_prompt);
    free(c->prefix_prompt);
    free(c->previous_summary);
    free(c->files);
    free(c->details);
    memset(c, 0, sizeof *c);
}

int pic_compaction_plan(sqlite3 *db, int64_t submission, const char *instructions, long keep_recent_tokens,
                        pic_compaction *c) {
    row *rows;
    size_t n, cut = 0, history_end, turn_start = 0;
    char *summary, *details;
    int split = 0, have_cut = 0;
    sqlite3_int64 acc = 0;
    memset(c, 0, sizeof *c);
    if (load_rows(db, submission, &rows, &n) != 0) {
        return -1;
    }
    if (previous(db, submission, &summary, &details) != 0) {
        free_rows(rows, n);
        return -1;
    }
    c->tokens_before = estimate(rows, n, summary);
    /* Walk back from the newest entry until keepRecentTokens are kept, then
     * cut at the nearest valid point at or after it (never a tool result). */
    for (size_t i = 0; i < n; i++) {
        if (rows[i].cut) {
            cut = i;
            have_cut = 1;
            break;
        }
    }
    if (have_cut) {
        for (size_t i = n; i-- > 0;) {
            if (rows[i].tokens == 0) {
                continue;
            }
            acc += rows[i].tokens;
            if (acc >= keep_recent_tokens) {
                size_t j = i;
                while (j < n && !rows[j].cut) {
                    j++;
                }
                if (j == n) {
                    for (j = n; j-- > 0 && !rows[j].cut;) {
                    }
                }
                cut = j;
                break;
            }
        }
        if (!rows[cut].turn_start) {
            for (size_t i = cut + 1; i-- > 0;) {
                if (rows[i].turn_start) {
                    turn_start = i;
                    split = 1;
                    break;
                }
            }
        }
    }
    history_end = split ? turn_start : cut;
    if (!have_cut || (history_end == 0 && (!split || turn_start == cut))) {
        free_rows(rows, n);
        free(summary);
        free(details);
        return 1; /* nothing to summarize */
    }
    c->first_kept_seq = rows[cut].seq;
    c->split = split;
    if (history_end > 0) {
        sqlite3_str *p = sqlite3_str_new(db);
        sqlite3_str_appendall(p, "<conversation>\n");
        serialize(p, rows, 0, history_end);
        sqlite3_str_appendall(p, "\n</conversation>\n\n");
        if (summary) {
            sqlite3_str_appendf(p, "<previous-summary>\n%s\n</previous-summary>\n\n", summary);
        }
        sqlite3_str_appendall(p, summary ? update_summarization_prompt : summarization_prompt);
        if (instructions && *instructions) {
            sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
        }
        c->history_prompt = finish(p);
    }
    if (split) {
        sqlite3_str *p = sqlite3_str_new(db);
        sqlite3_str_appendall(p, "# Conversation\n");
        serialize(p, rows, turn_start, cut);
        sqlite3_str_appendall(p, "\n\n# Instructions\n");
        sqlite3_str_appendall(p, turn_prefix_prompt);
        if (instructions && *instructions) {
            sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
        }
        c->prefix_prompt = finish(p);
    }
    free_rows(rows, n);
    c->previous_summary = summary;
    if ((history_end > 0 && !c->history_prompt) || (split && !c->prefix_prompt) ||
        file_lists(db, submission, c->first_kept_seq, details, &c->details, &c->files) != 0) {
        free(details);
        pic_compaction_free(c);
        return -1;
    }
    free(details);
    return 0;
}

/* A non-negative whole number at PATH of the JSON setting text, else DEF
 * (Pi refuses another value; pic keeps the default). The model's override
 * (modelOverrides["provider/model"]) wins when it has one. */
static long setting_tokens(sqlite3 *db, const char *json, const char *model, const char *field, long def) {
    sqlite3_stmt *q = NULL;
    long out = def;
    if (!json || sqlite3_prepare_v2(db,
                                    "SELECT coalesce((SELECT json_extract(o.value, '$.' || ?3) FROM json_each(?1, '$.modelOverrides') o"
                                    "   WHERE o.key = ?2 AND o.type = 'object' AND json_type(o.value, '$.' || ?3) = 'integer'"
                                    "   AND json_extract(o.value, '$.' || ?3) >= 0),"
                                    " CASE WHEN json_type(?1, '$.' || ?3) = 'integer' AND json_extract(?1, '$.' || ?3) >= 0"
                                    "   THEN json_extract(?1, '$.' || ?3) END)"
                                    " WHERE json_valid(?1) AND json_type(?1) = 'object'",
                                    -1, &q, NULL) != SQLITE_OK) {
        return def;
    }
    sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, model ? model : "", -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, field, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_INTEGER) {
        out = (long)sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

/* Whether the JSON setting text has false at PATH (Pi's `?? true`). */
static int setting_false(sqlite3 *db, const char *json, const char *path) {
    sqlite3_stmt *q = NULL;
    int out = 0;
    if (json && sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1, ?2) = 'false'", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        out = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

static int setting_true(sqlite3 *db, const char *json, const char *path) {
    sqlite3_stmt *q = NULL;
    int out = 0;
    if (json && sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1, ?2) = 'true'", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        out = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

void pic_compaction_settings_get(const char *model, pic_compaction_settings *out) {
    sqlite3 *db = pic_userdb(NULL, 0);
    char *json = db ? pic_setting("compaction") : NULL;
    out->enabled = !setting_false(db, json, "$.enabled");
    out->reserve_tokens = setting_tokens(db, json, model, "reserveTokens", PIC_RESERVE_TOKENS);
    out->keep_recent_tokens = setting_tokens(db, json, model, "keepRecentTokens", PIC_KEEP_RECENT_TOKENS);
    free(json);
}

void pic_branch_settings_get(pic_branch_settings *out) {
    sqlite3 *db = pic_userdb(NULL, 0);
    char *json = db ? pic_setting("branchSummary") : NULL;
    out->reserve_tokens = setting_tokens(db, json, NULL, "reserveTokens", PIC_BRANCH_RESERVE_TOKENS);
    out->skip_prompt = setting_true(db, json, "$.skipPrompt");
    free(json);
}

/* ---- branch summaries ----------------------------------------------------- */

static const char branch_summary_prompt[] =
    "Create a structured summary of this conversation branch for context when returning later.\n\n"
    "Use this EXACT format:\n\n"
    "## Goal\n"
    "[What was the user trying to accomplish in this branch?]\n\n"
    "## Constraints & Preferences\n"
    "- [Any constraints, preferences, or requirements mentioned]\n"
    "- [Or \"(none)\" if none were mentioned]\n\n"
    "## Progress\n"
    "### Done\n"
    "- [x] [Completed tasks/changes]\n\n"
    "### In Progress\n"
    "- [ ] [Work that was started but not finished]\n\n"
    "### Blocked\n"
    "- [Issues preventing progress, if any]\n\n"
    "## Key Decisions\n"
    "- **[Decision]**: [Brief rationale]\n\n"
    "## Next Steps\n"
    "1. [What should happen next to continue this work]\n\n"
    "Keep each section concise. Preserve exact file paths, function names, and error messages.";

const char pic_branch_summary_preamble[] =
    "The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n";

/* Pi's collectEntriesForBranchSummary: the entries on FROM's path below its
 * deepest common ancestor with TARGET's (?1 FROM, ?2 TARGET); entry numbers
 * grow down a path, so that ancestor is the largest number on both. */
#define BRANCH_CTE                                                                                                 \
    "WITH RECURSIVE o(seq) AS (SELECT ?1 UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN o ON x.seq = o.seq"   \
    "   WHERE x.parent_seq IS NOT NULL),"                                                                          \
    " t(seq) AS (SELECT ?2 UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN t ON x.seq = t.seq"                 \
    "   WHERE x.parent_seq IS NOT NULL),"                                                                          \
    " a(seq) AS (SELECT coalesce(max(o.seq), 0) FROM o JOIN t ON t.seq = o.seq),"                                  \
    " b(seq) AS (SELECT o.seq FROM o, a WHERE o.seq > a.seq)"

void pic_branch_free(pic_branch *b) {
    free(b->prompt);
    free(b->files);
    free(b->details);
    memset(b, 0, sizeof *b);
}

int pic_branch_plan(sqlite3 *db, sqlite3_int64 from, sqlite3_int64 target, long budget, const char *instructions,
                    pic_branch *b) {
    sqlite3_stmt *q = NULL;
    row *rows = NULL;
    size_t n = 0, cap = 0, first = 0, ops_from;
    int step, *is_summary = NULL;
    sqlite3_int64 total = 0;
    memset(b, 0, sizeof *b);
    /* Pi's prepareBranchEntries: tool results are left out (their calls say
     * enough); summaries are messages as convertToLlm makes them. */
    if (sqlite3_prepare_v2(db,
                           BRANCH_CTE " SELECT e.seq, e.kind, " TOKENS_SQL ", " SERIALIZE_SQL
                                      " FROM pic_entry e JOIN b ON b.seq = e.seq WHERE e.kind != 'tool_result' ORDER BY e.seq",
                           -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, from);
    sqlite3_bind_int64(q, 2, target);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *kind = (const char *)sqlite3_column_text(q, 1);
        if (n == cap) {
            row *grown = realloc(rows, (cap = cap ? cap * 2 : 64) * sizeof *rows);
            int *flags = realloc(is_summary, cap * sizeof *is_summary);
            if (grown) {
                rows = grown;
            }
            if (flags) {
                is_summary = flags;
            }
            if (!grown || !flags) {
                break;
            }
        }
        rows[n].seq = sqlite3_column_int64(q, 0);
        rows[n].tokens = sqlite3_column_int64(q, 2);
        rows[n].text = dup_text(sqlite3_column_text(q, 3));
        is_summary[n] = strcmp(kind, "compaction") == 0 || strcmp(kind, "branch_summary") == 0;
        n++;
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        free_rows(rows, n);
        free(is_summary);
        return -1;
    }
    if (n == 0) {
        free(rows);
        free(is_summary);
        return 1; /* nothing on the branch left */
    }
    /* Newest to oldest until the budget is spent; a summary that does not fit
     * still goes in while under 90% of it. File operations are taken from
     * the message that stopped the walk too, as Pi extracts them first. */
    first = n;
    ops_from = n;
    for (size_t i = n; i-- > 0;) {
        ops_from = i;
        if (budget > 0 && total + rows[i].tokens > budget) {
            if (is_summary[i] && (double)total < (double)budget * 0.9) {
                first = i;
                total += rows[i].tokens;
            }
            break;
        }
        first = i;
        total += rows[i].tokens;
    }
    free(is_summary);
    if (first < n) {
        sqlite3_str *p = sqlite3_str_new(db);
        sqlite3_str_appendall(p, "<conversation>\n");
        serialize(p, rows, first, n);
        sqlite3_str_appendall(p, "\n</conversation>\n\n");
        sqlite3_str_appendall(p, branch_summary_prompt);
        if (instructions && *instructions) {
            sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
        }
        b->prompt = finish(p);
        if (!b->prompt) {
            free_rows(rows, n);
            return -1;
        }
    }
    /* Files: read, write and edit calls from where the walk stopped, and the
     * lists of every earlier branch summary on the branch. */
    if (sqlite3_prepare_v2(
            db,
            BRANCH_CTE ", ops(path, w) AS ("
                       "  SELECT json_extract(c.value,'$.arguments.path'), json_extract(c.value,'$.name') != 'read'"
                       "  FROM pic_entry e JOIN b ON b.seq = e.seq, json_each(e.body) c"
                       "  WHERE e.kind IN ('assistant','answer') AND e.seq >= ?3 AND json_extract(c.value,'$.type') = 'toolCall'"
                       "   AND json_extract(c.value,'$.name') IN ('read','write','edit')"
                       "   AND json_type(c.value,'$.arguments.path') = 'text'"
                       "  UNION ALL SELECT r.value, 0 FROM pic_entry e JOIN b ON b.seq = e.seq,"
                       "   json_each(coalesce(json_extract(e.native, '$.readFiles'), '[]')) r WHERE e.kind = 'branch_summary'"
                       "  UNION ALL SELECT r.value, 1 FROM pic_entry e JOIN b ON b.seq = e.seq,"
                       "   json_each(coalesce(json_extract(e.native, '$.modifiedFiles'), '[]')) r WHERE e.kind = 'branch_summary'),"
                       FILES_SQL,
            -1, &q, NULL) != SQLITE_OK) {
        free_rows(rows, n);
        pic_branch_free(b);
        return -1;
    }
    sqlite3_bind_int64(q, 1, from);
    sqlite3_bind_int64(q, 2, target);
    sqlite3_bind_int64(q, 3, rows[ops_from].seq);
    free_rows(rows, n);
    if (read_files(db, q, &b->details, &b->files) != 0) {
        pic_branch_free(b);
        return -1;
    }
    return 0;
}

/* ---- lapse: the decision and its measurement ------------------------------ */

static int lapse_schema(sqlite3 *db) {
    return sqlite3_exec(db,
                        "CREATE TABLE IF NOT EXISTS pic_lapse("
                        "  submission_id INTEGER NOT NULL,"
                        "  turn INTEGER NOT NULL,"
                        "  session_id TEXT NOT NULL,"
                        "  decided_ms INTEGER NOT NULL,"
                        "  idle_seconds INTEGER NOT NULL,"
                        "  context_tokens INTEGER NOT NULL,"
                        "  arm TEXT NOT NULL CHECK(arm IN ('compact','holdout','small')),"
                        "  PRIMARY KEY(submission_id, turn))",
                        NULL, NULL, NULL) == SQLITE_OK
               ? 0
               : -1;
}

/* The holdout share: PIC_LAPSE_HOLDOUT, else the lapseHoldout setting, else
 * the default. main.c refuses a value outside 0 to 1 before any run. */
static double lapse_holdout(void) {
    const char *e = getenv("PIC_LAPSE_HOLDOUT");
    char *owned = NULL, *end = NULL;
    double h = PIC_LAPSE_HOLDOUT;
    const char *v = e && *e ? e : (pic_userdb(NULL, 0) ? (owned = pic_setting("lapseHoldout")) : NULL);
    if (v && *v) {
        double d = strtod(v, &end);
        if (end && !*end && d >= 0.0 && d <= 1.0) {
            h = d;
        }
    }
    free(owned);
    return h;
}

int pic_lapse_decide(sqlite3 *db, int64_t submission, int64_t turn, sqlite3_int64 idle, long tokens, long floor) {
    sqlite3_stmt *q = NULL;
    const char *arm = "compact";
    int out = -1;
    if (lapse_schema(db) != 0) {
        return -1;
    }
    if (tokens <= floor) {
        arm = "small";
    } else {
        double h = lapse_holdout();
        if (h > 0.0 &&
            sqlite3_prepare_v2(db, "SELECT (random() & 4294967295) / 4294967296.0", -1, &q, NULL) == SQLITE_OK &&
            sqlite3_step(q) == SQLITE_ROW && sqlite3_column_double(q, 0) < h) {
            arm = "holdout";
        }
        sqlite3_finalize(q);
        q = NULL;
    }
    /* the first arm kept for this request's turn stands */
    if (sqlite3_prepare_v2(db,
                           "INSERT OR IGNORE INTO pic_lapse(submission_id,turn,session_id,decided_ms,idle_seconds,context_tokens,arm)"
                           " SELECT ?1, ?2, session_id, CAST(unixepoch('subsec') * 1000 AS INTEGER), ?3, ?4, ?5"
                           " FROM pic_submission WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, turn);
    sqlite3_bind_int64(q, 3, idle);
    sqlite3_bind_int64(q, 4, tokens);
    sqlite3_bind_text(q, 5, arm, -1, SQLITE_STATIC);
    if (sqlite3_step(q) != SQLITE_DONE) {
        sqlite3_finalize(q);
        return -1;
    }
    sqlite3_finalize(q);
    if (sqlite3_prepare_v2(db, "SELECT arm = 'compact' FROM pic_lapse WHERE submission_id = ? AND turn = ?", -1, &q, NULL) ==
        SQLITE_OK) {
        sqlite3_bind_int64(q, 1, submission);
        sqlite3_bind_int64(q, 2, turn);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = sqlite3_column_int(q, 0);
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* A fixed-seed generator for the bootstrap, so a report reads the same twice. */
static unsigned long long lapse_rng(unsigned long long *x) {
    *x ^= *x << 13;
    *x ^= *x >> 7;
    *x ^= *x << 17;
    return *x;
}

static int cmp_double(const void *a, const void *b) {
    double x = *(const double *)a, y = *(const double *)b;
    return x < y ? -1 : x > y;
}

static double mean_of(const double *v, int n) {
    double t = 0.0;
    for (int k = 0; k < n; k++) {
        t += v[k];
    }
    return n ? t / n : 0.0;
}

#define LAPSE_MIN_ARM 5 /* lapses each arm needs before a comparison is shown */
#define LAPSE_RESAMPLES 4000

/* Each cold cache's window runs from its request's turn to the next cold
 * cache kept in the same session (or the session's end), so where a window
 * ends does not depend on its arm. Its cost is every done request in it,
 * summaries included. */
int pic_lapse_report(sqlite3 *db, int json, FILE *out) {
    sqlite3_stmt *q = NULL;
    double *cost[2] = {NULL, NULL}; /* 0 compact, 1 holdout */
    int n[2] = {0, 0}, cap[2] = {0, 0}, small = 0, rc = -1;
    double mean[2], ratio = 0, saved = 0, lo_r = 0, hi_r = 0, lo_s = 0, hi_s = 0;
    int enough;
    if (lapse_schema(db) != 0 ||
        sqlite3_prepare_v2(
            db,
            "WITH l AS (SELECT session_id, submission_id AS u, turn AS t, arm,"
            "   lead(submission_id) OVER w AS nu, lead(turn) OVER w AS nt"
            "   FROM pic_lapse WINDOW w AS (PARTITION BY session_id ORDER BY submission_id, turn))"
            " SELECT l.arm, (SELECT coalesce(sum(json_extract(g.usage, '$.pic_cost.total')), 0)"
            "   FROM pic_generation g JOIN pic_submission s ON s.id = g.submission_id"
            "   WHERE s.session_id = l.session_id AND g.state = 'done' AND json_valid(g.usage)"
            "   AND (g.submission_id > l.u OR (g.submission_id = l.u AND g.turn >= l.t))"
            "   AND (l.nu IS NULL OR g.submission_id < l.nu OR (g.submission_id = l.nu AND g.turn < l.nt)))"
            " FROM l",
            -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        const char *arm = (const char *)sqlite3_column_text(q, 0);
        int a = strcmp(arm, "compact") == 0 ? 0 : strcmp(arm, "holdout") == 0 ? 1 : -1;
        if (a < 0) {
            small++;
            continue;
        }
        if (n[a] == cap[a]) {
            double *grown = realloc(cost[a], sizeof(double) * (size_t)(cap[a] = cap[a] ? cap[a] * 2 : 16));
            if (!grown) {
                goto done;
            }
            cost[a] = grown;
        }
        cost[a][n[a]++] = sqlite3_column_double(q, 1);
    }
    mean[0] = mean_of(cost[0], n[0]);
    mean[1] = mean_of(cost[1], n[1]);
    enough = n[0] >= LAPSE_MIN_ARM && n[1] >= LAPSE_MIN_ARM && mean[1] > 0.0;
    if (enough) {
        double *rs = malloc(sizeof(double) * LAPSE_RESAMPLES), *ss = malloc(sizeof(double) * LAPSE_RESAMPLES);
        unsigned long long x = 0x9e3779b97f4a7c15ULL;
        if (!rs || !ss) {
            free(rs);
            free(ss);
            goto done;
        }
        for (int b = 0; b < LAPSE_RESAMPLES; b++) {
            double m[2];
            for (int a = 0; a < 2; a++) {
                double t = 0.0;
                for (int k = 0; k < n[a]; k++) {
                    t += cost[a][lapse_rng(&x) % (unsigned long long)n[a]];
                }
                m[a] = t / n[a];
            }
            rs[b] = m[1] > 0.0 ? m[0] / m[1] : 1.0;
            ss[b] = (m[1] - m[0]) * n[0];
        }
        qsort(rs, LAPSE_RESAMPLES, sizeof(double), cmp_double);
        qsort(ss, LAPSE_RESAMPLES, sizeof(double), cmp_double);
        lo_r = rs[LAPSE_RESAMPLES / 40];
        hi_r = rs[LAPSE_RESAMPLES - 1 - LAPSE_RESAMPLES / 40];
        lo_s = ss[LAPSE_RESAMPLES / 40];
        hi_s = ss[LAPSE_RESAMPLES - 1 - LAPSE_RESAMPLES / 40];
        ratio = mean[0] / mean[1];
        saved = (mean[1] - mean[0]) * n[0];
        free(rs);
        free(ss);
    }
    if (json) {
        fprintf(out, "{\"compacted\":%d,\"heldOut\":%d,\"small\":%d,\"meanCompacted\":%.6f,\"meanHeldOut\":%.6f", n[0], n[1],
                small, mean[0], mean[1]);
        if (enough) {
            fprintf(out, ",\"ratio\":%.4f,\"ratioLow\":%.4f,\"ratioHigh\":%.4f,\"saved\":%.4f,\"savedLow\":%.4f,\"savedHigh\":%.4f}\n",
                    ratio, lo_r, hi_r, saved, lo_s, hi_s);
        } else {
            fputs(",\"ratio\":null,\"saved\":null}\n", out);
        }
    } else {
        fprintf(out, "cold caches: %d compacted, %d held out, %d under the floor\n", n[0], n[1], small);
        if (n[0] + n[1] > 0) {
            fprintf(out, "cost from each to the next in its session: compacted $%.4f on average, held out $%.4f\n", mean[0],
                    mean[1]);
        }
        if (enough) {
            fprintf(out, "compacted / held out: %.2f (95%% interval %.2f to %.2f)\n", ratio, lo_r, hi_r);
            fprintf(out, "saved: $%.2f over %d compactions (95%% interval $%.2f to $%.2f)\n", saved, n[0], lo_s, hi_s);
        } else {
            fprintf(out, "not enough to compare yet: each arm needs %d (lapseHoldout sets how many are held out)\n",
                    LAPSE_MIN_ARM);
        }
    }
    rc = 0;
done:
    sqlite3_finalize(q);
    free(cost[0]);
    free(cost[1]);
    return rc;
}