/* 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" 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; a reply's usage normalised across the * APIs (Anthropic leaves cache tokens out of input_tokens). */ #define TOKENS_SQL \ "(CASE e.kind WHEN 'user' THEN length(e.body) WHEN 'tool_result' THEN length(e.body)" \ " WHEN 'instructions' 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 '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'), '')" \ " 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; 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; } } } /* 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(?3, '{}'), '$.readFiles')" " UNION ALL SELECT value, 1 FROM json_each(coalesce(?3, '{}'), '$.modifiedFiles'))," " 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', (SELECT json_group_array(path) FROM r)," " 'modifiedFiles', (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)", -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); } 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; } 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, 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 >= PIC_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; }