# prune — Lossless Conversation Compactor > Trim conversation to essentials. Search everything. ## Overview `prune` is a deterministic, lossless compaction extension for pi. It replaces the default LLM-based summarization with algorithmic extraction that preserves: 1. **Brief transcript** — chronological flow with tool calls collapsed to one-liners 2. **Key facts** — extracted goals, files, blockers, preferences 3. **Lossless recall** — raw messages stay searchable via JSONL + `prune_recall` **Note on "lossless":** prune preserves original JSONL at the system level. Lossless refers to data integrity, not instant recall. The `prune_recall` tool (implemented as part of prune) provides programmatic search. ## Architecture ```text ┌─────────────────────────────────────────────────────────────┐ │ session_before_compact │ │ │ │ │ ▼ │ │ normalize(messages) → blocks │ │ │ │ │ ▼ │ │ extract(blocks) → ExtractOutput │ │ │ │ │ ▼ │ │ format(fresh ExtractOutput) → freshSummary │ │ │ │ │ ▼ │ │ merge(previousSummary, freshSummary) → finalSummary │ └─────────────────────────────────────────────────────────────┘ ``` ## Output Format ```text [Session Goal] - Fix the auth bug - Also: update token refresh logic [Files And Changes] - Modified: session.ts, auth.test.ts - Created: middleware.ts [Outstanding Context] - lint check still failing on line 42 [User Preferences] - Prefer TypeScript strict mode - Never commit with debug logs [Commits] - abc1234: Fix token refresh [Continue Now] - Current request: Fix the auth bug (#5) - Last action: edit session.ts (#9) - Next: continue current request; use prune_recall before redoing old work. --- [user] Fix the auth bug (#5) [assistant] Root cause found * bash "bun test" (#7) * edit "session.ts" (#9) ...(N earlier lines omitted) ─────────────────────────────────────────────────────────────── prune: 309 entries summarized; before 18.9k tok; raw kept 67 entries; split-prefix 0 Use prune_recall to search for prior work, decisions, and context from before this summary. Do not redo work already completed. ``` ## Sections | Section | Description | Merge Policy | | ----------------------- | ---------------------------------------- | ------------------------------------------------------------------------ | | `[Session Goal]` | Goals + scope changes from user messages | Sticky (accumulate, dedup, cap 8) | | `[Files And Changes]` | Modified, created, read files | Union by category, dedup, cap 10 each | | `[Outstanding Context]` | Errors, blockers, pending questions | Fresh (replace) | | `[User Preferences]` | prefer/never/always patterns | Sticky (accumulate, cap 15) | | `[Commits]` | Extracted git commits with hashes | Sticky (keep recent 8) | | `[Continue Now]` | Resume block from latest transcript tail | Fresh (replace) | | `---` | Brief transcript | Append fresh after previous, then cap tail (older first in final output) | ## Extract Algorithm ### 1. Normalize Map pi messages → blocks: - `user` — text content from user messages - `assistant` — text content from assistant messages - `tool_call` — tool name + args - `tool_result` — output, mark errors - `thinking` — skip ### 2. Build Sections #### Goals Extracted from user blocks. Algorithm (based on pi-vcc + real session analysis): ````typescript // Pseudo-code. Impl should use arrays + RegExp construction, not copy these multiline regexes directly. // First user block → collect up to 6 goals // Subsequent user blocks → detect scope changes // Patterns for goals: GOAL_VERB_RE = /\b(scan|check|fix|implement|add|create|build|refactor|debug| investigate|update|remove|delete|migrate|deploy|test|write|set up| spin|run|execute|verify|review|analyze|explain|describe|explore| call|use|switch|clean|lint|format)\b/i; // Scope change patterns: SCOPE_CHANGE_RE = /\b(also|instead|actually|change of plan|forget that| new task|switch to|now I want|pivot|let'?s do|stop .* and| while we'?re at it|between|for now)\b/i; // Noise filters: NOISE_SHORT_RE = /^(ok|yes|no|yep|nope|go|hi|hey|thanks?|thx|k|y|n| done|go ahead|looks good|sounds good|lgtm|sounds right| makes sense|sure|please|thank)\s*[.!?]*$/i; NON_GOAL_RE = /^\s*[\[│├└─╭╰─]|```|^\s*(=[A-Z_]+\(|function |const |let | var |import |export |class |async |await |interface |type )| ^(https?:\/\/|file:|\/[a-z])|^\s*```|\s*```\s*$|^\s*\| | ^\s*For each\b|\bin full\b[^\n]*\b(comments?|issues?|PRs?|linked)\b| ^@[\w\/.-]+\s*$/i; // Template signal (stop collecting at these): TEMPLATE_SIGNAL_RE = /^\s*(For each\b|Do NOT\b|Analyze and propose\b| If [Tt]ask|Output:\s*$|here'?s a|ticket:)/i; // Extract: // 1. Truncate at template signal // 2. Filter noise lines // 3. Filter non-goal patterns // 4. Collect from first block, scope-change only from subsequent ```` **Real session edge cases handled:** - Short messages: "yes", "done", "ok", "noop", "go" → filtered - Questions: usually transcript-only; task questions like "can you fix X?" may become goals - URLs: filtered via NON_GOAL_RE - Multi-part: "do X. also do Y." → captures scope change via "also" - Command templates: stopped at TEMPLATE_SIGNAL #### Files ```typescript // From tool_call args: // - edit/write → Modified/Created // - read → Read // - bash "git commit" → Commits extractFileFromArgs(toolName, args) → { modified, created, read } extractCommits(blocks) → [{ hash, message }, ...] ``` #### Context ```typescript // Errors from tool_result with isError // Blockers from assistant/user text matching BLOCKER_RE BLOCKER_RE = /\b(fail|broken|cannot|can't|won't work|blocked|blocker| not (fixed|resolved|working)|crash(es|ed|ing)?|still (broken|failing|wrong))\b/i; // Cap at 5 items ``` **Note:** Context is extracted fresh on each compaction, not merged. Old blockers are discarded when resolved. #### Preferences ```typescript // From user messages matching preference patterns // STRICT: require pattern in first 200 chars to avoid matching pasted content PREF_PATTERNS = [ /\bprefer(?:s|red|ring)?\s+\w/i, /\bdon'?t want\b/i, /\balways (?:use|do|run|prefer|keep|make|format|write|add|set|put|prefix|start|include|append)\b/i, /\bnever (?:use|do|run|push|commit|write|ignore|add|set|put|remove|delete|include|deploy)\b/i, /\bplease (?:use|avoid|keep|make|don'?t|do not|format|write)\b/i, /\b(?:style|format|language|naming)\s*[:=]\s*\S/i, ]; // Validation: // 1. Must be in first 200 chars of message (not buried in pasted content) // 2. Line length < 200 chars // 3. Not a question // 4. Cap at 1 per user block, 10 total ``` **Known limitations (false positive risk):** The preference extraction regex cannot distinguish user-authored instructions from: 1. **Quoted tool output** — agent-generated examples copied into a user message 2. **Pasted content** — user pasting code, logs, or external text 3. **Previous compaction output** — quoted compaction summaries in new messages 4. **Assistant suggestions** — content the assistant generated that user is quoting **Mitigation attempts:** - Stricter position requirement (first 200 chars) — catches direct pastes but not tool output - Line length cap (200 chars) — filters some noise - Question filter — avoids interrogative patterns **200-char heuristic analysis (from real sessions):** - User messages in real sessions average <500 chars - Pasted content (skill files, code blocks) averages 2000+ chars - The heuristic catches most direct preference pastes - It does NOT catch content extracted incorrectly from tool output or prior compactions **False positive example:** ```text "POV: You Angered the Wrong Cat 😈🐱 (POV format = engagement)" ``` This was in a compaction output and not found in user-authored messages scanned later. Most likely path: generated/test content became part of prior summary or quoted context, then preference regex preserved it. User later quoted it while reporting the false positive. **Acceptable tradeoff:** Preferences are hints, not facts. False positives in preferences are noisy but not harmful to compaction correctness. ### 3. Build Transcript ```typescript // Collapses tool calls to one-liners: // * bash "npm install" (#5) // * edit "src/main.ts" (#7) // Truncation: // - User: 256 chars, strip self-talk // - Assistant: 200 chars, strip self-talk // - Tool calls: 120 chars, compress bash // Collapse: // - Cap at toolCapPerTurn tool-call lines per user turn // - Errors are always kept ``` ### 4. Merge ```typescript merge(previousSummary: string | undefined, freshSummary: string): string { // Text merge using stable section headers. // Outstanding Context + Continue Now: REPLACE (fresh only) // Files: union by category + dedup // Goals/Preferences/Commits: union + dedup + cap // Transcript: previous brief + fresh brief, then cap tail // Footer/metadata: render once at end } ``` ## prune_recall Implemented as part of prune. Two surfaces share one search implementation: 1. `prune_recall` — registered tool, exposed to the LLM only after a prune compaction exists in the current branch 2. `/prune-recall` — command for the human, always available ```typescript prune_recall({ query: string, // plain text or regex string scope: 'lineage' | 'all', // active branch only or all entries in session file limit: number, // max results expand: number[], // expand exact source refs, e.g. [205, 270] }) ``` Searches session JSONL for matching entries. Returns structured results with context. ### Source refs - `#N` = 1-based `sourceIndex` assigned during `normalize()` from current branch order - Transcript refs and `expand` use same `#N` - `scope: 'lineage'` searches current branch/lineage and preserves `#N` mapping - `scope: 'all'` searches whole session file, including off-lineage branches; results include both `#N` when available and entry id - Refs are stable while branch history is append-only; export/import or tree navigation can change ordinal mapping ### Metadata footer ```text prune: 309 entries summarized; before 18.9k tok; raw kept 67 entries; split-prefix 0 ``` - `entries summarized` = messages passed to deterministic extraction, including old raw-tail entries moved into summary - `before N tok` = compaction event `tokensBefore`, if available - `raw kept` = branch entries kept after returned `firstKeptEntryId` - `split-prefix` = `turnPrefixMessages.length` ## Commands | Command | Description | | --------------------------- | ------------------------- | | `/prune` | Manual compaction trigger | | `/prune-recall ` | Search current lineage | | `/prune-recall all` | Search all branches | ## Settings ```json { "prune": { "sectionLimit": 8, "transcriptLimit": 60, "toolCapPerTurn": 8, "debug": false } } ``` ## Testing Strategy ### Default tests (`bun test`) 1. **Unit tests** — normalize(), extract(), format(), merge(), recall() in isolation 2. **Golden/edge tests** — minimized real-session messages and false positives 3. **Harness tests** — `@marcfargas/pi-test-harness` verifies extension loading/hooks with mocked model Harness isolation rule: - use temp cwd - pass absolute prune extension path - do not use repo cwd as harness cwd - assert only prune extension loaded ### Real MiniMax integration (`PRUNE_REAL=1 bun run test:real`) Use pi SDK or CLI, not test-harness. Test-harness replaces the model with playbook. Real integration must isolate resources: - temp cwd - temp agentDir - temp sessionDir - `noExtensions: true` / CLI `--no-extensions` - only prune extension loaded - MiniMax provider only - tiny compaction thresholds to force compaction Assertions are structural, not exact model text: - compaction starts/ends - summary contains `[Session Goal]`, `---`, `Use prune_recall` - summary does not contain `vcc_recall` - `prune_recall` can find older raw message ### Test Fixtures ```typescript // fixtures/simple.jsonl — 3-turn conversation // fixtures/complex.jsonl — 50+ turns, errors, branches // fixtures/merge.jsonl — previous + fresh for merge testing // fixtures/real-sessions/ — anonymized real messages ``` ## Comparison to pi-vcc | Aspect | pi-vcc | prune | | --------------------- | ------------------------------------- | ------------------------- | | Files | 15+ | ~8 | | Extractors | goals, files, prefs, commits, context | same | | Merge | header-based text parsing | simpler tested text merge | | Test coverage | minimal | comprehensive | | Real session analysis | none | yes | | Output metadata | yes | yes (same) | | prune_recall | external tool | built-in | ## TODO - [x] Core extract functions (normalize, extract) - [x] merge() implementation - [x] format() implementation - [x] prune_recall tool implementation - [x] session_before_compact hook - [x] /prune command - [x] Unit tests - [x] Integration tests - [x] Settings support