repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

remove prune extension

15ea7cd9ac5c1a1955573746cf578cd0ead11262

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (24)

CHANGELOG.md

Modified
9 9 ## 0.0.1
11 11 - Ship initial pi-ext set:
12 - goal, tldr, leaks, tps, quota, vcs-status, prune
12 + goal, tldr, leaks, tps, quota, vcs-status
13 13 - Add goal loop:
14 14 autocomplete, progress UI, standing prompts, judge-gated updates
15 15 - Add tldr live summaries, model footer, quota parsers, jj-aware workspace

README.md

Modified
90 90 | `neko` | Tiny animated editor cat for Pi. Pointless. Correct. | [README](extensions/neko/README.md) |
91 91 | `nu-bang` | Nushell bang-command bridge for Pi. | [README](extensions/nu-bang/README.md) |
92 92 | `prompt-autopsy` | System-prompt autopsy command for Pi. | [README](extensions/prompt-autopsy/README.md) |
93 -| `prune` | Deterministic Pi session compaction with searchable recall. | [README](extensions/prune/README.md) |
94 93 | `pulse` | Living documentation sync for Pi. | [README](extensions/pulse/README.md) |
95 94 | `q` | Follow-up question fork helper for Pi. | [README](extensions/q/README.md) |
96 95 | `quota` | Subscription quota dashboard for Pi providers. | [README](extensions/quota/README.md) |

extensions/goal/__tests__/unit.test.ts

Modified
230 230 ).toEqual({ done: true, blocked: false, reason: "complete" });
231 231 expect(
232 232 __goalTest.parseJudge('{"done":"true","blocked":1,"reason":" loose "}'),
233 - ).toEqual({ done: true, blocked: false, reason: "loose" });
233 + ).toEqual({ done: true, blocked: true, reason: "loose" });
234 234 expect(__goalTest.parseJudge('{"done":false,"blocked":true}')).toEqual({
235 235 done: false,
236 236 blocked: true,
507 - describe("elapsedSeconds / currentElapsedSeconds", () => {
507 + describe("elapsedSeconds", () => {
508 508 it("returns timeUsedSeconds from state", () => {
509 509 expect(__goalTest.elapsedSeconds(goal({ timeUsedSeconds: 42 }) as never)).toBe(42);
511 511 it("defaults to 0 when undefined", () => {
512 512 expect(__goalTest.elapsedSeconds(goal() as never)).toBe(0);
514 - it("currentElapsedSeconds returns max of snapshot and wall clock", () => {
515 - const state = goal({ createdAt: Date.now(), timeUsedSeconds: 0 }) as never;
516 - expect(__goalTest.currentElapsedSeconds(state)).toBeGreaterThanOrEqual(0);
517 - });
520 516 describe("verdictGlyph", () => {
1175 1171 expect(__goalTest.canUseUpdateGoal(goal({ turnsUsed: 0 }) as never)).toBe(false);
1175 + describe("parseLooseBoolean", () => {
1176 + it("accepts numeric 1 and 0", () => {
1177 + expect(__goalTest.parseLooseBoolean(1)).toBe(true);
1178 + expect(__goalTest.parseLooseBoolean(0)).toBe(false);
1179 + });
1180 + it("accepts string \"1\"", () => {
1181 + expect(__goalTest.parseLooseBoolean("1")).toBe(true);
1182 + });
1183 + it("rejects other numbers", () => {
1184 + expect(__goalTest.parseLooseBoolean(2)).toBe(false);
1185 + expect(__goalTest.parseLooseBoolean(-1)).toBe(false);
1186 + });
1187 + it("rejects non-boolean-like values", () => {
1188 + expect(__goalTest.parseLooseBoolean(null)).toBe(false);
1189 + expect(__goalTest.parseLooseBoolean(undefined)).toBe(false);
1190 + expect(__goalTest.parseLooseBoolean("yes")).toBe(false);
1191 + });
1192 + });
1194 + describe("JUDGE_PARSE_FAILURE_LIMIT", () => {
1195 + it("is 3", () => {
1196 + expect(__goalTest.JUDGE_PARSE_FAILURE_LIMIT).toBe(3);
1197 + });
1198 + });

extensions/goal/index.ts

Modified
115 115 let liveGoalMode: GoalUiMode = "normal";
116 116 const GOAL_WIDGET_DEFAULT_WIDTH = 78;
117 117 const GOAL_WIDGET_LEFT_PADDING = 0;
118 -const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge.
118 +const JUDGE_SYSTEM_PROMPT = `You are a strict /goal completion judge. Be skeptical. Agents lie about completion.
119 120 Return only JSON: {"done":boolean,"blocked":boolean,"reason":"one sentence"}.
120 -Mark done only if the latest assistant response explicitly proves the objective and every criterion are complete.
121 -Mark blocked only if the response shows a real impasse needing user input or external state.
122 -Otherwise return done=false, blocked=false.`;
122 +## Mark done=true ONLY if ALL of:
123 +1. The latest assistant response contains VERIFIABLE evidence for every criterion — not claims, not "looks good", not "should work".
124 +2. Test output, build results, or file diffs are shown in the response or tool results. Assertions without output are not evidence.
125 +3. Every criterion is independently addressed with specific proof tied to that criterion.
126 +4. No criterion was redefined smaller, skipped, or hand-waved.
127 +5. Tool results (read/write/edit/bash) support the claims. If a tool returned error or empty, the claim fails.
129 +## Mark blocked=true ONLY if:
130 +- The response shows a genuine impasse that requires user input or external state change. "Not sure" or "maybe done" is NOT blocked — that is continue.
132 +## Otherwise done=false, blocked=false (continue working).
134 +## Common agent lies to reject:
135 +- "Tests pass" with no test output shown.
136 +- "Implemented" without showing the actual file contents or diffs.
137 +- "Verified" without showing the verification command and its output.
138 +- "Looks correct" or "should work" — these are not evidence.
139 +- Partial completion presented as full completion.
140 +- A criterion ignored or silently dropped.`;
123 141 const GOAL_SUBCOMMANDS: GoalSubcommand[] = [
124 142 { value: "status", description: "Show current goal" },
125 143 { value: "pause", description: "Pause active goal" },
343 361 return state.timeUsedSeconds ?? 0;
346 -function currentElapsedSeconds(state: GoalState): number {
347 - return Math.max(
348 - elapsedSeconds(state),
349 - Math.floor((Date.now() - state.createdAt) / 1000),
350 - );
353 364 function durationText(seconds: number): string {
354 365 if (seconds < 60) return `${seconds}s`;
355 366 if (seconds < 3600) return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
380 391 if (state.timeBudgetSeconds)
381 392 parts.push(
382 - `${durationText(currentElapsedSeconds(state))}/${durationText(state.timeBudgetSeconds)}`,
393 + `${durationText(elapsedSeconds(state))}/${durationText(state.timeBudgetSeconds)}`,
384 - else parts.push(durationText(currentElapsedSeconds(state)));
395 + else parts.push(durationText(elapsedSeconds(state)));
385 396 return parts.join(" · ");
1033 1044 function parseLooseBoolean(value: unknown): boolean {
1034 - if (value === true) return true;
1035 - if (value === false) return false;
1036 - if (typeof value === "string") return value.trim().toLowerCase() === "true";
1045 + if (value === true || value === 1) return true;
1046 + if (value === false || value === 0) return false;
1047 + if (typeof value === "string") {
1048 + const lower = value.trim().toLowerCase();
1049 + return lower === "true" || lower === "1";
1037 1051 return false;
1376 1390 let removeTerminalInput: (() => void) | undefined;
1377 1391 let probe: ProbeState | undefined;
1378 1392 let lastTurnEvidence: TurnEvidence | undefined;
1393 + let turnStartedAt: number | undefined;
1379 1394 const syncUpdateGoalTool = () =>
1380 1395 setToolActive(pi, "update_goal", canUseUpdateGoal(state));
1450 1465 timeBudgetSeconds: settings.timeBudgetSeconds,
1451 1466 timeUsedSeconds: 0,
1452 1467 errorRetries: 0,
1453 - sessionId: currentSessionId(ctx),
1454 - createdAt: now,
1468 + sessionId: currentSessionId(ctx),
1469 + createdAt: now,
1455 1470 updatedAt: now,
1457 1472 appendGoal(pi, state);
1475 1490 pi.on("agent_start", (_event, _ctx) => {
1476 1491 lastTurnEvidence = undefined;
1492 + turnStartedAt = Date.now();
1477 1493 if (probe?.active) appendProbe(pi, "agent-start", { mode: probe.mode });
1585 1601 lastReason: verdict.reason,
1586 1602 lastVerdict: goalVerdictLabel(verdict),
1587 1603 tokensUsed: (judged.tokensUsed ?? 0) + tokenDelta(evidence),
1588 - timeUsedSeconds: currentElapsedSeconds(judged),
1604 + timeUsedSeconds:
1605 + (judged.timeUsedSeconds ?? 0) +
1606 + (turnStartedAt ? Math.floor((Date.now() - turnStartedAt) / 1000) : 0),
1590 1608 if (isJudgeFailure(verdict)) {
1591 1609 const parseFailure = isJudgeParseFailure(verdict);
1860 1878 timeBudgetSeconds: settings.timeBudgetSeconds,
1861 1879 timeUsedSeconds: 0,
1862 1880 errorRetries: 0,
1863 - sessionId: currentSessionId(ctx),
1881 + sessionId: currentSessionId(ctx),
1864 1882 createdAt: Date.now(),
1865 1883 updatedAt: Date.now(),
1932 1950 sanitizeGoalText,
1933 1951 durationText,
1934 1952 compactCount,
1935 - currentElapsedSeconds,
1936 1953 elapsedSeconds,
1937 1954 reasonHash,
1938 1955 nextBlockedStreak,
1946 1963 shortText,
1947 1964 usageTokenDelta,
1948 1965 canUseUpdateGoal,
1966 + parseLooseBoolean,
1967 + JUDGE_PARSE_FAILURE_LIMIT,

extensions/prune/CHANGELOG.md

Deleted
deleted file mode 100644
1 -# Changelog
3 -## 0.0.2
5 -- Keep prune source unchanged from v0.0.1; release tag only.
6 -- Keep `/prune`, `/prune-recall`, and `prune_recall` behavior unchanged.
7 -- Keep tests, README, and CHANGELOG unchanged.
9 -## 0.1.0 - 2026-05-21
11 -- a40a427 prepare extensions for npm release
12 -- 133cb7d chore(pi):
13 - migrate extensions to earendil packages
14 -- 5ca1296 Rework Pi agent extensions
15 -- 5fbf178 pi(ext):
16 - add remaining extensions (angel, animations, code-actions, files-widget,
17 - ghost, git-safe, neko, prune, web, etc.)

extensions/prune/README.md

Deleted
deleted file mode 100644
1 -# prune
3 -<!-- demo:prune:start -->
5 -![Prune recall](assets/prune.gif)
7 -<!-- demo:prune:end -->
9 -Deterministic Pi session compaction with searchable recall.
11 -## Install / load
13 -`prune` is loaded through the root `pi-ext` package.
14 -See the [root README](../../README.md).
16 -## Commands / tools / settings
18 -Commands:
20 -| Command | Description |
21 -| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22 -| `/prune` | Starts Pi compaction through `ctx.compact()`. With `prune.overrideDefault` enabled, `session_before_compact` supplies the prune summary. Command args are not read. |
23 -| `/prune-recall <query> [all]` | Searches session history and shows formatted matches. Default scope is current branch lineage. A trailing `all` searches all entries. Command limit is `10`. |
25 -Tool:
27 -| Tool | Arguments | Behavior |
28 -| -------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
29 -| `prune_recall` | `query: string`, `scope?: "lineage" \| "all"`, `limit?: number`, `expand?: number[]` | Searches session entries and returns scored matches. Default scope: `lineage`. Default limit: `5`. `limit` max: `20`. |
31 -`prune_recall` is registered at load time, but it is active for the agent only
32 -after a prune compaction exists in the current branch.
34 -```typescript
35 -prune_recall({ query: "auth token" })
36 -prune_recall({ query: "auth token", scope: "all" })
37 -prune_recall({ query: "auth token", expand: [12, 14] })
38 -```
40 -Hooks:
42 -| Hook | Behavior |
43 -| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44 -| `session_before_compact` | Returns prune compaction when `prune.overrideDefault` is true. Hard-caps raw kept tail at ~32k tokens when a safe boundary exists. Includes `firstKeptEntryId`, `tokensBefore`, and details `{ kind: "prune", version: 1, sourceEntriesProcessed, tailKept, splitPrefixMessages }`. |
45 -| `session_start` | Enables/disables `prune_recall` from current branch state. |
46 -| `session_tree` | Enables/disables `prune_recall` from current branch state. |
47 -| `session_compact` | Enables `prune_recall` after a prune compaction, logs in debug mode, and notifies UI when present. |
49 -Settings:
51 -| Setting | Default | Behavior |
52 -| ----------------------- | ------: | --------------------------------------------------------------------- |
53 -| `prune.overrideDefault` | `true` | Return prune compaction from `session_before_compact`. |
54 -| `prune.sectionLimit` | `8` | Max lines per structured section in formatted output. |
55 -| `prune.transcriptLimit` | `60` | Max transcript lines kept in summary tail. |
56 -| `prune.toolCapPerTurn` | `8` | Max tool-call transcript lines per user turn. Errors are always kept. |
57 -| `prune.debug` | `false` | Log prune stats, skipped roles, and compaction status. |
59 -## Behavior
61 -- With `prune.overrideDefault` enabled, compaction is local and deterministic.
62 - The prune hook does not call an LLM.
63 -- `/prune` starts normal Pi compaction; the hook replaces the default summary
64 - only when enabled.
65 -- Settings are read once from `settingsManager.getSettings().prune` when the
66 - extension loads.
67 -- Pi roles mapped for compaction:
68 - `user`, `assistant`, `tool`, `toolResult`, `bashExecution`, `branchSummary`,
69 - `compactionSummary`.
70 - `custom` is skipped.
71 -- Assistant `thinking` and `image` parts are skipped during compaction.
72 - Assistant `toolCall` parts become transcript tool lines.
73 -- Extracted sections:
74 - - `[Session Goal]`:
75 - first user task lines plus later scope changes.
76 - - `[Files And Changes]`:
77 - paths inferred from read/write/edit tool args and simple bash path matches.
78 - - `[Outstanding Context]`:
79 - tool errors and recent blocker/failure lines.
80 - - `[User Preferences]`:
81 - explicit user preference lines.
82 - - `[Continue Now]`:
83 - deterministic resume block from the transcript tail.
84 -- Empty structured sections are omitted.
85 -- Transcript entries keep stable `#N` source refs from the compaction input
86 - order.
87 -- Tool calls render as `* tool "arg" (#N)` when a command/path is available,
88 - otherwise `* tool (#N)`.
89 -- Bash tool commands are shortened:
90 - leading `cd ...
91 - &&` is removed, and a trailing simple pipe such as `tail`/`head` is removed.
92 -- Tool errors render as `[tool_error] [ERROR] tool (#N)`.
93 -- Existing prune summaries are merged with fresh summaries.
94 - Goals/preferences/files are deduped, context and continue block are refreshed,
95 - transcript keeps previous entries before fresh entries.
96 -- Prune compactions are detected by `details.kind === "prune"`; older hook
97 - summaries are also detected when they contain the prune recall note.
98 -- Recall searches current branch lineage by default.
99 - `scope:
100 - "all"` searches all session entries.
101 -- Recall includes message entries, compaction summaries, and `custom_message`
102 - content.
103 -- Recall message text includes text parts, tool call names/args, and thinking
104 - parts.
105 - Images are ignored.
106 -- Regex-looking query strings are tried as case-insensitive regex.
107 - Invalid regex falls back to term matching.
108 -- Regex matches score `10`; term matches score by matched-term count.
109 -- `expand` returns exact `#N` entries even when the query does not match.
111 -## Output Format
113 -```text
114 -[Session Goal]
115 -- Fix the auth bug
116 -- [Scope change]
117 -- also update token refresh logic
119 -[Files And Changes]
120 -- Modified: session.ts
122 -[Outstanding Context]
123 -- lint still failing
125 -[Continue Now]
126 -- Current request: Fix the auth bug (#1)
127 -- Last action: read src/auth/session.ts (#3)
128 -- Next: continue current request; use prune_recall before redoing old work.
130 ----
132 -[user]
133 -Fix the auth bug (#1)
134 -* read "src/auth/session.ts" (#3)
136 ----
138 -prune: 10 entries summarized; before 18.9k tok; raw kept 3 entries; split-prefix 0
140 ----
142 -Use prune_recall to search for prior work, decisions, and context from before this summary.
143 -Do not redo work already completed.
144 -```
146 -## Testing
148 -```bash
149 -bun install
151 -bun test # fast default: unit + harness, no network
152 -bun run test:unit # pure funcs only
153 -bun run test:harness # pi-test-harness extension wiring
154 -bun run test:watch # watch fast tests
155 -bun run test:coverage # coverage for fast tests
157 -bun run test:real # real MiniMax integ test, costs quota
158 -bun run test:all # fast tests + real MiniMax
159 -```
161 -Notes:
163 -- `bun test` intentionally excludes `__tests__/real/`.
164 -- `test:real` uses MiniMax, temp cwd/agentDir/session, `noExtensions:
165 - true`, and only prune loaded.

extensions/prune/SPEC.md

Deleted
deleted file mode 100644
1 -# prune — Lossless Conversation Compactor
3 -> Trim conversation to essentials. Search everything.
5 -## Overview
7 -`prune` is a deterministic, lossless compaction extension for pi.
8 -It replaces the default LLM-based summarization with algorithmic extraction that
9 -preserves:
11 -1. **Brief transcript** — chronological flow with tool calls collapsed to
12 - one-liners
13 -2. **Key facts** — extracted goals, files, blockers, preferences
14 -3. **Lossless recall** — raw messages stay searchable via JSONL + `prune_recall`
16 -**Note on "lossless":** prune preserves original JSONL at the system level.
17 -Lossless refers to data integrity, not instant recall.
18 -The `prune_recall` tool (implemented as part of prune) provides programmatic
19 -search.
21 -## Architecture
23 -```text
24 -┌─────────────────────────────────────────────────────────────┐
25 -│ session_before_compact │
26 -│ │ │
27 -│ ▼ │
28 -│ normalize(messages) → blocks │
29 -│ │ │
30 -│ ▼ │
31 -│ extract(blocks) → ExtractOutput │
32 -│ │ │
33 -│ ▼ │
34 -│ format(fresh ExtractOutput) → freshSummary │
35 -│ │ │
36 -│ ▼ │
37 -│ merge(previousSummary, freshSummary) → finalSummary │
38 -└─────────────────────────────────────────────────────────────┘
39 -```
41 -## Output Format
43 -```text
44 -[Session Goal]
45 -- Fix the auth bug
46 -- Also: update token refresh logic
48 -[Files And Changes]
49 -- Modified: session.ts, auth.test.ts
50 -- Created: middleware.ts
52 -[Outstanding Context]
53 -- lint check still failing on line 42
55 -[User Preferences]
56 -- Prefer TypeScript strict mode
57 -- Never commit with debug logs
59 -[Commits]
60 -- abc1234: Fix token refresh
62 -[Continue Now]
63 -- Current request: Fix the auth bug (#5)
64 -- Last action: edit session.ts (#9)
65 -- Next: continue current request; use prune_recall before redoing old work.
67 ----
68 -[user] Fix the auth bug (#5)
69 -[assistant] Root cause found
70 -* bash "bun test" (#7)
71 -* edit "session.ts" (#9)
72 -...(N earlier lines omitted)
74 -───────────────────────────────────────────────────────────────
76 - prune: 309 entries summarized; before 18.9k tok; raw kept 67 entries; split-prefix 0
78 -Use prune_recall to search for prior work, decisions, and context from before this summary.
79 -Do not redo work already completed.
80 -```
82 -## Sections
84 -| Section | Description | Merge Policy |
85 -| ----------------------- | ---------------------------------------- | ------------------------------------------------------------------------ |
86 -| `[Session Goal]` | Goals + scope changes from user messages | Sticky (accumulate, dedup, cap 8) |
87 -| `[Files And Changes]` | Modified, created, read files | Union by category, dedup, cap 10 each |
88 -| `[Outstanding Context]` | Errors, blockers, pending questions | Fresh (replace) |
89 -| `[User Preferences]` | prefer/never/always patterns | Sticky (accumulate, cap 15) |
90 -| `[Commits]` | Extracted git commits with hashes | Sticky (keep recent 8) |
91 -| `[Continue Now]` | Resume block from latest transcript tail | Fresh (replace) |
92 -| `---` | Brief transcript | Append fresh after previous, then cap tail (older first in final output) |
94 -## Extract Algorithm
96 -### 1. Normalize
98 -Map pi messages → blocks:
100 -- `user` — text content from user messages
101 -- `assistant` — text content from assistant messages
102 -- `tool_call` — tool name + args
103 -- `tool_result` — output, mark errors
104 -- `thinking` — skip
106 -### 2. Build Sections
108 -#### Goals
110 -Extracted from user blocks.
111 -Algorithm (based on pi-vcc + real session analysis):
113 -````typescript
114 -// Pseudo-code. Impl should use arrays + RegExp construction, not copy these multiline regexes directly.
115 -// First user block → collect up to 6 goals
116 -// Subsequent user blocks → detect scope changes
118 -// Patterns for goals:
119 -GOAL_VERB_RE = /\b(scan|check|fix|implement|add|create|build|refactor|debug|
120 -investigate|update|remove|delete|migrate|deploy|test|write|set up|
121 -spin|run|execute|verify|review|analyze|explain|describe|explore|
122 -call|use|switch|clean|lint|format)\b/i;
124 -// Scope change patterns:
125 -SCOPE_CHANGE_RE = /\b(also|instead|actually|change of plan|forget that|
126 -new task|switch to|now I want|pivot|let'?s do|stop .* and|
127 -while we'?re at it|between|for now)\b/i;
129 -// Noise filters:
130 -NOISE_SHORT_RE = /^(ok|yes|no|yep|nope|go|hi|hey|thanks?|thx|k|y|n|
131 -done|go ahead|looks good|sounds good|lgtm|sounds right|
132 -makes sense|sure|please|thank)\s*[.!?]*$/i;
134 -NON_GOAL_RE = /^\s*[\[│├└─╭╰─]|```|^\s*(=[A-Z_]+\(|function |const |let |
135 -var |import |export |class |async |await |interface |type )|
136 -^(https?:\/\/|file:|\/[a-z])|^\s*```|\s*```\s*$|^\s*\| |
137 -^\s*For each\b|\bin full\b[^\n]*\b(comments?|issues?|PRs?|linked)\b|
138 -^@[\w\/.-]+\s*$/i;
140 -// Template signal (stop collecting at these):
141 -TEMPLATE_SIGNAL_RE = /^\s*(For each\b|Do NOT\b|Analyze and propose\b|
142 -If [Tt]ask|Output:\s*$|here'?s a|ticket:)/i;
144 -// Extract:
145 -// 1. Truncate at template signal
146 -// 2. Filter noise lines
147 -// 3. Filter non-goal patterns
148 -// 4. Collect from first block, scope-change only from subsequent
149 -````
151 -**Real session edge cases handled:**
153 -- Short messages:
154 - "yes", "done", "ok", "noop", "go" → filtered
155 -- Questions:
156 - usually transcript-only; task questions like "can you fix X?" may become goals
157 -- URLs:
158 - filtered via NON_GOAL_RE
159 -- Multi-part:
160 - "do X.
161 - also do Y." → captures scope change via "also"
162 -- Command templates:
163 - stopped at TEMPLATE_SIGNAL
165 -#### Files
167 -```typescript
168 -// From tool_call args:
169 -// - edit/write → Modified/Created
170 -// - read → Read
171 -// - bash "git commit" → Commits
173 -extractFileFromArgs(toolName, args) → { modified, created, read }
174 -extractCommits(blocks) → [{ hash, message }, ...]
175 -```
177 -#### Context
179 -```typescript
180 -// Errors from tool_result with isError
181 -// Blockers from assistant/user text matching BLOCKER_RE
182 -BLOCKER_RE = /\b(fail|broken|cannot|can't|won't work|blocked|blocker|
183 -not (fixed|resolved|working)|crash(es|ed|ing)?|still (broken|failing|wrong))\b/i;
185 -// Cap at 5 items
186 -```
188 -**Note:** Context is extracted fresh on each compaction, not merged.
189 -Old blockers are discarded when resolved.
191 -#### Preferences
193 -```typescript
194 -// From user messages matching preference patterns
195 -// STRICT: require pattern in first 200 chars to avoid matching pasted content
196 -PREF_PATTERNS = [
197 - /\bprefer(?:s|red|ring)?\s+\w/i,
198 - /\bdon'?t want\b/i,
199 - /\balways (?:use|do|run|prefer|keep|make|format|write|add|set|put|prefix|start|include|append)\b/i,
200 - /\bnever (?:use|do|run|push|commit|write|ignore|add|set|put|remove|delete|include|deploy)\b/i,
201 - /\bplease (?:use|avoid|keep|make|don'?t|do not|format|write)\b/i,
202 - /\b(?:style|format|language|naming)\s*[:=]\s*\S/i,
203 -];
205 -// Validation:
206 -// 1. Must be in first 200 chars of message (not buried in pasted content)
207 -// 2. Line length < 200 chars
208 -// 3. Not a question
209 -// 4. Cap at 1 per user block, 10 total
210 -```
212 -**Known limitations (false positive risk):**
214 -The preference extraction regex cannot distinguish user-authored instructions
215 -from:
217 -1. **Quoted tool output** — agent-generated examples copied into a user message
218 -2. **Pasted content** — user pasting code, logs, or external text
219 -3. **Previous compaction output** — quoted compaction summaries in new messages
220 -4. **Assistant suggestions** — content the assistant generated that user is
221 - quoting
223 -**Mitigation attempts:**
225 -- Stricter position requirement (first 200 chars) — catches direct pastes but
226 - not tool output
227 -- Line length cap (200 chars) — filters some noise
228 -- Question filter — avoids interrogative patterns
230 -**200-char heuristic analysis (from real sessions):**
232 -- User messages in real sessions average <500 chars
233 -- Pasted content (skill files, code blocks) averages 2000+ chars
234 -- The heuristic catches most direct preference pastes
235 -- It does NOT catch content extracted incorrectly from tool output or prior
236 - compactions
238 -**False positive example:**
240 -```text
241 -"POV: You Angered the Wrong Cat 😈🐱 (POV format = engagement)"
242 -```
244 -This was in a compaction output and not found in user-authored messages scanned
245 -later.
246 -Most likely path:
247 -generated/test content became part of prior summary or quoted context, then
248 -preference regex preserved it.
249 -User later quoted it while reporting the false positive.
251 -**Acceptable tradeoff:** Preferences are hints, not facts.
252 -False positives in preferences are noisy but not harmful to compaction
253 -correctness.
255 -### 3. Build Transcript
257 -```typescript
258 -// Collapses tool calls to one-liners:
259 -// * bash "npm install" (#5)
260 -// * edit "src/main.ts" (#7)
262 -// Truncation:
263 -// - User: 256 chars, strip self-talk
264 -// - Assistant: 200 chars, strip self-talk
265 -// - Tool calls: 120 chars, compress bash
267 -// Collapse:
268 -// - Cap at toolCapPerTurn tool-call lines per user turn
269 -// - Errors are always kept
270 -```
272 -### 4. Merge
274 -```typescript
275 -merge(previousSummary: string | undefined, freshSummary: string): string {
276 - // Text merge using stable section headers.
277 - // Outstanding Context + Continue Now: REPLACE (fresh only)
278 - // Files: union by category + dedup
279 - // Goals/Preferences/Commits: union + dedup + cap
280 - // Transcript: previous brief + fresh brief, then cap tail
281 - // Footer/metadata: render once at end
283 -```
285 -## prune_recall
287 -Implemented as part of prune.
288 -Two surfaces share one search implementation:
290 -1. `prune_recall` — registered tool, exposed to the LLM only after a prune
291 - compaction exists in the current branch
292 -2. `/prune-recall` — command for the human, always available
294 -```typescript
295 -prune_recall({
296 - query: string, // plain text or regex string
297 - scope: 'lineage' | 'all', // active branch only or all entries in session file
298 - limit: number, // max results
299 - expand: number[], // expand exact source refs, e.g. [205, 270]
300 -})
301 -```
303 -Searches session JSONL for matching entries.
304 -Returns structured results with context.
306 -### Source refs
308 -- `#N` = 1-based `sourceIndex` assigned during `normalize()` from current branch
309 - order
310 -- Transcript refs and `expand` use same `#N`
311 -- `scope:
312 - 'lineage'` searches current branch/lineage and preserves `#N` mapping
313 -- `scope:
314 - 'all'` searches whole session file, including off-lineage branches; results
315 - include both `#N` when available and entry id
316 -- Refs are stable while branch history is append-only; export/import or tree
317 - navigation can change ordinal mapping
319 -### Metadata footer
321 -```text
322 -prune: 309 entries summarized; before 18.9k tok; raw kept 67 entries; split-prefix 0
323 -```
325 -- `entries summarized` = messages passed to deterministic extraction, including
326 - old raw-tail entries moved into summary
327 -- `before N tok` = compaction event `tokensBefore`, if available
328 -- `raw kept` = branch entries kept after returned `firstKeptEntryId`
329 -- `split-prefix` = `turnPrefixMessages.length`
331 -## Commands
333 -| Command | Description |
334 -| --------------------------- | ------------------------- |
335 -| `/prune` | Manual compaction trigger |
336 -| `/prune-recall <query>` | Search current lineage |
337 -| `/prune-recall <query> all` | Search all branches |
339 -## Settings
341 -```json
343 - "prune": {
344 - "sectionLimit": 8,
345 - "transcriptLimit": 60,
346 - "toolCapPerTurn": 8,
347 - "debug": false
348 - }
350 -```
352 -## Testing Strategy
354 -### Default tests (`bun test`)
356 -1. **Unit tests** — normalize(), extract(), format(), merge(), recall() in
357 - isolation
358 -2. **Golden/edge tests** — minimized real-session messages and false positives
359 -3. **Harness tests** — `@marcfargas/pi-test-harness` verifies extension
360 - loading/hooks with mocked model
362 -Harness isolation rule:
364 -- use temp cwd
365 -- pass absolute prune extension path
366 -- do not use repo cwd as harness cwd
367 -- assert only prune extension loaded
369 -### Real MiniMax integration (`PRUNE_REAL=1 bun run test:real`)
371 -Use pi SDK or CLI, not test-harness.
372 -Test-harness replaces the model with playbook.
374 -Real integration must isolate resources:
376 -- temp cwd
377 -- temp agentDir
378 -- temp sessionDir
379 -- `noExtensions:
380 - true` / CLI `--no-extensions`
381 -- only prune extension loaded
382 -- MiniMax provider only
383 -- tiny compaction thresholds to force compaction
385 -Assertions are structural, not exact model text:
387 -- compaction starts/ends
388 -- summary contains `[Session Goal]`, `---`, `Use prune_recall`
389 -- summary does not contain `vcc_recall`
390 -- `prune_recall` can find older raw message
392 -### Test Fixtures
394 -```typescript
395 -// fixtures/simple.jsonl — 3-turn conversation
396 -// fixtures/complex.jsonl — 50+ turns, errors, branches
397 -// fixtures/merge.jsonl — previous + fresh for merge testing
398 -// fixtures/real-sessions/ — anonymized real messages
399 -```
401 -## Comparison to pi-vcc
403 -| Aspect | pi-vcc | prune |
404 -| --------------------- | ------------------------------------- | ------------------------- |
405 -| Files | 15+ | ~8 |
406 -| Extractors | goals, files, prefs, commits, context | same |
407 -| Merge | header-based text parsing | simpler tested text merge |
408 -| Test coverage | minimal | comprehensive |
409 -| Real session analysis | none | yes |
410 -| Output metadata | yes | yes (same) |
411 -| prune_recall | external tool | built-in |
413 -## TODO
415 -- [x] Core extract functions (normalize, extract)
416 -- [x] merge() implementation
417 -- [x] format() implementation
418 -- [x] prune_recall tool implementation
419 -- [x] session_before_compact hook
420 -- [x] /prune command
421 -- [x] Unit tests
422 -- [x] Integration tests
423 -- [x] Settings support

extensions/prune/__tests__/extract.test.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — extract tests
3 - */
5 -import { describe, expect, it } from "bun:test";
6 -import { extract } from "../src/extract.ts";
7 -import { normalize } from "../src/normalize.ts";
8 -import type { Message } from "../src/types.ts";
10 -// ─── Test Fixtures ───────────────────────────────────────────────────────
12 -const SIMPLE_USER_MSG: Message = {
13 - role: "user",
14 - content: "Fix the auth bug, users cannot log in after password reset",
15 -};
17 -const SIMPLE_ASSISTANT_MSG: Message = {
18 - role: "assistant",
19 - content:
20 - "The issue is a missing token refresh. Let me check the auth module.",
21 -};
23 -const TOOL_CALL_MSG: Message = {
24 - role: "assistant",
25 - content: [
26 - {
27 - type: "toolCall",
28 - name: "read",
29 - arguments: { path: "src/auth/session.ts" },
30 - },
31 - ],
32 -};
34 -const ERROR_MSG: Message = {
35 - role: "tool",
36 - toolName: "bash",
37 - isError: true,
38 - content: "ENOENT: no such file or directory",
39 -};
41 -// ─── Tests ─────────────────────────────────────────────────────────────
43 -describe("normalize", () => {
44 - it("normalizes user message", () => {
45 - const blocks = normalize([SIMPLE_USER_MSG]);
46 - expect(blocks).toHaveLength(1);
47 - expect(blocks[0].kind).toBe("user");
48 - expect(blocks[0].text).toContain("auth bug");
49 - });
51 - it("normalizes assistant message", () => {
52 - const blocks = normalize([SIMPLE_ASSISTANT_MSG]);
53 - expect(blocks).toHaveLength(1);
54 - expect(blocks[0].kind).toBe("assistant");
55 - expect(blocks[0].sourceIndex).toBe(1);
56 - });
58 - it("normalizes tool call", () => {
59 - const blocks = normalize([TOOL_CALL_MSG]);
60 - expect(blocks).toHaveLength(1);
61 - expect(blocks[0].kind).toBe("tool_call");
62 - expect(blocks[0].name).toBe("read");
63 - expect(blocks[0].args).toEqual({ path: "src/auth/session.ts" });
64 - });
66 - it("normalizes error tool result", () => {
67 - const blocks = normalize([ERROR_MSG]);
68 - expect(blocks).toHaveLength(1);
69 - expect(blocks[0].kind).toBe("tool_result");
70 - expect(blocks[0].isError).toBe(true);
71 - expect(blocks[0].name).toBe("bash");
72 - });
74 - it("normalizes real Pi toolResult role", () => {
75 - const blocks = normalize([
76 - {
77 - role: "toolResult",
78 - toolName: "write",
79 - isError: false,
80 - content: [
81 - { type: "text", text: "Successfully wrote 123 bytes to file.ts" },
82 - ],
83 - },
84 - ]);
85 - expect(blocks).toHaveLength(1);
86 - expect(blocks[0].kind).toBe("tool_result");
87 - expect(blocks[0].name).toBe("write");
88 - });
90 - it("skips empty messages", () => {
91 - const blocks = normalize([{ role: "user", content: "" }]);
92 - expect(blocks).toHaveLength(0);
93 - });
95 - it("skips unsupported roles and empty assistant content", () => {
96 - const blocks = normalize([
97 - { role: "system" as unknown as Message["role"], content: "ignored" },
98 - { role: "assistant" },
99 - { role: "assistant", content: " " },
100 - ]);
101 - expect(blocks).toHaveLength(0);
102 - });
104 - it("normalizes mixed assistant content and skips thinking/images", () => {
105 - const blocks = normalize([
106 - {
107 - role: "assistant",
108 - content: [
109 - { type: "thinking", thinking: "secret" },
110 - { type: "text", text: "Visible answer" },
111 - { type: "image", mimeType: "image/png" },
112 - { type: "toolCall", name: "", arguments: {} },
113 - ],
114 - },
115 - ]);
116 - expect(blocks).toHaveLength(1);
117 - expect(blocks[0].kind).toBe("assistant");
118 - expect(blocks[0].text).toBe("Visible answer");
119 - });
121 - it("extracts tool result text from content parts", () => {
122 - const blocks = normalize([
123 - {
124 - role: "tool",
125 - toolName: "read",
126 - content: [{ type: "text", text: "file body" }],
127 - },
128 - ]);
129 - expect(blocks[0].text).toBe("file body");
130 - });
132 - it("preserves 1-based source indices", () => {
133 - const messages = [SIMPLE_USER_MSG, SIMPLE_ASSISTANT_MSG, TOOL_CALL_MSG];
134 - const blocks = normalize(messages);
135 - expect(blocks[0].sourceIndex).toBe(1);
136 - expect(blocks[1].sourceIndex).toBe(2);
137 - expect(blocks[2].sourceIndex).toBe(3);
138 - });
139 -});
141 -describe("extract", () => {
142 - it("extracts goals from user messages", () => {
143 - const blocks = normalize([SIMPLE_USER_MSG]);
144 - const result = extract(blocks);
145 - expect(result.goals.length).toBeGreaterThan(0);
146 - expect(result.goals[0]).toContain("auth bug");
147 - });
149 - it("extracts errors from tool results", () => {
150 - const blocks = normalize([ERROR_MSG]);
151 - const result = extract(blocks);
152 - expect(result.context.length).toBeGreaterThan(0);
153 - expect(result.context[0]).toContain("ENOENT");
154 - });
156 - it("extracts files from tool calls", () => {
157 - const blocks = normalize([TOOL_CALL_MSG]);
158 - const result = extract(blocks);
159 - expect(result.files.read.size).toBeGreaterThan(0);
160 - expect([...result.files.read][0]).toContain("session.ts");
161 - });
163 - it("compresses bash transcript commands", () => {
164 - const result = extract(
165 - normalize([
166 - {
167 - role: "assistant",
168 - content: [
169 - {
170 - type: "toolCall",
171 - name: "bash",
172 - arguments: { command: "cd /tmp/project && bun test | tail -n 5" },
173 - },
174 - ],
175 - },
176 - ]),
177 - );
178 - expect(result.transcript[0].cmd).toBe("bun test");
179 - });
181 - it("extracts absolute paths from bash commands", () => {
182 - const result = extract(
183 - normalize([
184 - {
185 - role: "assistant",
186 - content: [
187 - {
188 - type: "toolCall",
189 - name: "bash",
190 - arguments: { command: "touch /tmp/prune/file.ts" },
191 - },
192 - ],
193 - },
194 - ]),
195 - );
196 - expect([...result.files.modified]).toContain("/tmp/prune/file.ts");
197 - });
199 - it("uses file_path and file args for transcript commands", () => {
200 - const result = extract(
201 - normalize([
202 - {
203 - role: "assistant",
204 - content: [
205 - {
206 - type: "toolCall",
207 - name: "read",
208 - arguments: { file_path: "src/a.ts" },
209 - },
210 - ],
211 - },
212 - {
213 - role: "assistant",
214 - content: [
215 - {
216 - type: "toolCall",
217 - name: "write",
218 - arguments: { file: "src/b.ts" },
219 - },
220 - ],
221 - },
222 - {
223 - role: "assistant",
224 - content: [{ type: "toolCall", name: "unknown", arguments: {} }],
225 - },
226 - ]),
227 - );
228 - expect(result.transcript[0].cmd).toBe("src/a.ts");
229 - expect(result.transcript[1].cmd).toBe("src/b.ts");
230 - expect(result.transcript[2].cmd).toBeUndefined();
231 - });
233 - it("caps tool calls per turn and keeps errors", () => {
234 - const result = extract(
235 - normalize([
236 - { role: "user", content: "fix it" },
237 - {
238 - role: "assistant",
239 - content: [
240 - { type: "toolCall", name: "read", arguments: { path: "a.ts" } },
241 - ],
242 - },
243 - {
244 - role: "assistant",
245 - content: [
246 - { type: "toolCall", name: "read", arguments: { path: "b.ts" } },
247 - ],
248 - },
249 - { role: "tool", toolName: "bash", isError: true, content: "failed" },
250 - ]),
251 - { toolCapPerTurn: 1 },
252 - );
253 - expect(result.transcript.map((entry) => entry.cmd)).toContain("a.ts");
254 - expect(result.transcript.map((entry) => entry.cmd)).not.toContain("b.ts");
255 - expect(result.transcript.some((entry) => entry.role === "error")).toBe(
256 - true,
257 - );
258 - });
260 - it("ignores thinking blocks if present directly", () => {
261 - const result = extract([
262 - { kind: "thinking", text: "secret", sourceIndex: 1 },
263 - ]);
264 - expect(result.transcript).toHaveLength(0);
265 - });
267 - it("renders tool errors with fallback body", () => {
268 - const result = extract(
269 - normalize([
270 - { role: "tool", toolName: "bash", isError: true, content: "" },
271 - ]),
272 - );
273 - expect(result.context[0]).toContain("(no output)");
274 - expect(result.transcript[0].text).toBe("[ERROR] bash");
275 - });
277 - it("caps context at 5 items", () => {
278 - const errors = Array(10).fill(ERROR_MSG);
279 - const blocks = normalize(errors);
280 - const result = extract(blocks);
281 - expect(result.context.length).toBeLessThanOrEqual(5);
282 - });
284 - describe("preferences", () => {
285 - it("extracts prefer patterns", () => {
286 - const msg: Message = {
287 - role: "user",
288 - content: "I prefer TypeScript strict mode",
289 - };
290 - const blocks = normalize([msg]);
291 - const result = extract(blocks);
292 - expect(result.preferences.length).toBeGreaterThan(0);
293 - });
295 - it("extracts never patterns", () => {
296 - const msg: Message = {
297 - role: "user",
298 - content: "Never use var, always const or let",
299 - };
300 - const blocks = normalize([msg]);
301 - const result = extract(blocks);
302 - expect(result.preferences.length).toBeGreaterThan(0);
303 - });
305 - it("does not extract buried pasted preference-looking text", () => {
306 - const msg: Message = {
307 - role: "user",
308 - content: `${"x".repeat(220)}\nPrefer fake pasted rule`,
309 - };
310 - const result = extract(normalize([msg]));
311 - expect(result.preferences).toHaveLength(0);
312 - });
314 - it("does not extract known generated POV false positive", () => {
315 - const msg: Message = {
316 - role: "user",
317 - content:
318 - '"POV: You Angered the Wrong Cat 😈🐱 (POV format = engagement)',
319 - };
320 - const result = extract(normalize([msg]));
321 - expect(result.preferences).toHaveLength(0);
322 - });
323 - });
325 - describe("real-session edge cases", () => {
326 - it("extracts scan/switch/spin/do task language", () => {
327 - const messages: Message[] = [
328 - { role: "user", content: "scan this code base and check health" },
329 - { role: "user", content: "switch project from nodejs/npm to bun." },
330 - { role: "user", content: "spin up dev server for me to test" },
331 - { role: "user", content: "do rest" },
332 - ];
333 - const result = extract(normalize(messages));
334 - expect(result.goals.join("\n")).toContain("scan this code base");
335 - expect(result.scopeChanges.join("\n")).toContain("switch project");
336 - expect(result.scopeChanges.join("\n")).toContain("spin up dev server");
337 - expect(result.scopeChanges.join("\n")).toContain("do rest");
338 - });
340 - it("keeps simple questions out of goals", () => {
341 - const result = extract(
342 - normalize([{ role: "user", content: "what is subsetting?" }]),
343 - );
344 - expect(result.goals).toHaveLength(0);
345 - expect(result.transcript[0].text).toContain("what is subsetting?");
346 - });
348 - it("treats task questions as goals", () => {
349 - const result = extract(
350 - normalize([{ role: "user", content: "can you fix?" }]),
351 - );
352 - expect(result.goals.join("\n")).toContain("can you fix?");
353 - });
355 - it("stops goal extraction before skill bodies", () => {
356 - const result = extract(
357 - normalize([
358 - {
359 - role: "user",
360 - content:
361 - 'read pi skill\n<skill name="pi">\nPrefer fake skill rule\nfix fake skill task\n</skill>',
362 - },
363 - ]),
364 - );
365 - expect(result.goals).toEqual(["read pi skill"]);
366 - expect(result.preferences).toHaveLength(0);
367 - });
369 - it("strips assistant self-talk from transcript", () => {
370 - const result = extract(
371 - normalize([{ role: "assistant", content: "Okay, so fixed the bug" }]),
372 - );
373 - expect(result.transcript[0].text).toBe("fixed the bug");
374 - });
376 - it("keeps assistant text when no self-talk prefix matches", () => {
377 - const result = extract(
378 - normalize([{ role: "assistant", content: "Implemented the fix" }]),
379 - );
380 - expect(result.transcript[0].text).toBe("Implemented the fix");
381 - });
382 - });
383 -});
385 -// ─── Integration Tests ────────────────────────────────────────────────────────────
387 -describe("extract integration", () => {
388 - it("processes a realistic conversation", () => {
389 - const conversation: Message[] = [
390 - {
391 - role: "user",
392 - content: "Fix the auth bug, users cannot log in after password reset",
393 - },
394 - {
395 - role: "assistant",
396 - content:
397 - "The issue is a missing token refresh. Let me check the auth module.",
398 - },
399 - {
400 - role: "assistant",
401 - content: [
402 - {
403 - type: "toolCall",
404 - name: "read",
405 - arguments: { path: "src/auth/session.ts" },
406 - },
407 - ],
408 - },
409 - {
410 - role: "tool",
411 - toolName: "read",
412 - content: "async function refreshToken() { ... }",
413 - },
414 - { role: "assistant", content: "Found it! The token refresh is missing." },
415 - {
416 - role: "assistant",
417 - content: [
418 - {
419 - type: "toolCall",
420 - name: "edit",
421 - arguments: {
422 - path: "src/auth/session.ts",
423 - new: "await refreshToken()",
424 - },
425 - },
426 - ],
427 - },
428 - ];
430 - const blocks = normalize(conversation);
431 - const result = extract(blocks);
433 - // Should have goal
434 - expect(result.goals.length).toBeGreaterThan(0);
436 - // Should have files
437 - expect(result.files.modified.size + result.files.read.size).toBeGreaterThan(
438 - 0,
439 - );
441 - // Should have transcript
442 - expect(result.transcript.length).toBeGreaterThan(0);
443 - });
444 -});

extensions/prune/__tests__/format.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "bun:test";
2 -import { format } from "../src/format.ts";
3 -import type { ExtractOutput } from "../src/types.ts";
5 -function emptyData(): ExtractOutput {
6 - return {
7 - goals: [],
8 - scopeChanges: [],
9 - files: { modified: new Set(), created: new Set(), read: new Set() },
10 - context: [],
11 - preferences: [],
12 - transcript: [],
13 - };
16 -describe("format", () => {
17 - it("renders spec section headers and prune_recall footer", () => {
18 - const data = emptyData();
19 - data.goals.push("Fix the auth bug");
20 - data.scopeChanges.push("also update token refresh logic");
21 - data.files.modified.add("session.ts");
22 - data.context.push("lint still failing");
23 - data.preferences.push("Prefer TypeScript strict mode");
24 - data.transcript.push({ role: "user", text: "Fix the auth bug", ref: "#1" });
26 - const out = format(data, {
27 - sourceEntriesProcessed: 10,
28 - tailKept: 3,
29 - tokenEstimate: 18900,
30 - }).summary;
32 - expect(out).toContain("[Session Goal]");
33 - expect(out).toContain("- [Scope change]");
34 - expect(out).toContain("[Files And Changes]");
35 - expect(out).toContain("[Outstanding Context]");
36 - expect(out).toContain("[User Preferences]");
37 - expect(out).toContain("[Continue Now]");
38 - expect(out).toContain("- Current request: Fix the auth bug (#1)");
39 - expect(out).toContain("[user]\nFix the auth bug (#1)");
40 - expect(out).toContain(
41 - "prune: 10 entries summarized; before 18.9k tok; raw kept 3 entries",
42 - );
43 - expect(out).toContain("Use prune_recall");
44 - expect(out).not.toContain("vcc_recall");
45 - });
47 - it("caps transcript tail", () => {
48 - const data = emptyData();
49 - for (let i = 1; i <= 5; i++) {
50 - data.transcript.push({
51 - role: "user",
52 - text: `message ${i}`,
53 - ref: `#${i}`,
54 - });
55 - }
57 - const out = format(data, { transcriptLimit: 2 }).summary;
58 - expect(out).toContain("...(3 earlier lines omitted)");
59 - expect(out).not.toContain("message 1 (#1)");
60 - expect(out).toContain("message 4 (#4)");
61 - expect(out).toContain("message 5 (#5)");
62 - });
64 - it("renders recall note once", () => {
65 - const data = emptyData();
66 - data.transcript.push({ role: "user", text: "hello", ref: "#1" });
67 - const out = format(data).summary;
68 - expect(out.match(/Use prune_recall/g)?.length).toBe(1);
69 - });
71 - it("renders assistant text, tool without cmd, and errors", () => {
72 - const data = emptyData();
73 - data.transcript.push(
74 - { role: "assistant", text: "Done", ref: "#2" },
75 - { role: "assistant", text: "", tool: "bash", ref: "#3" },
76 - { role: "error", text: "[ERROR] bash", ref: "#4" },
77 - );
78 - const out = format(data).summary;
79 - expect(out).toContain("[assistant]\nDone (#2)");
80 - expect(out).toContain("* bash (#3)");
81 - expect(out).toContain("[tool_error] [ERROR] bash (#4)");
82 - });
84 - it("caps long file lists and omits token estimate when unavailable", () => {
85 - const data = emptyData();
86 - for (let i = 0; i < 12; i++) data.files.modified.add(`file${i}.ts`);
87 - const out = format(data, {
88 - sourceEntriesProcessed: 12,
89 - tailKept: 0,
90 - }).summary;
91 - expect(out).toContain("(+2 more)");
92 - expect(out).toContain("prune: 12 entries summarized; raw kept 0 entries");
93 - expect(out).not.toContain("; before");
94 - });
96 - it("formats small token estimates without k suffix", () => {
97 - const data = emptyData();
98 - const out = format(data, {
99 - sourceEntriesProcessed: 1,
100 - tailKept: 0,
101 - tokenEstimate: 999,
102 - }).summary;
103 - expect(out).toContain("before 999 tok");
104 - });
105 -});

extensions/prune/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { afterEach, describe, expect, it } from "bun:test";
2 -import path from "node:path";
3 -import {
4 - createTestSession,
5 - type TestSession,
6 -} from "@marcfargas/pi-test-harness";
8 -describe("pi-test-harness isolation", () => {
9 - let t: TestSession | undefined;
10 - afterEach(() => t?.dispose());
12 - it("loads only prune extension with temp cwd and absolute path", async () => {
13 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
14 - t = await createTestSession({ extensions: [prunePath] });
16 - const loaded = t.session.extensionRunner.extensions.map(
17 - (e: { path: string }) => e.path,
18 - );
19 - expect(loaded).toHaveLength(1);
20 - expect(loaded[0]).toBe(prunePath);
21 - });
23 - it("registers prune_recall tool and prune commands", async () => {
24 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
25 - t = await createTestSession({ extensions: [prunePath] });
27 - const [extension] = t.session.extensionRunner.extensions;
28 - expect([...extension.tools.keys()]).toContain("prune_recall");
29 - expect([...extension.commands.keys()]).toContain("prune");
30 - expect([...extension.commands.keys()]).toContain("prune-recall");
31 - });
33 - it("session_before_compact returns prune summary", async () => {
34 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
35 - t = await createTestSession({ extensions: [prunePath] });
37 - const result = await t.session.extensionRunner.emit({
38 - type: "session_before_compact",
39 - preparation: {
40 - firstKeptEntryId: "keep-1",
41 - messagesToSummarize: [
42 - { role: "user", content: "Fix auth token refresh" },
43 - { role: "assistant", content: "Working on it" },
44 - {
45 - role: "toolResult",
46 - toolName: "write",
47 - content: [
48 - {
49 - type: "text",
50 - text: "Successfully wrote 123 bytes to src/auth.ts",
51 - },
52 - ],
53 - isError: false,
54 - },
55 - ],
56 - turnPrefixMessages: [{ role: "user", content: "Also update docs" }],
57 - isSplitTurn: false,
58 - tokensBefore: 1234,
59 - fileOps: { readFiles: [], modifiedFiles: [] },
60 - settings: { enabled: true, reserveTokens: 1000, keepRecentTokens: 1 },
61 - },
62 - branchEntries: [],
63 - signal: new AbortController().signal,
64 - });
66 - expect(result?.compaction?.summary).toContain("[Session Goal]");
67 - expect(result?.compaction?.summary).toContain("Fix auth token refresh");
68 - expect(result?.compaction?.summary).toContain(
69 - "before 1.2k tok; raw kept 0 entries; split-prefix 1",
70 - );
71 - expect(result?.compaction?.summary).toContain("[Continue Now]");
72 - expect(result?.compaction?.summary).not.toContain(
73 - "- Successfully wrote 123 bytes",
74 - );
75 - expect(result?.compaction?.firstKeptEntryId).toBe("keep-1");
76 - expect(result?.compaction?.details).toEqual({
77 - kind: "prune",
78 - version: 1,
79 - sourceEntriesProcessed: 4,
80 - tailKept: 0,
81 - splitPrefixMessages: 1,
82 - });
83 - });
85 - it("moves oversized raw tail into summary at safe boundary", async () => {
86 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
87 - t = await createTestSession({ extensions: [prunePath] });
89 - const result = await t.session.extensionRunner.emit({
90 - type: "session_before_compact",
91 - preparation: {
92 - firstKeptEntryId: "keep-old",
93 - messagesToSummarize: [],
94 - turnPrefixMessages: [],
95 - isSplitTurn: false,
96 - tokensBefore: 90000,
97 - fileOps: { readFiles: [], modifiedFiles: [] },
98 - settings: { enabled: true, reserveTokens: 1000, keepRecentTokens: 1 },
99 - },
100 - branchEntries: [
101 - {
102 - type: "message",
103 - id: "keep-old",
104 - parentId: null,
105 - timestamp: "",
106 - message: { role: "user", content: "old kept huge ".repeat(20000) },
107 - },
108 - {
109 - type: "message",
110 - id: "safe-new",
111 - parentId: "keep-old",
112 - timestamp: "",
113 - message: { role: "user", content: "new request" },
114 - },
115 - {
116 - type: "message",
117 - id: "tail-assistant",
118 - parentId: "safe-new",
119 - timestamp: "",
120 - message: { role: "assistant", content: "done" },
121 - },
122 - ],
123 - signal: new AbortController().signal,
124 - });
126 - expect(result?.compaction?.firstKeptEntryId).toBe("safe-new");
127 - expect(result?.compaction?.details).toMatchObject({
128 - sourceEntriesProcessed: 1,
129 - tailKept: 2,
130 - });
131 - expect(result?.compaction?.summary).toContain("raw kept 2 entries");
132 - });
134 - it("activates prune_recall only after prune compaction exists in branch", async () => {
135 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
136 - t = await createTestSession({ extensions: [prunePath] });
138 - await t.session.extensionRunner.emit({
139 - type: "session_start",
140 - reason: "startup",
141 - });
142 - expect(t.session.getActiveToolNames()).not.toContain("prune_recall");
144 - const keptId = t.session.sessionManager.appendMessage({
145 - role: "user",
146 - content: [{ type: "text", text: "kept" }],
147 - });
148 - t.session.sessionManager.appendCompaction(
149 - "Use prune_recall to search for prior work, decisions, and context from before this summary.",
150 - keptId,
151 - 100,
152 - { kind: "prune", version: 1 },
153 - true,
154 - );
156 - await t.session.extensionRunner.emit({
157 - type: "session_start",
158 - reason: "resume",
159 - });
160 - expect(t.session.getActiveToolNames()).toContain("prune_recall");
161 - });
163 - it("prune_recall tool searches session manager entries", async () => {
164 - const prunePath = path.resolve(import.meta.dir, "../index.ts");
165 - t = await createTestSession({ extensions: [prunePath] });
166 - t.session.sessionManager.appendMessage({
167 - role: "user",
168 - content: [{ type: "text", text: "Fix auth token refresh" }],
169 - });
171 - const tool = t.session.extensionRunner.getToolDefinition("prune_recall");
172 - const result = await tool.execute(
173 - "call-1",
174 - { query: "auth", limit: 5 },
175 - undefined,
176 - undefined,
177 - t.session.extensionRunner.createContext(),
178 - );
180 - const text = result.content
181 - .map((part: { text?: string }) => part.text ?? "")
182 - .join("\n");
183 - expect(text).toContain("user score=1");
184 - expect(text).toContain("Fix auth token refresh");
185 - });
186 -});

extensions/prune/__tests__/merge.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "bun:test";
2 -import { RECALL_NOTE, SEPARATOR } from "../src/constants.ts";
3 -import { merge } from "../src/merge.ts";
5 -const prev = `[Session Goal]\n- Fix auth\n\n[Files And Changes]\n- Modified: a.ts\n\n[Outstanding Context]\n- old error${SEPARATOR}[user]\nold (#1)${SEPARATOR}prune: 3 source entries processed; tail kept 1${SEPARATOR}${RECALL_NOTE}`;
6 -const fresh = `[Session Goal]\n- Fix auth\n- [Scope change]\n- Add tests\n\n[Files And Changes]\n- Modified: b.ts, a.ts\n- Read: c.ts\n\n[Outstanding Context]\n- new error${SEPARATOR}[user]\nfresh (#4)${SEPARATOR}prune: 6 source entries processed; tail kept 2${SEPARATOR}${RECALL_NOTE}`;
8 -describe("merge", () => {
9 - it("dedups sticky sections, replaces context, keeps recall note once", () => {
10 - const out = merge(prev, fresh);
11 - expect(out).toContain("- Fix auth");
12 - expect(out).toContain("- Add tests");
13 - expect(out.match(/- Fix auth/g)?.length).toBe(1);
14 - expect(out).toContain("- Modified: a.ts, b.ts");
15 - expect(out).toContain("- Read: c.ts");
16 - expect(out).not.toContain("old error");
17 - expect(out).toContain("new error");
18 - expect(out.match(/Use prune_recall/g)?.length).toBe(1);
19 - expect(out).not.toContain("vcc_recall");
20 - });
22 - it("keeps previous then fresh transcript order", () => {
23 - const out = merge(prev, fresh);
24 - expect(out.indexOf("old (#1)")).toBeLessThan(out.indexOf("fresh (#4)"));
25 - });
27 - it("drops old sticky pollution that came from tool output misclassified as user goals", () => {
28 - const polluted = `[Session Goal]\n- Fix real task\n- Successfully wrote 123 bytes to src/a.ts\n- bunx prettier --write .\n\n[User Preferences]\n- local format = function ()${SEPARATOR}[user]\nold (#1)${SEPARATOR}${RECALL_NOTE}`;
29 - const out = merge(polluted, fresh);
30 - expect(out).toContain("- Fix real task");
31 - expect(out).not.toContain("Successfully wrote 123 bytes");
32 - expect(out).not.toContain("bunx prettier");
33 - expect(out).not.toContain("local format = function");
34 - });
35 -});

extensions/prune/__tests__/real/minimax.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "bun:test";
2 -import fs from "node:fs";
3 -import os from "node:os";
4 -import path from "node:path";
5 -import { getModel } from "@earendil-works/pi-ai";
6 -import {
7 - AuthStorage,
8 - createAgentSession,
9 - DefaultResourceLoader,
10 - ModelRegistry,
11 - SessionManager,
12 - SettingsManager,
13 -} from "@earendil-works/pi-coding-agent";
15 -const real = process.env.PRUNE_REAL === "1";
16 -const d = real ? describe : describe.skip;
18 -d("real MiniMax integration", () => {
19 - it("runs isolated SDK session with only prune loaded and manual compaction", async () => {
20 - const temp = fs.mkdtempSync(path.join(os.tmpdir(), "prune-real-"));
21 - const cwd = path.join(temp, "cwd");
22 - const agentDir = path.join(temp, "agent");
23 - fs.mkdirSync(cwd, { recursive: true });
24 - fs.mkdirSync(agentDir, { recursive: true });
26 - const prunePath = path.resolve(import.meta.dir, "../../index.ts");
27 - const settingsManager = SettingsManager.inMemory({
28 - defaultProvider: "minimax",
29 - defaultModel: "MiniMax-M2.7-highspeed",
30 - defaultThinkingLevel: "off",
31 - compaction: {
32 - enabled: true,
33 - reserveTokens: 1000,
34 - keepRecentTokens: 1,
35 - },
36 - });
38 - const loader = new DefaultResourceLoader({
39 - cwd,
40 - agentDir,
41 - settingsManager,
42 - noExtensions: true,
43 - noSkills: true,
44 - noPromptTemplates: true,
45 - noThemes: true,
46 - noContextFiles: true,
47 - additionalExtensionPaths: [prunePath],
48 - });
49 - await loader.reload();
51 - const authStorage = AuthStorage.create();
52 - const modelRegistry = ModelRegistry.create(authStorage);
53 - const model = getModel("minimax", "MiniMax-M2.7-highspeed");
54 - const events: string[] = [];
56 - const { session, extensionsResult } = await createAgentSession({
57 - cwd,
58 - agentDir,
59 - authStorage,
60 - modelRegistry,
61 - model,
62 - thinkingLevel: "off",
63 - sessionManager: SessionManager.inMemory(),
64 - settingsManager,
65 - resourceLoader: loader,
66 - noTools: "all",
67 - });
69 - try {
70 - expect(extensionsResult.extensions.map((e) => e.path)).toEqual([
71 - prunePath,
72 - ]);
73 - session.subscribe((event) => events.push(event.type));
75 - const big = "Fix auth token refresh. Keep answer to exactly OK. ".repeat(
76 - 80,
77 - );
78 - await session.prompt(big);
79 - await session.agent.waitForIdle();
80 - await session.prompt("Also update docs. Keep answer to exactly OK.");
81 - await session.agent.waitForIdle();
83 - const result = await session.compact();
84 - expect(events).toContain("compaction_start");
85 - expect(events).toContain("compaction_end");
86 - expect(result.summary).toContain("[Session Goal]");
87 - expect(result.summary).toContain("---");
88 - expect(result.summary).toContain("Use prune_recall");
89 - expect(result.summary).not.toContain("vcc_recall");
91 - const compaction = session.sessionManager
92 - .getEntries()
93 - .find((e) => e.type === "compaction");
94 - expect(compaction).toBeTruthy();
95 - expect(compaction?.fromHook).toBe(true);
96 - } finally {
97 - session.dispose();
98 - fs.rmSync(temp, { recursive: true, force: true });
99 - }
100 - }, 120000);
101 -});

extensions/prune/__tests__/recall.test.ts

Deleted
deleted file mode 100644
1 -import { describe, expect, it } from "bun:test";
2 -import { formatRecallResults, recall } from "../src/recall.ts";
3 -import type { SearchResult } from "../src/types.ts";
5 -const entries = [
6 - {
7 - type: "message",
8 - message: { role: "user", content: "Fix auth token refresh" },
9 - },
10 - {
11 - type: "message",
12 - message: { role: "assistant", content: "Read session.ts" },
13 - },
14 - { type: "message", message: { role: "user", content: "Update docs" } },
15 -];
16 -const source = {
17 - getBranch: () => entries.slice(0, 2),
18 - getEntries: () => entries,
19 -};
21 -describe("recall", () => {
22 - it("searches lineage by default", () => {
23 - const results = recall(source, { query: "auth" });
24 - expect(results).toHaveLength(1);
25 - expect(results[0].index).toBe(1);
26 - });
28 - it("searches all entries when requested", () => {
29 - const results = recall(source, { query: "docs", scope: "all" });
30 - expect(results).toHaveLength(1);
31 - expect(results[0].index).toBe(3);
32 - });
34 - it("expands exact refs", () => {
35 - const results = recall(source, { query: "missing", expand: [2] });
36 - expect(results).toHaveLength(1);
37 - expect(results[0].index).toBe(2);
38 - expect(results[0].context).toContain("Read session.ts");
39 - });
41 - it("matches regex query strings", () => {
42 - const results = recall(source, { query: "auth.*refresh" });
43 - expect(results).toHaveLength(1);
44 - expect(results[0].score).toBe(10);
45 - });
47 - it("matches RegExp query objects", () => {
48 - const results = recall(source, { query: /session\.ts/ });
49 - expect(results).toHaveLength(1);
50 - expect(results[0].index).toBe(2);
51 - });
53 - it("falls back to terms for invalid regex-like query", () => {
54 - const results = recall(source, { query: "[auth" });
55 - expect(results).toHaveLength(1);
56 - });
58 - it("searches compaction and custom message entries", () => {
59 - const richSource = {
60 - getBranch: () => [
61 - { type: "compaction", summary: "[Session Goal]\n- Fix billing flow" },
62 - {
63 - type: "custom_message",
64 - content: [{ type: "text", text: "custom array content" }],
65 - },
66 - { type: "custom_message", content: undefined },
67 - { type: "label" },
68 - ],
69 - getEntries: () => [],
70 - };
71 - const compaction = recall(richSource, { query: "billing" })[0];
72 - expect(compaction.context).toContain("billing");
73 - expect(compaction.role).toBe("assistant");
74 - expect(compaction.entry.content).toContain("billing");
75 - expect(recall(richSource, { query: "custom" })[0].context).toContain(
76 - "custom",
77 - );
78 - });
80 - it("maps real Pi toolResult role to tool in recall output", () => {
81 - const richSource = {
82 - getBranch: () => [
83 - {
84 - type: "message",
85 - message: {
86 - role: "toolResult",
87 - toolName: "bash",
88 - content: [{ type: "text", text: "failing test output" }],
89 - },
90 - },
91 - ],
92 - getEntries: () => [],
93 - };
94 - const result = recall(richSource, { query: "failing" })[0];
95 - expect(result.role).toBe("tool");
96 - expect(formatRecallResults([result])).toContain("#1 tool score=1");
97 - });
99 - it("searches message content parts including tool calls and thinking", () => {
100 - const richSource = {
101 - getBranch: () => [
102 - {
103 - type: "message",
104 - message: {
105 - role: "assistant",
106 - content: [
107 - { type: "text", text: "visible text" },
108 - {
109 - type: "toolCall",
110 - name: "read",
111 - arguments: { path: "src/auth.ts" },
112 - },
113 - { type: "thinking", thinking: "hidden thought" },
114 - { type: "image", mimeType: "image/png" },
115 - ],
116 - },
117 - },
118 - {
119 - type: "message",
120 - message: { role: "assistant" },
121 - },
122 - ],
123 - getEntries: () => [],
124 - };
125 - expect(recall(richSource, { query: "visible" })).toHaveLength(1);
126 - expect(recall(richSource, { query: "auth.ts" })).toHaveLength(1);
127 - expect(recall(richSource, { query: "hidden" })).toHaveLength(1);
128 - });
130 - it("returns long snippets around match", () => {
131 - const long = `${"a ".repeat(200)}needle ${"b ".repeat(200)}`;
132 - const richSource = {
133 - getBranch: () => [
134 - { type: "message", message: { role: "user", content: long } },
135 - ],
136 - getEntries: () => [],
137 - };
138 - const result = recall(richSource, { query: "needle" })[0];
139 - expect(result.context?.startsWith("...")).toBe(true);
140 - expect(result.context).toContain("needle");
141 - });
143 - it("formats results without context", () => {
144 - const results: SearchResult[] = [
145 - {
146 - index: 7,
147 - entry: { role: "assistant", content: "x" },
148 - role: "assistant",
149 - score: 2,
150 - },
151 - ];
152 - expect(formatRecallResults(results)).toBe("#7 assistant score=2");
153 - });
155 - it("formats empty results", () => {
156 - expect(formatRecallResults([])).toBe("No matches.");
157 - });
158 -});

extensions/prune/assets/prune.gif

Deleted
deleted file mode 100644

Previous version contains binary or non-UTF-8 data.

extensions/prune/fixtures/simple.jsonl

Deleted
deleted file mode 100644
1 -{"role":"user","content":"Fix the auth bug, users cannot log in after password reset","timestamp":1704067200000}
2 -{"role":"assistant","content":"I'll investigate the token refresh logic.","timestamp":1704067201000}
3 -{"role":"assistant","content":[{"type":"toolCall","name":"read","arguments":{"path":"src/auth/session.ts"}}],"timestamp":1704067202000}
4 -{"role":"tool","toolName":"read","content":"async function refreshToken() {\n return null;\n}","timestamp":1704067203000}
5 -{"role":"assistant","content":"Found the bug. The refresh returns null instead of generating a new token.","timestamp":1704067204000}
6 -{"role":"assistant","content":[{"type":"toolCall","name":"edit","arguments":{"path":"src/auth/session.ts","newText":"await generateToken(userId)"}}],"timestamp":1704067205000}
7 -{"role":"tool","toolName":"edit","content":"Applied edit.","timestamp":1704067206000}
8 -{"role":"assistant","content":"Now let me run the tests to verify the fix.","timestamp":1704067207000}
9 -{"role":"assistant","content":[{"type":"toolCall","name":"bash","arguments":{"command":"npm test src/auth/session.test.ts"}}],"timestamp":1704067208000}
10 -{"role":"tool","toolName":"bash","content":"✓ All tests pass","timestamp":1704067209000}

extensions/prune/index.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — Lossless Conversation Compactor
3 - *
4 - * Algorithmic compaction that preserves searchable transcript.
5 - * Replaces default LLM summarization with deterministic extraction.
6 - */
8 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
9 -import { Type } from "typebox";
10 -import {
11 - DEFAULT_SECTION_LIMIT,
12 - DEFAULT_TRANSCRIPT_LIMIT,
13 - MAX_RAW_TAIL_TOKENS,
14 -} from "./src/constants.ts";
15 -import { extract } from "./src/extract.ts";
16 -import { format } from "./src/format.ts";
17 -import { merge } from "./src/merge.ts";
18 -import { normalize } from "./src/normalize.ts";
19 -import { formatRecallResults, recall } from "./src/recall.ts";
20 -import type { Message, PruneSettings } from "./src/types.ts";
22 -// ─── Settings ──────────────────────────────────────────────────────────────
24 -const RECALL_TOOL = "prune_recall";
25 -const PRUNE_DETAILS_KIND = "prune";
27 -interface PruneCompactionDetails {
28 - kind: typeof PRUNE_DETAILS_KIND;
29 - version: 1;
30 - sourceEntriesProcessed: number;
31 - tailKept: number;
32 - splitPrefixMessages: number;
35 -const DEFAULT_SETTINGS: Required<PruneSettings> = {
36 - overrideDefault: true,
37 - sectionLimit: DEFAULT_SECTION_LIMIT,
38 - transcriptLimit: DEFAULT_TRANSCRIPT_LIMIT,
39 - toolCapPerTurn: 8,
40 - debug: false,
41 -};
43 -// ─── State ────────────────────────────────────────────────────────────────
45 -let settings = { ...DEFAULT_SETTINGS };
47 -// ─── Helpers ────────────────────────────────────────────────────────────
49 -function loadSettings(pi: ExtensionAPI): void {
50 - const raw = (
51 - pi as unknown as {
52 - settingsManager?: { getSettings?: () => { prune?: PruneSettings } };
53 - }
54 - ).settingsManager?.getSettings?.();
55 - if (raw?.prune) {
56 - settings = { ...DEFAULT_SETTINGS, ...raw.prune };
57 - }
60 -function isPruneCompaction(entry: unknown): boolean {
61 - const e = entry as {
62 - type?: string;
63 - summary?: string;
64 - fromHook?: boolean;
65 - details?: { kind?: string };
66 - };
67 - if (e?.type !== "compaction") return false;
68 - if (e.details?.kind === PRUNE_DETAILS_KIND) return true;
69 - // Backwards-compatible detection for prune compactions created before details existed.
70 - return (
71 - e.fromHook === true &&
72 - typeof e.summary === "string" &&
73 - e.summary.includes("Use prune_recall")
74 - );
77 -function setContains(values: string[], value: string): boolean {
78 - return values.includes(value);
81 -// ─── Core prune function ─────────────────────────────────────────────────
83 -function prune(
84 - messages: Message[],
85 - previous?: string,
86 - metadata: {
87 - sourceEntriesProcessed?: number;
88 - tailKept?: number;
89 - splitPrefixMessages?: number;
90 - tokenEstimate?: number;
91 - } = {},
92 -): string {
93 - const blocks = normalize(messages);
94 - const data = extract(blocks, { toolCapPerTurn: settings.toolCapPerTurn });
96 - const output = format(data, {
97 - sectionLimit: settings.sectionLimit,
98 - transcriptLimit: settings.transcriptLimit,
99 - ...metadata,
100 - });
102 - const summary = previous ? merge(previous, output.summary) : output.summary;
104 - if (settings.debug) {
105 - console.log("[prune]", {
106 - blocks: blocks.length,
107 - outputLines: output.stats.messagesOut,
108 - elapsedMs: output.stats.elapsedMs.toFixed(2),
109 - });
110 - }
112 - return summary;
115 -function toPruneMessage(message: unknown): Message | undefined {
116 - const m = message as {
117 - role?: string;
118 - content?:
119 - | string
120 - | Array<{
121 - type: string;
122 - text?: string;
123 - name?: string;
124 - arguments?: Record<string, unknown>;
125 - thinking?: string;
126 - }>;
127 - toolName?: string;
128 - isError?: boolean;
129 - command?: string;
130 - output?: string;
131 - exitCode?: number;
132 - summary?: string;
133 - };
135 - switch (m.role) {
136 - case "user":
137 - return { role: "user", content: m.content };
138 - case "assistant":
139 - return { role: "assistant", content: m.content };
140 - case "tool":
141 - case "toolResult":
142 - return {
143 - role: "tool",
144 - content: m.content,
145 - toolName: m.toolName,
146 - isError: m.isError,
147 - };
148 - case "bashExecution":
149 - return {
150 - role: "tool",
151 - content: m.output ?? "",
152 - toolName: "bash",
153 - isError: typeof m.exitCode === "number" ? m.exitCode !== 0 : false,
154 - };
155 - case "branchSummary":
156 - case "compactionSummary":
157 - return m.summary ? { role: "assistant", content: m.summary } : undefined;
158 - case "custom":
159 - return undefined;
160 - default:
161 - if (settings.debug)
162 - console.log("[prune] skipped unsupported message role", m.role);
163 - return undefined;
164 - }
167 -type SessionEntryLike = {
168 - type?: string;
169 - id?: string;
170 - message?: unknown;
171 - summary?: string;
172 - content?: unknown;
173 -};
175 -function planRawTail(
176 - branchEntries: unknown[],
177 - firstKeptEntryId: string,
178 -): { firstKeptEntryId: string; extraMessages: Message[]; rawTailKept: number } {
179 - const entries = branchEntries as SessionEntryLike[];
180 - const oldIndex = entries.findIndex((entry) => entry.id === firstKeptEntryId);
181 - if (oldIndex < 0)
182 - return { firstKeptEntryId, extraMessages: [], rawTailKept: 0 };
184 - let accumulated = 0;
185 - let candidate = oldIndex;
186 - for (let i = entries.length - 1; i >= oldIndex; i--) {
187 - const next = accumulated + estimateEntryTokens(entries[i]);
188 - if (next > MAX_RAW_TAIL_TOKENS) break;
189 - accumulated = next;
190 - if (isSafeBoundary(entries[i])) candidate = i;
191 - }
193 - const newFirstKeptEntryId = entries[candidate]?.id ?? firstKeptEntryId;
194 - const extraMessages =
195 - candidate > oldIndex
196 - ? entries
197 - .slice(oldIndex, candidate)
198 - .map(entryToPruneMessage)
199 - .filter((message): message is Message => message !== undefined)
200 - : [];
202 - return {
203 - firstKeptEntryId: newFirstKeptEntryId,
204 - extraMessages,
205 - rawTailKept: entries.length - candidate,
206 - };
209 -function entryToPruneMessage(entry: SessionEntryLike): Message | undefined {
210 - if (entry.type === "message") return toPruneMessage(entry.message);
211 - if (entry.type === "branch_summary" && entry.summary)
212 - return { role: "assistant", content: entry.summary };
213 - if (entry.type === "custom_message")
214 - return { role: "user", content: entry.content as Message["content"] };
215 - return undefined;
218 -function isSafeBoundary(entry: SessionEntryLike): boolean {
219 - if (entry.type === "custom_message" || entry.type === "branch_summary")
220 - return true;
221 - if (entry.type !== "message") return false;
222 - const role = (entry.message as { role?: string } | undefined)?.role;
223 - return role === "user" || role === "assistant" || role === "bashExecution";
226 -function estimateEntryTokens(entry: SessionEntryLike): number {
227 - if (entry.type === "message") return estimateUnknownTokens(entry.message);
228 - if (entry.type === "branch_summary")
229 - return estimateStringTokens(entry.summary ?? "");
230 - if (entry.type === "custom_message")
231 - return estimateUnknownTokens(entry.content);
232 - return 0;
235 -function estimateUnknownTokens(value: unknown): number {
236 - if (typeof value === "string") return estimateStringTokens(value);
237 - if (Array.isArray(value))
238 - return estimateStringTokens(
239 - value
240 - .map((part) => {
241 - if (typeof part !== "object" || part == null) return String(part);
242 - const p = part as {
243 - text?: string;
244 - thinking?: string;
245 - arguments?: unknown;
246 - name?: string;
247 - };
248 - if (p.text) return p.text;
249 - if (p.thinking) return p.thinking;
250 - if (p.arguments)
251 - return `${p.name ?? ""} ${JSON.stringify(p.arguments)}`;
252 - return JSON.stringify(p);
253 - })
254 - .join("\n"),
255 - );
256 - if (value && typeof value === "object" && "content" in value) {
257 - return estimateUnknownTokens((value as { content?: unknown }).content);
258 - }
259 - return estimateStringTokens(JSON.stringify(value ?? ""));
262 -function estimateStringTokens(text: string): number {
263 - return Math.ceil(text.length / 4);
266 -// ─── Extension ────────────────────────────────────────────────────────────
268 -export default function (pi: ExtensionAPI) {
269 - loadSettings(pi);
271 - function enableRecallTool(): void {
272 - const active = pi.getActiveTools();
273 - if (!setContains(active, RECALL_TOOL))
274 - pi.setActiveTools([...active, RECALL_TOOL]);
275 - }
277 - function disableRecallTool(): void {
278 - const active = pi.getActiveTools();
279 - if (setContains(active, RECALL_TOOL))
280 - pi.setActiveTools(active.filter((name) => name !== RECALL_TOOL));
281 - }
283 - function syncRecallTool(ctx: {
284 - sessionManager: { getBranch(): unknown[] };
285 - }): void {
286 - const hasPruneSummary = ctx.sessionManager
287 - .getBranch()
288 - .some(isPruneCompaction);
289 - if (hasPruneSummary) enableRecallTool();
290 - else disableRecallTool();
291 - }
293 - // ─── session_before_compact ──────────────────────────────────────────
295 - pi.on("session_before_compact", async (event) => {
296 - const { preparation } = event;
298 - if (!settings.overrideDefault) return;
300 - const tail = planRawTail(event.branchEntries, preparation.firstKeptEntryId);
301 - const allMessages = [
302 - ...preparation.messagesToSummarize,
303 - ...preparation.turnPrefixMessages,
304 - ]
305 - .map(toPruneMessage)
306 - .filter((message): message is Message => message !== undefined);
307 - allMessages.push(...tail.extraMessages);
309 - const summary = prune(allMessages, preparation.previousSummary, {
310 - sourceEntriesProcessed: allMessages.length,
311 - tailKept: tail.rawTailKept,
312 - splitPrefixMessages: preparation.turnPrefixMessages.length,
313 - tokenEstimate: preparation.tokensBefore,
314 - });
316 - const details: PruneCompactionDetails = {
317 - kind: PRUNE_DETAILS_KIND,
318 - version: 1,
319 - sourceEntriesProcessed: allMessages.length,
320 - tailKept: tail.rawTailKept,
321 - splitPrefixMessages: preparation.turnPrefixMessages.length,
322 - };
324 - return {
325 - compaction: {
326 - summary,
327 - firstKeptEntryId: tail.firstKeptEntryId,
328 - tokensBefore: preparation.tokensBefore,
329 - details,
330 - },
331 - };
332 - });
334 - // ─── recall tool activation ──────────────────────────────────────────
336 - pi.on("session_start", async (_event, ctx) => {
337 - syncRecallTool(ctx);
338 - });
340 - pi.on("session_tree", async (_event, ctx) => {
341 - syncRecallTool(ctx);
342 - });
344 - // ─── session_compact ─────────────────────────────────────────────────
346 - pi.on("session_compact", async (event, ctx) => {
347 - if (!event.fromExtension || !isPruneCompaction(event.compactionEntry))
348 - return;
349 - enableRecallTool();
350 - const entry = event.compactionEntry as {
351 - id?: string;
352 - summary?: string;
353 - tokensBefore?: number;
354 - };
355 - const lineCount = entry.summary?.split("\n").length ?? 0;
356 - const msg = `prune compaction saved${entry.id ? ` #${entry.id}` : ""}: ${lineCount} lines${entry.tokensBefore ? ` from ${entry.tokensBefore.toLocaleString()} tok` : ""}`;
357 - if (settings.debug) console.log("[prune]", msg);
358 - if (ctx.hasUI) ctx.ui.notify(msg, "info");
359 - });
361 - // ─── Tool: prune_recall ───────────────────────────────────────────────
363 - pi.registerTool({
364 - name: "prune_recall",
365 - label: "Prune Recall",
366 - description:
367 - "Search compacted session history. Returns matching messages with relevance scores.",
368 - parameters: Type.Object({
369 - query: Type.String({
370 - description: "Search query (string or regex pattern)",
371 - }),
372 - scope: Type.Optional(
373 - Type.Union([Type.Literal("lineage"), Type.Literal("all")]),
374 - ),
375 - limit: Type.Optional(Type.Number({ minimum: 1, maximum: 20 })),
376 - expand: Type.Optional(Type.Array(Type.Number())),
377 - }),
379 - async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
380 - const results = recall(ctx.sessionManager, {
381 - query: params.query,
382 - scope: params.scope ?? "lineage",
383 - limit: params.limit ?? 5,
384 - expand: params.expand ?? [],
385 - });
386 - return {
387 - content: [{ type: "text", text: formatRecallResults(results) }],
388 - details: { count: results.length },
389 - };
390 - },
391 - });
393 - // ─── Command: /prune ───────────────────────────────────────────────
395 - pi.registerCommand("prune", {
396 - description: "Run lossless compaction: /prune [focus?]",
397 - handler: async (_args, ctx) => {
398 - if (settings.debug) console.log("[prune] Manual compaction requested");
399 - ctx.compact({
400 - onComplete: (result) => {
401 - if (ctx.hasUI)
402 - ctx.ui.notify(
403 - `prune compaction complete: ${result.summary.split("\n").length} lines`,
404 - "info",
405 - );
406 - },
407 - onError: (error) => {
408 - if (ctx.hasUI)
409 - ctx.ui.notify(`prune compaction failed: ${error.message}`, "error");
410 - else console.error(`[prune] compaction failed: ${error.message}`);
411 - },
412 - });
413 - if (ctx.hasUI) ctx.ui.notify("prune compaction started", "info");
414 - },
415 - });
417 - // ─── Command: /prune-recall ────────────────────────────────────────
419 - pi.registerCommand("prune-recall", {
420 - description: "Search compacted history: /prune-recall <query> [scope]",
421 - handler: async (args, ctx) => {
422 - const parts = args.trim().split(/\s+/).filter(Boolean);
423 - const scope = parts.at(-1) === "all" ? "all" : "lineage";
424 - const query =
425 - scope === "all" ? parts.slice(0, -1).join(" ") : parts.join(" ");
426 - const results = recall(ctx.sessionManager, { query, scope, limit: 10 });
427 - const text = formatRecallResults(results);
428 - if (ctx.hasUI) {
429 - ctx.ui.notify(text.slice(0, 1000), results.length ? "info" : "warning");
430 - } else {
431 - console.log(text);
432 - }
433 - },
434 - });

extensions/prune/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-prune",
3 - "description": "Lossless conversation compactor for pi",
4 - "type": "module",
5 - "main": "index.ts",
6 - "scripts": {
7 - "test": "bun test ./__tests__/*.test.ts",
8 - "test:watch": "bun test ./__tests__/*.test.ts --watch",
9 - "test:unit": "bun test ./__tests__/extract.test.ts ./__tests__/format.test.ts ./__tests__/merge.test.ts ./__tests__/recall.test.ts",
10 - "test:harness": "bun test ./__tests__/harness.test.ts",
11 - "test:real": "PRUNE_REAL=1 bun test ./__tests__/real/*.test.ts --timeout 120000",
12 - "test:all": "bun run test && bun run test:real",
13 - "test:coverage": "bun test ./__tests__/*.test.ts --coverage"
14 - },
15 - "keywords": [
16 - "pi",
17 - "extension",
18 - "compaction",
19 - "memory",
20 - "pi-extension"
21 - ],
22 - "license": "MIT",
23 - "peerDependencies": {
24 - "@earendil-works/pi-ai": "*",
25 - "@earendil-works/pi-coding-agent": "*",
26 - "typebox": "*"
27 - },
28 - "devDependencies": {
29 - "@marcfargas/pi-test-harness": "^0.6.1"
30 - },
31 - "private": true
32 -}

extensions/prune/src/constants.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — constants
3 - */
5 -// ─── Limits ─────────────────────────────────────────────────────────────────
7 -export const DEFAULT_SECTION_LIMIT = 8;
8 -export const DEFAULT_TRANSCRIPT_LIMIT = 60;
9 -export const DEFAULT_TOOL_CAP = 8;
10 -export const MAX_RAW_TAIL_TOKENS = 32000;
12 -export const TRUNCATE_USER = 256;
13 -export const TRUNCATE_ASSISTANT = 200;
15 -// ─── Blockers ─────────────────────────────────────────────────────────────
17 -export const BLOCKER_RE =
18 - /\b(fail(ed|s|ure|ing)?|broken|cannot|can't|won't work|does not work|doesn't work|still (broken|failing|wrong)|blocked|blocker|not (fixed|resolved|working)|crash(es|ed|ing)?)\b/i;
20 -// ─── Self-talk prefixes ──────────────────────────────────────────────────
22 -export const SELF_TALK_PREFIX_RE =
23 - /^\s*(?:hmm|wait|actually|oh|okay|ok|well|so)[,.!\s-]+/i;
25 -// ─── Goal patterns ────────────────────────────────────────────────────────
27 -export const GOAL_VERBS = [
28 - "scan",
29 - "check",
30 - "fix",
31 - "implement",
32 - "add",
33 - "create",
34 - "build",
35 - "refactor",
36 - "debug",
37 - "investigate",
38 - "update",
39 - "remove",
40 - "delete",
41 - "migrate",
42 - "deploy",
43 - "test",
44 - "write",
45 - "set up",
46 - "spin",
47 - "run",
48 - "execute",
49 - "verify",
50 - "review",
51 - "analyze",
52 - "explain",
53 - "describe",
54 - "explore",
55 - "call",
56 - "use",
57 - "switch",
58 - "clean",
59 - "lint",
60 - "format",
61 - "do",
62 -];
64 -export const GOAL_RE = new RegExp(
65 - `\\b(${GOAL_VERBS.map((v) => v.replace(/ /g, "\\s+")).join("|")})\\b`,
66 - "i",
67 -);
69 -export const SCOPE_CHANGE_RE =
70 - /\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|for now)\b/i;
72 -export const NOISE_SHORT_RE =
73 - /^(ok|okay|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|noop)\s*[.!?]*$/i;
75 -export const NON_GOAL_RE =
76 - /^\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;
78 -export const TEMPLATE_SIGNAL_RE =
79 - /^\s*(<skill\b|```|For each\b|Do NOT\b|Analyze and propose\b|If [Tt]ask|Output:\s*$|here'?s a|ticket:)\b/i;
81 -export const INTERROGATIVE_RE =
82 - /^\s*(what|why|how|when|where|who|which|is|are|was|were|do|does|did|should|could|would)\b/i;
84 -// ─── Preference patterns ─────────────────────────────────────────────────
86 -export const PREF_PATTERNS = [
87 - /\bprefer(?:s|red|ring)?\s+\w/i,
88 - /\bdon'?t want\b/i,
89 - /\balways (?:use|do|run|prefer|keep|make|format|write|add|set|put|prefix|start|include|append|check)\b/i,
90 - /\bnever (?:use|do|run|push|commit|write|ignore|add|set|put|remove|delete|include|deploy)\b/i,
91 - /\bplease (?:use|avoid|keep|make|don'?t|do not|format|write)\b/i,
92 - /\b(?:style|format|language|naming)\s*[:=]\s*\S/i,
93 -];
95 -export const GENERATED_PREF_FALSE_POSITIVE_RE =
96 - /\bPOV\b.*\bformat\s*[:=]\s*engagement\b/i;
98 -// ─── File path patterns ─────────────────────────────────────────────────
100 -export const FILE_PATH_RE = /(?:^|\/)([^/\s]+\.[a-zA-Z0-9]+$)/;
102 -// ─── Section headers ─────────────────────────────────────────────────────
104 -export const SECTION_SESSION = "[Session Goal]";
105 -export const SECTION_FILES = "[Files And Changes]";
106 -export const SECTION_CONTEXT = "[Outstanding Context]";
107 -export const SECTION_PREFS = "[User Preferences]";
108 -export const SECTION_CONTINUE = "[Continue Now]";
109 -export const SECTION_COMMITS = "[Commits]";
110 -export const SEPARATOR = "\n\n---\n\n";
112 -export const RECALL_NOTE =
113 - "Use prune_recall to search for prior work, decisions, and context from before this summary.\nDo not redo work already completed.";

extensions/prune/src/extract.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — extract sections from blocks
3 - */
5 -import {
6 - BLOCKER_RE,
7 - DEFAULT_TOOL_CAP,
8 - GENERATED_PREF_FALSE_POSITIVE_RE,
9 - GOAL_RE,
10 - INTERROGATIVE_RE,
11 - NOISE_SHORT_RE,
12 - NON_GOAL_RE,
13 - PREF_PATTERNS,
14 - SCOPE_CHANGE_RE,
15 - SELF_TALK_PREFIX_RE,
16 - TEMPLATE_SIGNAL_RE,
17 - TRUNCATE_ASSISTANT,
18 - TRUNCATE_USER,
19 -} from "./constants.ts";
20 -import type { Block, ExtractOutput, TranscriptEntry } from "./types.ts";
22 -/**
23 - * Extract structured sections from blocks.
24 - */
25 -export interface ExtractOptions {
26 - toolCapPerTurn?: number;
29 -export function extract(
30 - blocks: Block[],
31 - options: ExtractOptions = {},
32 -): ExtractOutput {
33 - const toolCapPerTurn = options.toolCapPerTurn ?? DEFAULT_TOOL_CAP;
34 - const goals: string[] = [];
35 - const scopeChanges: string[] = [];
36 - const modified = new Set<string>();
37 - const created = new Set<string>();
38 - const read = new Set<string>();
39 - const context: string[] = [];
40 - const preferences: string[] = [];
42 - let sawInitialGoalBlock = false;
44 - // First pass: extract goals, scope changes, preferences from user messages
45 - for (const block of blocks) {
46 - if (block.kind !== "user") continue;
48 - const lines = goalCandidateLines(block.text);
49 - if (lines.length > 0) {
50 - if (!sawInitialGoalBlock) {
51 - for (const line of lines.slice(0, 6))
52 - addUnique(goals, truncate(line, TRUNCATE_USER));
53 - sawInitialGoalBlock = true;
54 - } else {
55 - const leading = block.text.slice(0, 200);
56 - const isTask = GOAL_RE.test(leading) && lines[0].length > 5;
57 - const isScopeChange = SCOPE_CHANGE_RE.test(leading);
58 - if (isScopeChange || isTask) {
59 - for (const line of lines.slice(0, isScopeChange ? 3 : 2)) {
60 - addUnique(scopeChanges, truncate(line, TRUNCATE_USER));
61 - }
62 - }
63 - }
64 - }
66 - extractPreferences(block.text, preferences);
67 - }
69 - // Second pass: extract files and context from tool calls/results
70 - for (const block of blocks) {
71 - if (block.kind === "tool_call" && block.args) {
72 - extractFileFromArgs(
73 - block.name || "",
74 - block.args,
75 - modified,
76 - created,
77 - read,
78 - );
79 - }
80 - if (block.kind === "tool_result" && block.isError) {
81 - const error = block.name
82 - ? `[${block.name}] ${truncate(firstLine(block.text), 150)}`
83 - : truncate(firstLine(block.text), 150);
84 - addUnique(context, error);
85 - }
86 - }
88 - // Third pass: extract blockers from assistant/user text tail
89 - for (const block of blocks.slice(-20)) {
90 - if (block.kind !== "assistant" && block.kind !== "user") continue;
91 - const lines = block.text.split("\n").filter((l) => l.trim());
92 - for (const line of lines) {
93 - if (BLOCKER_RE.test(line) && line.length > 15) {
94 - const clean =
95 - block.kind === "user"
96 - ? `[user] ${truncate(line.trim(), 150)}`
97 - : truncate(line.trim(), 150);
98 - addUnique(context, clean);
99 - break;
100 - }
101 - }
102 - }
104 - const transcript = buildTranscript(blocks, toolCapPerTurn);
106 - return {
107 - goals: goals.slice(0, 8),
108 - scopeChanges: scopeChanges.slice(0, 8),
109 - files: { modified, created, read },
110 - context: context.slice(0, 5),
111 - preferences: preferences.slice(0, 10),
112 - transcript,
113 - };
116 -function goalCandidateLines(text: string): string[] {
117 - const raw = nonEmptyLines(text);
118 - const stop = raw.findIndex((line) => TEMPLATE_SIGNAL_RE.test(line));
119 - const lines = stop >= 0 ? raw.slice(0, stop) : raw;
121 - return collapseSkillLines(lines)
122 - .map(stripLeadingBullet)
123 - .filter(isSubstantiveGoalLine)
124 - .filter((line) => {
125 - if (!line.endsWith("?")) return true;
126 - // Questions usually stay transcript-only unless they include a task/action verb.
127 - return (
128 - GOAL_RE.test(line) &&
129 - !INTERROGATIVE_RE.test(line.replace(/^can you\s+/i, ""))
130 - );
131 - });
134 -function isSubstantiveGoalLine(line: string): boolean {
135 - const t = line.trim();
136 - if (t.length <= 5) return false;
137 - if (t.length > 240) return false;
138 - if (NOISE_SHORT_RE.test(t)) return false;
139 - if (NON_GOAL_RE.test(t)) return false;
140 - return true;
143 -function nonEmptyLines(text: string): string[] {
144 - return text
145 - .split("\n")
146 - .map((l) => l.trim())
147 - .filter(Boolean);
150 -function stripLeadingBullet(line: string): string {
151 - return line.replace(/^\s*(?:[-*+]|\d+\.)\s+/, "").trim();
154 -function collapseSkillLines(lines: string[]): string[] {
155 - const out: string[] = [];
156 - let inSkill = false;
157 - for (const line of lines) {
158 - if (/^<skill\b/i.test(line)) {
159 - inSkill = true;
160 - continue;
161 - }
162 - if (/^<\/skill>/i.test(line)) {
163 - inSkill = false;
164 - continue;
165 - }
166 - if (!inSkill) out.push(line);
167 - }
168 - return out;
171 -/**
172 - * Extract file paths from tool args.
173 - */
174 -function extractFileFromArgs(
175 - toolName: string,
176 - args: Record<string, unknown>,
177 - modified: Set<string>,
178 - created: Set<string>,
179 - read: Set<string>,
180 -): void {
181 - const name = toolName.toLowerCase();
183 - if (name.includes("edit") || name.includes("write")) {
184 - extractFilePath(args.path || args.file_path || args.file, modified);
185 - extractFilePath(args.new_path, created);
186 - }
188 - if (name.includes("read")) {
189 - extractFilePath(args.path || args.file_path || args.file, read);
190 - }
192 - if (name.includes("bash")) {
193 - const cmd = String(args.command || "");
194 - const pathMatch = cmd.match(/['"]?(\/[\w/.-]+\.\w+)['"]?/);
195 - if (pathMatch) {
196 - modified.add(pathMatch[1]);
197 - }
198 - }
201 -function extractFilePath(path: unknown, set: Set<string>): void {
202 - if (typeof path === "string" && path.trim()) {
203 - const parts = path.split("/");
204 - set.add(parts[parts.length - 1]);
205 - }
208 -/**
209 - * Extract user preferences from text.
210 - */
211 -function extractPreferences(text: string, prefs: string[]): void {
212 - const head = text.slice(0, 200);
213 - let perBlock = 0;
215 - for (const line of collapseSkillLines(nonEmptyLines(head))) {
216 - const trimmed = line.trim();
217 - if (trimmed.length < 5) continue;
218 - if (trimmed.length > 200) continue;
219 - if (trimmed.endsWith("?") || trimmed.includes("?...")) continue;
220 - if (GENERATED_PREF_FALSE_POSITIVE_RE.test(trimmed)) continue;
221 - if (!PREF_PATTERNS.some((p) => p.test(trimmed))) continue;
222 - addUnique(prefs, truncate(trimmed, 200));
223 - if (++perBlock >= 1) break;
224 - }
227 -/**
228 - * Build brief transcript from blocks.
229 - */
230 -function buildTranscript(
231 - blocks: Block[],
232 - toolCapPerTurn: number,
233 -): TranscriptEntry[] {
234 - const entries: TranscriptEntry[] = [];
235 - let toolCallsThisTurn = 0;
237 - for (const block of blocks) {
238 - switch (block.kind) {
239 - case "user": {
240 - toolCallsThisTurn = 0;
241 - const text = truncate(stripSelfTalk(block.text), TRUNCATE_USER);
242 - if (text) {
243 - entries.push({ role: "user", text, ref: `#${block.sourceIndex}` });
244 - }
245 - break;
246 - }
247 - case "assistant": {
248 - const text = truncate(stripSelfTalk(block.text), TRUNCATE_ASSISTANT);
249 - if (text) {
250 - entries.push({
251 - role: "assistant",
252 - text,
253 - ref: `#${block.sourceIndex}`,
254 - });
255 - }
256 - break;
257 - }
258 - case "tool_call": {
259 - if (toolCallsThisTurn >= toolCapPerTurn) break;
260 - toolCallsThisTurn++;
261 - const tool = block.name || "unknown";
262 - const cmd = extractToolCmd(block.args || {});
263 - entries.push({
264 - role: "assistant",
265 - text: "",
266 - tool,
267 - cmd,
268 - ref: `#${block.sourceIndex}`,
269 - });
270 - break;
271 - }
272 - case "tool_result": {
273 - if (block.isError) {
274 - const error = block.name ? `[ERROR] ${block.name}` : "[ERROR]";
275 - entries.push({
276 - role: "error",
277 - text: error,
278 - ref: `#${block.sourceIndex}`,
279 - });
280 - }
281 - break;
282 - }
283 - case "thinking":
284 - break;
285 - }
286 - }
288 - return entries;
291 -/**
292 - * Strip self-talk prefixes from assistant text.
293 - */
294 -function stripSelfTalk(text: string): string {
295 - let result = text;
296 - for (let i = 0; i < 2; i++) {
297 - const stripped = result.replace(SELF_TALK_PREFIX_RE, "");
298 - if (stripped === result) break;
299 - result = stripped;
300 - }
301 - return result;
304 -/**
305 - * Extract command from tool args.
306 - */
307 -function extractToolCmd(args: Record<string, unknown>): string | undefined {
308 - if (args.command) {
309 - const cmd = String(args.command);
310 - return compressBash(cmd);
311 - }
313 - if (args.path) return String(args.path);
314 - if (args.file_path) return String(args.file_path);
315 - if (args.file) return String(args.file);
317 - return undefined;
320 -function compressBash(raw: string): string {
321 - let cmd =
322 - raw
323 - .split("\n")
324 - .map((l) => l.trim())
325 - .filter(Boolean)[0] ?? raw;
326 - cmd = cmd.replace(/^cd\s+\S+\s*&&\s*/, "");
327 - cmd = cmd.replace(
328 - /\s*\|\s*(?:head|tail|sort|wc|column|tr|cut|awk|uniq|node|bun)(?:\s[^|]*)?$/,
329 - "",
330 - );
331 - return truncate(cmd, 120);
334 -function firstLine(text: string): string {
335 - return text.split("\n")[0]?.trim() || "(no output)";
338 -function addUnique(items: string[], item: string): void {
339 - if (!item.trim()) return;
340 - if (!items.includes(item)) items.push(item);
343 -/**
344 - * Truncate text to max length.
345 - */
346 -function truncate(text: string, max: number): string {
347 - const flat = text.replace(/\s+/g, " ").trim();
348 - if (flat.length <= max) return flat;
349 - return flat.slice(0, max - 3) + "...";

extensions/prune/src/format.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — format extract output to summary string
3 - */
5 -import {
6 - DEFAULT_SECTION_LIMIT,
7 - DEFAULT_TRANSCRIPT_LIMIT,
8 - RECALL_NOTE,
9 - SECTION_CONTEXT,
10 - SECTION_CONTINUE,
11 - SECTION_FILES,
12 - SECTION_PREFS,
13 - SECTION_SESSION,
14 - SEPARATOR,
15 -} from "./constants.ts";
16 -import type { ExtractOutput, PruneOutput, TranscriptEntry } from "./types.ts";
18 -export interface FormatOptions {
19 - sectionLimit?: number;
20 - transcriptLimit?: number;
21 - sourceEntriesProcessed?: number;
22 - tailKept?: number;
23 - splitPrefixMessages?: number;
24 - tokenEstimate?: number;
27 -/**
28 - * Format extract output into a summary string for LLM context.
29 - */
30 -export function format(
31 - data: ExtractOutput,
32 - options: FormatOptions = {},
33 -): PruneOutput {
34 - const start = performance.now();
35 - const {
36 - sectionLimit = DEFAULT_SECTION_LIMIT,
37 - transcriptLimit = DEFAULT_TRANSCRIPT_LIMIT,
38 - sourceEntriesProcessed,
39 - tailKept,
40 - splitPrefixMessages,
41 - tokenEstimate,
42 - } = options;
44 - const sections: string[] = [];
46 - const sessionLines: string[] = [];
47 - for (const goal of data.goals.slice(0, sectionLimit)) {
48 - sessionLines.push(`- ${goal}`);
49 - }
50 - if (data.scopeChanges.length > 0) {
51 - sessionLines.push("- [Scope change]");
52 - for (const change of data.scopeChanges.slice(0, sectionLimit)) {
53 - sessionLines.push(`- ${change}`);
54 - }
55 - }
56 - if (sessionLines.length > 0) {
57 - sections.push(`${SECTION_SESSION}\n${sessionLines.join("\n")}`);
58 - }
60 - const fileLines = formatFileLines(data.files);
61 - if (fileLines.length > 0) {
62 - sections.push(`${SECTION_FILES}\n${fileLines.join("\n")}`);
63 - }
65 - if (data.context.length > 0) {
66 - sections.push(
67 - `${SECTION_CONTEXT}\n${data.context
68 - .slice(0, sectionLimit)
69 - .map((i) => `- ${i}`)
70 - .join("\n")}`,
71 - );
72 - }
74 - if (data.preferences.length > 0) {
75 - sections.push(
76 - `${SECTION_PREFS}\n${data.preferences
77 - .slice(0, sectionLimit)
78 - .map((i) => `- ${i}`)
79 - .join("\n")}`,
80 - );
81 - }
83 - const transcriptLines = capTranscript(
84 - data.transcript.map(formatTranscriptEntry).filter(Boolean),
85 - transcriptLimit,
86 - );
88 - const continueLines = formatContinueLines(data.transcript);
89 - if (continueLines.length > 0) {
90 - sections.push(`${SECTION_CONTINUE}\n${continueLines.join("\n")}`);
91 - }
93 - const parts: string[] = [];
94 - if (sections.length > 0) parts.push(sections.join("\n\n"));
95 - if (transcriptLines.length > 0) parts.push(transcriptLines.join("\n"));
97 - const footer = formatFooter({
98 - sourceEntriesProcessed,
99 - tailKept,
100 - splitPrefixMessages,
101 - tokenEstimate,
102 - });
103 - if (footer) parts.push(footer);
104 - parts.push(RECALL_NOTE);
106 - const summary = parts.join(SEPARATOR);
107 - const elapsedMs = performance.now() - start;
109 - return {
110 - summary,
111 - stats: {
112 - messagesIn: data.transcript.length,
113 - messagesOut: summary.split("\n").length,
114 - reduction: 0,
115 - elapsedMs,
116 - },
117 - };
120 -function formatFileLines(files: ExtractOutput["files"]): string[] {
121 - const lines: string[] = [];
122 - const modified = capSet(files.modified, 10);
123 - const created = capSet(files.created, 10);
124 - const read = capSet(files.read, 10);
125 - if (modified) lines.push(`- Modified: ${modified}`);
126 - if (created) lines.push(`- Created: ${created}`);
127 - if (read) lines.push(`- Read: ${read}`);
128 - return lines;
131 -function capSet(set: Set<string>, limit: number): string {
132 - const arr = [...set];
133 - if (arr.length === 0) return "";
134 - if (arr.length <= limit) return arr.join(", ");
135 - return `${arr.slice(0, limit).join(", ")} (+${arr.length - limit} more)`;
138 -function capTranscript(lines: string[], limit: number): string[] {
139 - if (lines.length <= limit) return lines;
140 - const omitted = lines.length - limit;
141 - return [`...(${omitted} earlier lines omitted)`, "", ...lines.slice(-limit)];
144 -function formatFooter(options: {
145 - sourceEntriesProcessed?: number;
146 - tailKept?: number;
147 - splitPrefixMessages?: number;
148 - tokenEstimate?: number;
149 -}): string {
150 - if (options.sourceEntriesProcessed == null || options.tailKept == null)
151 - return "";
152 - const before =
153 - options.tokenEstimate == null
154 - ? ""
155 - : `; before ${formatTokenEstimate(options.tokenEstimate)} tok`;
156 - const split =
157 - options.splitPrefixMessages == null
158 - ? ""
159 - : `; split-prefix ${options.splitPrefixMessages}`;
160 - return `prune: ${options.sourceEntriesProcessed} entries summarized${before}; raw kept ${options.tailKept} entries${split}`;
163 -function formatContinueLines(transcript: TranscriptEntry[]): string[] {
164 - if (transcript.length === 0) return [];
165 - const lastUser = findLast(transcript, (entry) => entry.role === "user");
166 - const lastFailure = findLast(transcript, (entry) => entry.role === "error");
167 - const lastAction = findLast(transcript, (entry) => entry.role !== "user");
168 - const lines: string[] = [];
169 - if (lastUser) lines.push(`- Current request: ${formatBriefEntry(lastUser)}`);
170 - if (lastAction) lines.push(`- Last action: ${formatBriefEntry(lastAction)}`);
171 - if (lastFailure)
172 - lines.push(`- Last failure: ${formatBriefEntry(lastFailure)}`);
173 - lines.push(
174 - "- Next: continue current request; use prune_recall before redoing old work.",
175 - );
176 - return lines;
179 -function findLast<T>(
180 - items: T[],
181 - predicate: (item: T) => boolean,
182 -): T | undefined {
183 - for (let i = items.length - 1; i >= 0; i--) {
184 - if (predicate(items[i])) return items[i];
185 - }
186 - return undefined;
189 -function formatBriefEntry(entry: TranscriptEntry): string {
190 - if (entry.tool) {
191 - const cmd = entry.cmd ? ` ${entry.cmd}` : "";
192 - return `${entry.tool}${cmd}${entry.ref ? ` (${entry.ref})` : ""}`;
193 - }
194 - return `${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
197 -function formatTokenEstimate(tokens: number): string {
198 - if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`;
199 - return String(tokens);
202 -/**
203 - * Format a single transcript entry.
204 - */
205 -function formatTranscriptEntry(entry: TranscriptEntry): string {
206 - switch (entry.role) {
207 - case "user":
208 - return `[user]\n${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
209 - case "assistant":
210 - if (entry.tool) {
211 - const args = entry.cmd ? ` "${entry.cmd}"` : "";
212 - return `* ${entry.tool}${args}${entry.ref ? ` (${entry.ref})` : ""}`;
213 - }
214 - return `[assistant]\n${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
215 - case "error":
216 - return `[tool_error] ${entry.text}${entry.ref ? ` (${entry.ref})` : ""}`;
217 - default:
218 - return "";
219 - }

extensions/prune/src/merge.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — merge previous + fresh formatted summaries
3 - */
5 -import {
6 - RECALL_NOTE,
7 - SECTION_COMMITS,
8 - SECTION_CONTEXT,
9 - SECTION_CONTINUE,
10 - SECTION_FILES,
11 - SECTION_PREFS,
12 - SECTION_SESSION,
13 - SEPARATOR,
14 -} from "./constants.ts";
16 -const HEADER_NAMES = [
17 - SECTION_SESSION,
18 - SECTION_FILES,
19 - SECTION_CONTEXT,
20 - SECTION_PREFS,
21 - SECTION_CONTINUE,
22 - SECTION_COMMITS,
23 -];
25 -/** Merge formatted summaries using stable section headers. */
26 -export function merge(
27 - previousSummary: string | undefined,
28 - freshSummary: string,
29 -): string {
30 - const fresh = stripFooter(freshSummary).trim();
31 - const prev = previousSummary ? stripFooter(previousSummary).trim() : "";
32 - if (!prev) return freshSummary;
33 - if (!fresh) return previousSummary || "";
35 - const headers = HEADER_NAMES.map((header) =>
36 - mergeSection(header, sectionOf(prev, header), sectionOf(fresh, header)),
37 - ).filter(Boolean);
39 - const prevBrief = briefOf(prev);
40 - const freshBrief = briefOf(fresh);
41 - const mergedBrief = capBrief(
42 - [prevBrief, freshBrief].filter(Boolean).join("\n\n"),
43 - );
45 - const tailParts = [
46 - metadataOf(freshSummary) || metadataOf(previousSummary || ""),
47 - RECALL_NOTE,
48 - ].filter(Boolean);
49 - const bodyParts = [headers.join("\n\n"), mergedBrief, ...tailParts].filter(
50 - Boolean,
51 - );
52 - return bodyParts.join(SEPARATOR);
55 -function mergeSection(header: string, prev: string, fresh: string): string {
56 - if (header === SECTION_CONTEXT || header === SECTION_CONTINUE) return fresh;
57 - if (header === SECTION_FILES) {
58 - if (!prev) return fresh;
59 - if (!fresh) return prev;
60 - return mergeFiles(prev, fresh);
61 - }
63 - const prevLines = sanitizeStickyLines(header, contentLines(prev));
64 - const freshLines = sanitizeStickyLines(header, contentLines(fresh));
65 - const cap = header === SECTION_PREFS ? 15 : 8;
66 - const lines = dedup([...prevLines, ...freshLines]).slice(-cap);
67 - if (lines.length === 0) return "";
68 - return `${header}\n${lines.join("\n")}`;
71 -function mergeFiles(prev: string, fresh: string): string {
72 - const cats = ["Modified", "Created", "Read"] as const;
73 - const merged: Record<string, Set<string>> = {};
74 - for (const cat of cats) merged[cat] = new Set();
76 - for (const text of [prev, fresh]) {
77 - for (const line of contentLines(text)) {
78 - for (const cat of cats) {
79 - const prefix = `- ${cat}: `;
80 - if (!line.startsWith(prefix)) continue;
81 - const rest = line
82 - .slice(prefix.length)
83 - .replace(/\s*\(\+\d+ more\)\s*$/, "");
84 - for (const item of rest.split(",")) {
85 - const trimmed = item.trim();
86 - if (trimmed) merged[cat].add(trimmed);
87 - }
88 - }
89 - }
90 - }
92 - for (const p of merged.Modified) merged.Created.delete(p);
94 - const lines: string[] = [];
95 - for (const cat of cats) {
96 - const rendered = capSet(merged[cat], 10);
97 - if (rendered) lines.push(`- ${cat}: ${rendered}`);
98 - }
99 - return lines.length === 0 ? "" : `${SECTION_FILES}\n${lines.join("\n")}`;
102 -function sectionOf(text: string, header: string): string {
103 - const idx = text.indexOf(header);
104 - if (idx < 0) return "";
105 - const after = text.slice(idx);
106 - const candidates = HEADER_NAMES.filter((h) => h !== header)
107 - .map((h) => after.indexOf(h))
108 - .filter((n) => n > 0);
109 - const sep = after.indexOf(SEPARATOR);
110 - if (sep > 0) candidates.push(sep);
111 - const end = candidates.sort((a, b) => a - b)[0];
112 - return (end ? after.slice(0, end) : after).trim();
115 -function briefOf(text: string): string {
116 - const parts = text.split(SEPARATOR);
117 - if (parts.length < 2) return "";
118 - const chunks = parts.slice(1).filter((part) => {
119 - const trimmed = part.trim();
120 - return (
121 - trimmed &&
122 - !trimmed.startsWith("prune:") &&
123 - !trimmed.startsWith("Use prune_recall")
124 - );
125 - });
126 - return chunks.join(SEPARATOR).trim();
129 -function metadataOf(text: string): string {
130 - return (
131 - text
132 - .split(SEPARATOR)
133 - .map((p) => p.trim())
134 - .find((p) => p.startsWith("prune:")) || ""
135 - );
138 -function stripFooter(text: string): string {
139 - return text
140 - .replace(RECALL_NOTE, "")
141 - .split(SEPARATOR)
142 - .filter((part) => !part.trim().startsWith("prune:"))
143 - .join(SEPARATOR)
144 - .trim();
147 -function contentLines(section: string): string[] {
148 - return section
149 - .split("\n")
150 - .slice(1)
151 - .map((l) => l.trim())
152 - .filter(Boolean);
155 -function sanitizeStickyLines(header: string, lines: string[]): string[] {
156 - if (header !== SECTION_SESSION && header !== SECTION_PREFS) return lines;
157 - return lines.filter((line) => !isLikelyToolOutputLine(line));
160 -function isLikelyToolOutputLine(line: string): boolean {
161 - const body = line.replace(/^[-*]\s*/, "").trim();
162 - if (body === "[Scope change]") return false;
163 - return /^(?:Successfully (?:wrote|replaced|created|updated|deleted)|Could not find edits\[|\(pass\)|\(fail\)|diff --git\b|index [0-9a-f]{6,}\b|@@\b|---\s|\+\+\+\s|assert[A-Z]\w*\(|const\s|let\s|var\s|import\s|export\s|local\s+\w+\s*=\s*function\b|function\s|status=\d|for\s+file\s+in\s|bunx\s|bun\s+test\b|just\s|npm\s|pnpm\s|yarn\s|rg\s|git\s|sed\s|awk\s|[\w./-]+\.\w+:\d+)/i.test(
164 - body,
165 - );
168 -function dedup(lines: string[]): string[] {
169 - const seen = new Set<string>();
170 - const out: string[] = [];
171 - for (const line of lines) {
172 - const key = line.toLowerCase();
173 - if (seen.has(key)) continue;
174 - seen.add(key);
175 - out.push(line);
176 - }
177 - return out;
180 -function capSet(set: Set<string>, limit: number): string {
181 - const arr = [...set];
182 - if (arr.length === 0) return "";
183 - if (arr.length <= limit) return arr.join(", ");
184 - return `${arr.slice(0, limit).join(", ")} (+${arr.length - limit} more)`;
187 -function capBrief(text: string, limit = 120): string {
188 - const lines = text.split("\n");
189 - if (lines.length <= limit) return text;
190 - const omitted = lines.length - limit;
191 - return `...(${omitted} earlier lines omitted)\n\n${lines.slice(-limit).join("\n")}`;

extensions/prune/src/normalize.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — normalize messages to blocks
3 - */
5 -import type { Block, ContentPart, Message } from "./types.ts";
7 -/**
8 - * Map pi Message array to normalized Block array.
9 - * Each block gets a sourceIndex pointing to original message.
10 - */
11 -export function normalize(messages: Message[]): Block[] {
12 - return messages.flatMap((msg, i) => normalizeOne(msg, i + 1));
15 -function normalizeOne(msg: Message, msgIndex: number): Block[] {
16 - switch (msg.role) {
17 - case "user":
18 - return normalizeUser(msg, msgIndex);
19 - case "assistant":
20 - return normalizeAssistant(msg, msgIndex);
21 - case "tool":
22 - case "toolResult":
23 - return normalizeTool(msg, msgIndex);
24 - default:
25 - return [];
26 - }
29 -function normalizeUser(msg: Message, msgIndex: number): Block[] {
30 - const text = extractText(msg.content);
31 - if (!text.trim()) return [];
32 - return [{ kind: "user", text, sourceIndex: msgIndex }];
35 -function normalizeAssistant(msg: Message, msgIndex: number): Block[] {
36 - const blocks: Block[] = [];
38 - if (!msg.content) return [];
40 - if (typeof msg.content === "string") {
41 - if (msg.content.trim()) {
42 - blocks.push({
43 - kind: "assistant",
44 - text: msg.content,
45 - sourceIndex: msgIndex,
46 - });
47 - }
48 - return blocks;
49 - }
51 - for (const part of msg.content) {
52 - switch (part.type) {
53 - case "text":
54 - if (part.text?.trim()) {
55 - blocks.push({
56 - kind: "assistant",
57 - text: part.text,
58 - sourceIndex: msgIndex,
59 - });
60 - }
61 - break;
62 - case "thinking":
63 - // Skip thinking blocks
64 - break;
65 - case "toolCall":
66 - if (part.name?.trim()) {
67 - blocks.push({
68 - kind: "tool_call",
69 - text: "",
70 - sourceIndex: msgIndex,
71 - name: part.name,
72 - args: part.arguments,
73 - });
74 - }
75 - break;
76 - case "image":
77 - // Skip images
78 - break;
79 - }
80 - }
82 - return blocks;
85 -function normalizeTool(msg: Message, msgIndex: number): Block[] {
86 - const text = extractText(msg.content);
87 - return [
88 - {
89 - kind: "tool_result",
90 - text,
91 - sourceIndex: msgIndex,
92 - name: msg.toolName,
93 - isError: msg.isError,
94 - },
95 - ];
98 -function extractText(content: string | ContentPart[] | undefined): string {
99 - if (!content) return "";
100 - if (typeof content === "string") return content.trim();
102 - const parts: string[] = [];
103 - for (const part of content) {
104 - if (part.type === "text" && part.text) {
105 - parts.push(part.text);
106 - }
107 - }
108 - return parts.join(" ").trim();

extensions/prune/src/recall.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — search session entries
3 - */
5 -import type { Message, SearchInput, SearchResult } from "./types.ts";
7 -type SessionEntry = {
8 - type: string;
9 - id?: string;
10 - message?: Message;
11 - summary?: string;
12 - customType?: string;
13 - content?: unknown;
14 -};
16 -export interface RecallSource {
17 - getBranch(): SessionEntry[];
18 - getEntries(): SessionEntry[];
21 -export function recall(
22 - source: RecallSource,
23 - input: SearchInput,
24 -): SearchResult[] {
25 - const scope = input.scope ?? "lineage";
26 - const limit = input.limit ?? 5;
27 - const entries = scope === "all" ? source.getEntries() : source.getBranch();
28 - const query = input.query;
29 - const matcher = makeMatcher(query);
30 - const expand = new Set(input.expand ?? []);
31 - const results: SearchResult[] = [];
33 - entries.forEach((entry, i) => {
34 - const index = i + 1;
35 - const text = entryText(entry);
36 - if (!text) return;
38 - const expanded = expand.has(index);
39 - const score = matcher(text);
40 - if (score <= 0 && !expanded) return;
42 - results.push({
43 - index,
44 - entry: entryToMessage(entry, text),
45 - role: entryRole(entry),
46 - score: expanded ? Math.max(score, 1) : score,
47 - context: expanded ? text : snippet(text, query),
48 - });
49 - });
51 - return results
52 - .sort((a, b) => b.score - a.score || a.index - b.index)
53 - .slice(0, Math.max(limit, expand.size));
56 -export function formatRecallResults(results: SearchResult[]): string {
57 - if (results.length === 0) return "No matches.";
58 - return results
59 - .map((r) => {
60 - const ctx = r.context ? `\n${r.context}` : "";
61 - return `#${r.index} ${r.role} score=${r.score}${ctx}`;
62 - })
63 - .join("\n\n");
66 -function makeMatcher(query: string | RegExp): (text: string) => number {
67 - if (query instanceof RegExp) {
68 - return (text) => (query.test(text) ? 10 : 0);
69 - }
70 - const q = query.trim();
71 - if (!q) return () => 0;
73 - let regex: RegExp | undefined;
74 - if (looksLikeRegex(q)) {
75 - try {
76 - regex = new RegExp(q, "i");
77 - } catch {
78 - regex = undefined;
79 - }
80 - }
82 - const terms = q.toLowerCase().match(/[\p{L}\p{N}_-]+/gu) ?? [];
83 - return (text) => {
84 - if (regex?.test(text)) return 10;
85 - const lower = text.toLowerCase();
86 - let score = 0;
87 - for (const term of terms) {
88 - if (lower.includes(term)) score++;
89 - }
90 - return score;
91 - };
94 -function looksLikeRegex(q: string): boolean {
95 - return /[.*+?^${}()|[\]\\]/.test(q);
98 -function entryText(entry: SessionEntry): string {
99 - if (entry.type === "message" && entry.message)
100 - return messageText(entry.message);
101 - if (entry.type === "compaction" && typeof entry.summary === "string")
102 - return entry.summary;
103 - if (entry.type === "custom_message")
104 - return typeof entry.content === "string"
105 - ? entry.content
106 - : JSON.stringify(entry.content ?? "");
107 - return "";
110 -function messageText(message: Message): string {
111 - if (typeof message.content === "string") return message.content;
112 - if (Array.isArray(message.content)) {
113 - return message.content
114 - .map((part) => {
115 - if (part.type === "text") return part.text ?? "";
116 - if (part.type === "toolCall")
117 - return `${part.name ?? "tool"} ${JSON.stringify(part.arguments ?? {})}`;
118 - if (part.type === "thinking") return part.thinking ?? "";
119 - return "";
120 - })
121 - .filter(Boolean)
122 - .join("\n");
123 - }
124 - return "";
127 -function entryToMessage(entry: SessionEntry, text: string): Message {
128 - if (entry.type === "message" && entry.message) return entry.message;
129 - return { role: "assistant", content: text };
132 -function entryRole(entry: SessionEntry): "user" | "assistant" | "tool" {
133 - if (entry.type !== "message" || !entry.message?.role) return "assistant";
134 - if (entry.message.role === "tool" || entry.message.role === "toolResult")
135 - return "tool";
136 - if (entry.message.role === "assistant") return "assistant";
137 - return "user";
140 -function snippet(text: string, query: string | RegExp): string {
141 - const flat = text.replace(/\s+/g, " ").trim();
142 - if (flat.length <= 240) return flat;
143 - const needle =
144 - query instanceof RegExp
145 - ? ""
146 - : (query.trim().split(/\s+/)[0]?.toLowerCase() ?? "");
147 - const idx = needle ? flat.toLowerCase().indexOf(needle) : -1;
148 - const start = idx < 0 ? 0 : Math.max(0, idx - 80);
149 - return `${start > 0 ? "..." : ""}${flat.slice(start, start + 240)}${start + 240 < flat.length ? "..." : ""}`;

extensions/prune/src/types.ts

Deleted
deleted file mode 100644
1 -/**
2 - * prune — types
3 - */
5 -// ─── Core Types ────────────────────────────────────────────────────────────────
7 -export interface Message {
8 - role:
9 - | "user"
10 - | "assistant"
11 - | "tool"
12 - | "toolResult"
13 - | "bashExecution"
14 - | "custom"
15 - | "branchSummary"
16 - | "compactionSummary";
17 - content?: string | ContentPart[];
18 - toolName?: string;
19 - toolCallId?: string;
20 - isError?: boolean;
21 - thinking?: string;
22 - redacted?: boolean;
25 -export interface ContentPart {
26 - type: "text" | "toolCall" | "thinking" | "image";
27 - text?: string;
28 - name?: string;
29 - arguments?: Record<string, unknown>;
30 - thinking?: string;
31 - redacted?: boolean;
32 - mimeType?: string;
35 -// ─── Block Types ──────────────────────────────────────────────────────────────
37 -export type BlockKind =
38 - | "user"
39 - | "assistant"
40 - | "tool_call"
41 - | "tool_result"
42 - | "thinking";
44 -export interface Block {
45 - kind: BlockKind;
46 - text: string;
47 - sourceIndex: number;
48 - name?: string;
49 - args?: Record<string, unknown>;
50 - isError?: boolean;
53 -// ─── Extract Output ───────────────────────────────────────────────────────────
55 -export interface ExtractOutput {
56 - goals: string[];
57 - scopeChanges: string[];
58 - files: {
59 - modified: Set<string>;
60 - created: Set<string>;
61 - read: Set<string>;
62 - };
63 - context: string[];
64 - preferences: string[];
65 - transcript: TranscriptEntry[];
68 -export interface TranscriptEntry {
69 - role: "user" | "assistant" | "error";
70 - text: string;
71 - tool?: string;
72 - cmd?: string;
73 - ref?: string;
74 - count?: number;
77 -// ─── Prune Output ────────────────────────────────────────────────────────────
79 -export interface PruneOutput {
80 - summary: string;
81 - stats: PruneStats;
84 -export interface PruneStats {
85 - messagesIn: number;
86 - messagesOut: number;
87 - reduction: number;
88 - elapsedMs: number;
91 -// ─── Search Types ─────────────────────────────────────────────────────────────
93 -export type SearchScope = "lineage" | "all";
95 -export interface SearchInput {
96 - query: string | RegExp;
97 - scope?: SearchScope;
98 - limit?: number;
99 - expand?: number[];
102 -export interface SearchResult {
103 - index: number;
104 - entry: Message;
105 - role: "user" | "assistant" | "tool";
106 - score: number;
107 - context?: string;
110 -// ─── Settings ────────────────────────────────────────────────────────────────
112 -export interface PruneSettings {
113 - overrideDefault?: boolean;
114 - sectionLimit?: number;
115 - transcriptLimit?: number;
116 - toolCapPerTurn?: number;
117 - debug?: boolean;