/* 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 #include #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 " " 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]: ' || char(10) || e.body || char(10) ||" \ " ''" \ " 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 '' || char(10) || group_concat(path, char(10)) || char(10) || ''" \ " FROM r HAVING count(*) > 0)," \ " (SELECT '' || char(10) || group_concat(path, char(10)) || char(10) || ''" \ " 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, "\n"); serialize(p, rows, 0, history_end); sqlite3_str_appendall(p, "\n\n\n"); if (summary) { sqlite3_str_appendf(p, "\n%s\n\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, "\n"); serialize(p, rows, first, n); sqlite3_str_appendall(p, "\n\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; }