pi-mega-compact 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,29 +7,42 @@
7
7
  * driven by the event + command handlers in mega-events.ts / mega-commands.ts.
8
8
  */
9
9
 
10
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import type {
11
+ ExtensionAPI,
12
+ ExtensionContext,
13
+ } from "@earendil-works/pi-coding-agent";
11
14
  import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
12
15
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
13
16
  import { compactSession } from "../src/engine.js";
14
17
  import type { EngineMessage } from "../src/types.js";
15
- import { recallAndInline, recallAndInlineAsync, formatRecallBlock, type RecallInjectResult } from "../src/recall.js";
18
+ import {
19
+ recallAndInline,
20
+ recallAndInlineAsync,
21
+ formatRecallBlock,
22
+ type RecallInjectResult,
23
+ } from "../src/recall.js";
16
24
  import { normalizeSessionId } from "../src/store.js";
17
25
  import { estimateBlockTokens } from "../src/tokens.js";
18
26
  import { touchSession, logDaily } from "../src/store/sqlite.js";
19
27
  import { consolidateMemories } from "../src/memory.js";
28
+ import { type MegaRuntime, C, MARKER_TYPE } from "./mega-runtime.js";
20
29
  import {
21
- MegaRuntime,
22
- C,
23
- MARKER_TYPE,
24
- } from "./mega-runtime.js";
25
- import { resolveRepoRoot, preserveRecentForPressure, type MegaConfig } from "./mega-config.js";
30
+ resolveRepoRoot,
31
+ preserveRecentForPressure,
32
+ type MegaConfig,
33
+ } from "./mega-config.js";
26
34
  import { runRaptor } from "../src/dedup/raptor/index.js";
27
35
  import { loadDedupConfig } from "../src/config/dedup.js";
28
36
  import { upsertEmbedding as indexUpsertEmbedding } from "../src/store/vectorIndex.js";
29
37
 
30
38
  export type RunCompactResult =
31
- | { skipped: true }
32
- | { skipped: false; result: ReturnType<typeof compactSession>; keepFrom: number; saved: number };
39
+ | { skipped: true }
40
+ | {
41
+ skipped: false;
42
+ result: ReturnType<typeof compactSession>;
43
+ keepFrom: number;
44
+ saved: number;
45
+ };
33
46
 
34
47
  /**
35
48
  * Review the live conversation and persist durable memories (S20+S24). Shared by
@@ -42,271 +55,306 @@ export type RunCompactResult =
42
55
  * @param label a short source tag for the ticker line (e.g. "pressure" / "turn")
43
56
  */
44
57
  export async function runMemoryReview(
45
- runtime: MegaRuntime,
46
- view: ReturnType<MegaRuntime["engineView"]>,
47
- label: string,
58
+ runtime: MegaRuntime,
59
+ view: ReturnType<MegaRuntime["engineView"]>,
60
+ label: string,
48
61
  ): Promise<number> {
49
- try {
50
- const { reviewConversation } = await import("../src/memory.js");
51
- const { applyMemoryOps } = await import("../src/memoryOps.js");
52
- const ops = reviewConversation(view, []);
53
- if (ops.length) {
54
- await applyMemoryOps(ops, runtime.currentStateDir);
55
- // S21.2: ops landed — the compaction path reads this counter and fires
56
- // `consolidateMemories` only when > 0.
57
- runtime.memoriesTouchedThisCompaction += ops.length;
58
- runtime.pushTicker(`${C.green}🧠${C.reset} reviewed ${ops.length} memory op${ops.length === 1 ? "" : "s"} (${label})`);
59
- }
60
- return ops.length;
61
- } catch {
62
- /* non-fatal — auto-review must never break the turn loop / compaction */
63
- return 0;
64
- }
62
+ try {
63
+ const { reviewConversation } = await import("../src/memory.js");
64
+ const { applyMemoryOps } = await import("../src/memoryOps.js");
65
+ const ops = reviewConversation(view, []);
66
+ if (ops.length) {
67
+ await applyMemoryOps(ops, runtime.currentStateDir);
68
+ // S21.2: ops landed — the compaction path reads this counter and fires
69
+ // `consolidateMemories` only when > 0.
70
+ runtime.memoriesTouchedThisCompaction += ops.length;
71
+ runtime.pushTicker(
72
+ `${C.green}🧠${C.reset} reviewed ${ops.length} memory op${ops.length === 1 ? "" : "s"} (${label})`,
73
+ );
74
+ }
75
+ return ops.length;
76
+ } catch {
77
+ /* non-fatal — auto-review must never break the turn loop / compaction */
78
+ return 0;
79
+ }
65
80
  }
66
81
 
67
82
  /** Run the full compaction pipeline and persist a checkpoint. Returns the result. */
68
83
  export function runCompact(
69
- pi: ExtensionAPI,
70
- runtime: MegaRuntime,
71
- config: MegaConfig,
72
- ctx: ExtensionContext,
73
- messages: AgentMessage[],
74
- opts: { keepFrom?: number; summary?: string; compressionPressure?: number } = {},
84
+ pi: ExtensionAPI,
85
+ runtime: MegaRuntime,
86
+ config: MegaConfig,
87
+ ctx: ExtensionContext,
88
+ messages: AgentMessage[],
89
+ opts: {
90
+ keepFrom?: number;
91
+ summary?: string;
92
+ compressionPressure?: number;
93
+ } = {},
75
94
  ): RunCompactResult {
76
- runtime.bindRepo(ctx.cwd);
77
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
78
- runtime.resetRuntime(sid);
79
- runtime.rt.sessionId = sid;
95
+ runtime.bindRepo(ctx.cwd);
96
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
97
+ runtime.resetRuntime(sid);
98
+ runtime.rt.sessionId = sid;
80
99
 
81
- const view = runtime.engineView(messages);
82
- // keepFrom deepens with context pressure (Fix E): under high pressure we
83
- // compact more of the session, down to the preserveRecentMin floor.
84
- const preserve = preserveRecentForPressure(
85
- opts.compressionPressure ?? 0,
86
- config.preserveRecent,
87
- config.preserveRecentMin,
88
- );
89
- const keepFrom = opts.keepFrom ?? Math.max(0, view.length - preserve);
90
- // For very small sessions (fewer messages than preserveRecent), allow
91
- // compacting everything except the last message — the user explicitly
92
- // requested compaction, so don't refuse it just because the session is short.
93
- if (keepFrom <= 0) {
94
- if (view.length <= 1) return { skipped: true };
95
- // Use the fallback: compact everything except the last message
96
- const fallbackKeepFrom = view.length - 1;
97
- return doCompact(view, fallbackKeepFrom, opts, sid, config, pi, ctx, runtime);
98
- }
100
+ const view = runtime.engineView(messages);
101
+ // keepFrom deepens with context pressure (Fix E): under high pressure we
102
+ // compact more of the session, down to the preserveRecentMin floor.
103
+ const preserve = preserveRecentForPressure(
104
+ opts.compressionPressure ?? 0,
105
+ config.preserveRecent,
106
+ config.preserveRecentMin,
107
+ );
108
+ const keepFrom = opts.keepFrom ?? Math.max(0, view.length - preserve);
109
+ // For very small sessions (fewer messages than preserveRecent), allow
110
+ // compacting everything except the last message — the user explicitly
111
+ // requested compaction, so don't refuse it just because the session is short.
112
+ if (keepFrom <= 0) {
113
+ if (view.length <= 1) return { skipped: true };
114
+ // Use the fallback: compact everything except the last message
115
+ const fallbackKeepFrom = view.length - 1;
116
+ return doCompact(
117
+ view,
118
+ fallbackKeepFrom,
119
+ opts,
120
+ sid,
121
+ config,
122
+ pi,
123
+ ctx,
124
+ runtime,
125
+ );
126
+ }
99
127
 
100
- return doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime);
128
+ return doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime);
101
129
  }
102
130
 
103
131
  function doCompact(
104
- view: EngineMessage[],
105
- keepFrom: number,
106
- opts: { keepFrom?: number; summary?: string; compressionPressure?: number },
107
- sid: string,
108
- config: MegaConfig,
109
- pi: ExtensionAPI,
110
- ctx: ExtensionContext,
111
- runtime: MegaRuntime,
132
+ view: EngineMessage[],
133
+ keepFrom: number,
134
+ opts: { keepFrom?: number; summary?: string; compressionPressure?: number },
135
+ sid: string,
136
+ config: MegaConfig,
137
+ pi: ExtensionAPI,
138
+ ctx: ExtensionContext,
139
+ runtime: MegaRuntime,
112
140
  ): RunCompactResult {
113
- runtime.pulsing = true; // animate the status line while the (sync) pipeline runs
114
- // S21.2: reset the per-compaction memory-op counter so the post-compact
115
- // consolidate pass only fires when memory rows actually changed during the
116
- // compaction window (turn_end → auto-review may have written some).
117
- runtime.memoriesTouchedThisCompaction = 0;
118
- const result = compactSession(
119
- {
120
- sessionId: sid,
121
- messages: view,
122
- keepFrom,
123
- summary: opts.summary,
124
- timestamp: Date.now(),
125
- onTier: runtime.makeTierCallback(ctx),
126
- compressionPressure: opts.compressionPressure,
127
- },
128
- runtime.store,
129
- );
130
- runtime.pulsing = false;
141
+ runtime.pulsing = true; // animate the status line while the (sync) pipeline runs
142
+ // S21.2: reset the per-compaction memory-op counter so the post-compact
143
+ // consolidate pass only fires when memory rows actually changed during the
144
+ // compaction window (turn_end → auto-review may have written some).
145
+ runtime.memoriesTouchedThisCompaction = 0;
146
+ const result = compactSession(
147
+ {
148
+ sessionId: sid,
149
+ messages: view,
150
+ keepFrom,
151
+ summary: opts.summary,
152
+ timestamp: Date.now(),
153
+ onTier: runtime.makeTierCallback(ctx),
154
+ compressionPressure: opts.compressionPressure,
155
+ },
156
+ runtime.store,
157
+ );
158
+ runtime.pulsing = false;
131
159
 
132
- if (result.skipped) return { skipped: true };
133
- if (!result.deduped) {
134
- runtime.rt.persistedThisSession = true;
135
- runtime.rt.lastCheckpointId = result.checkpointId;
136
- }
137
- runtime.rt.lastCompactedFrom = result.compactedFrom;
138
- runtime.rt.lastCompactedTokens = result.tokenEstimate;
139
- runtime.rt.dedupAttempts++;
140
- // Honest "tokens saved" for this session-instance only:
141
- // new checkpoint → original − stored
142
- // deduped onto existing → whole original region (nothing new stored)
143
- // Resets to 0 on session_start (rt is rebuilt) — so a fresh session shows 0
144
- // while the repo's cumulative saved (SQLite meta) keeps the running total.
145
- const saved = result.deduped
146
- ? result.originalTokenEstimate
147
- : Math.max(0, result.originalTokenEstimate - result.tokenEstimate);
148
- runtime.rt.tokensSaved += saved;
149
- if (result.deduped) runtime.rt.dedupSkips++;
150
- // Grow the rolling "saved" goal so the progress bar always has a fresh
151
- // denominator (we don't want it pinned at 100% once we pass an old target).
152
- if (runtime.rt.tokensSaved > runtime.savedGoal) runtime.savedGoal = Math.ceil((runtime.rt.tokensSaved * 1.25) / 10_000) * 10_000;
160
+ if (result.skipped) return { skipped: true };
161
+ if (!result.deduped) {
162
+ runtime.rt.persistedThisSession = true;
163
+ runtime.rt.lastCheckpointId = result.checkpointId;
164
+ }
165
+ runtime.rt.lastCompactedFrom = result.compactedFrom;
166
+ runtime.rt.lastCompactedTokens = result.tokenEstimate;
167
+ runtime.rt.dedupAttempts++;
168
+ // Honest "tokens saved" for this session-instance only:
169
+ // new checkpoint → original − stored
170
+ // deduped onto existing → whole original region (nothing new stored)
171
+ // Resets to 0 on session_start (rt is rebuilt) — so a fresh session shows 0
172
+ // while the repo's cumulative saved (SQLite meta) keeps the running total.
173
+ const saved = result.deduped
174
+ ? result.originalTokenEstimate
175
+ : Math.max(0, result.originalTokenEstimate - result.tokenEstimate);
176
+ runtime.rt.tokensSaved += saved;
177
+ runtime.rt.lastCompactAt = Date.now();
178
+ if (result.deduped) runtime.rt.dedupSkips++;
179
+ // Grow the rolling "saved" goal so the progress bar always has a fresh
180
+ // denominator (we don't want it pinned at 100% once we pass an old target).
181
+ if (runtime.rt.tokensSaved > runtime.savedGoal)
182
+ runtime.savedGoal =
183
+ Math.ceil((runtime.rt.tokensSaved * 1.25) / 10_000) * 10_000;
153
184
 
154
- // Live toolbar activity: what file/region just got compacted or deduped.
155
- // Rendered via the rotating ticker line (see snapshot); the ring buffer is
156
- // cycled one-per-repaint so the single line scrolls through recent files.
157
- const files = result.filesModified ?? [];
158
- const fileLabel = files.length
159
- ? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ")
160
- : result.regionHash.slice(0, 8);
161
- runtime.lastActivityAt = Date.now();
162
- // Explain-why line: surfaced while fresh. Pulls the dedup reason (which for
163
- // L2 includes the cosine sim) so the user sees WHY a region was kept/dropped.
164
- runtime.lastWhy = result.deduped
165
- ? `why: deduped@${result.dedupReason ?? "tier"}`
166
- : `why: compacted ${result.checkpointId}`;
167
- // Recall/activity ticker: record this event in the ring buffer.
168
- const savedK = (saved / 1000).toFixed(1);
169
- runtime.pushTicker(
170
- result.deduped
171
- ? `${C.green}♻${C.reset} deduped ${fileLabel} · ${savedK}k saved`
172
- : `${C.cyan}🗜${C.reset} ${result.checkpointId} · +${savedK}k · ${fileLabel}`,
173
- );
174
- // The per-tier trace has settled into the final outcome — fold it back into
175
- // the activity line and stop showing the live trace.
176
- runtime.tierTrace = undefined;
185
+ // Live toolbar activity: what file/region just got compacted or deduped.
186
+ // Rendered via the rotating ticker line (see snapshot); the ring buffer is
187
+ // cycled one-per-repaint so the single line scrolls through recent files.
188
+ const files = result.filesModified ?? [];
189
+ const fileLabel = files.length
190
+ ? files
191
+ .map((f) => f.split("/").pop() ?? f)
192
+ .slice(0, 2)
193
+ .join(", ")
194
+ : result.regionHash.slice(0, 8);
195
+ runtime.lastActivityAt = Date.now();
196
+ // Explain-why line: surfaced while fresh. Pulls the dedup reason (which for
197
+ // L2 includes the cosine sim) so the user sees WHY a region was kept/dropped.
198
+ runtime.lastWhy = result.deduped
199
+ ? `why: deduped@${result.dedupReason ?? "tier"}`
200
+ : `why: compacted → ${result.checkpointId}`;
201
+ // Recall/activity ticker: record this event in the ring buffer.
202
+ const savedK = (saved / 1000).toFixed(1);
203
+ runtime.pushTicker(
204
+ result.deduped
205
+ ? `${C.green}♻${C.reset} deduped ${fileLabel} · ${savedK}k saved`
206
+ : `${C.cyan}🗜${C.reset} ${result.checkpointId} · +${savedK}k · ${fileLabel}`,
207
+ );
208
+ // The per-tier trace has settled into the final outcome — fold it back into
209
+ // the activity line and stop showing the live trace.
210
+ runtime.tierTrace = undefined;
177
211
 
178
- // Record session activity + a daily-log entry in the per-repo SQLite store
179
- // (foundation for resume-sessions / daily-log features). Best-effort — never
180
- // block a compaction on bookkeeping.
181
- try {
182
- const root = resolveRepoRoot(ctx.cwd);
183
- touchSession(sid, root, runtime.currentStateDir);
184
- logDaily(sid, "compact", result.checkpointId, saved, runtime.currentStateDir);
185
- } catch {
186
- /* non-fatal: stats bookkeeping only */
187
- }
212
+ // Record session activity + a daily-log entry in the per-repo SQLite store
213
+ // (foundation for resume-sessions / daily-log features). Best-effort — never
214
+ // block a compaction on bookkeeping.
215
+ try {
216
+ const root = resolveRepoRoot(ctx.cwd);
217
+ touchSession(sid, root, runtime.currentStateDir);
218
+ logDaily(
219
+ sid,
220
+ "compact",
221
+ result.checkpointId,
222
+ saved,
223
+ runtime.currentStateDir,
224
+ );
225
+ } catch {
226
+ /* non-fatal: stats bookkeeping only */
227
+ }
188
228
 
189
- // S21.2: best-effort consolidation of near-duplicate memories for this repo.
190
- // Runs after the per-repo stats touch so `consolidateMemories` can use the
191
- // same stateDir. Non-fatal — a failed consolidate never blocks a compaction.
192
- // Only runs when new memory ops landed in this pass (otherwise the prior
193
- // compaction's consolidate already had its shot — re-running would just
194
- // touch every row again with no merges).
195
- if (!result.deduped && runtime.memoriesTouchedThisCompaction > 0) {
196
- try {
197
- const root = resolveRepoRoot(ctx.cwd);
198
- void consolidateMemories(runtime.currentStateDir, root).then(
199
- (n) => {
200
- if (n > 0) runtime.pushTicker(`${C.green}∫${C.reset} consolidated ${n} memory dup${n === 1 ? "" : "s"}`);
201
- },
202
- () => {
203
- /* swallow: consolidate failures must never surface to the user */
204
- },
205
- );
206
- } catch {
207
- /* non-fatal */
208
- }
209
- }
229
+ // S21.2: best-effort consolidation of near-duplicate memories for this repo.
230
+ // Runs after the per-repo stats touch so `consolidateMemories` can use the
231
+ // same stateDir. Non-fatal — a failed consolidate never blocks a compaction.
232
+ // Only runs when new memory ops landed in this pass (otherwise the prior
233
+ // compaction's consolidate already had its shot — re-running would just
234
+ // touch every row again with no merges).
235
+ if (!result.deduped && runtime.memoriesTouchedThisCompaction > 0) {
236
+ try {
237
+ const root = resolveRepoRoot(ctx.cwd);
238
+ void consolidateMemories(runtime.currentStateDir, root).then(
239
+ (n) => {
240
+ if (n > 0)
241
+ runtime.pushTicker(
242
+ `${C.green}∫${C.reset} consolidated ${n} memory dup${n === 1 ? "" : "s"}`,
243
+ );
244
+ },
245
+ () => {
246
+ /* swallow: consolidate failures must never surface to the user */
247
+ },
248
+ );
249
+ } catch {
250
+ /* non-fatal */
251
+ }
252
+ }
210
253
 
211
- // S24 review-on-compact: when pressure is high, the just-compacted region is
212
- // exactly the context worth remembering, so review it immediately rather than
213
- // waiting for the next turn-cadence tick. Uses the shared runMemoryReview
214
- // helper (fire-and-forget; doCompact is sync). Best-effort + non-fatal. Only
215
- // fires above the `high` band so low-pressure compactions don't pay the cost.
216
- if (!result.deduped && config.memoryAutoReview && runtime.pressureBand !== "low" && runtime.pressureBand !== "medium") {
217
- void runMemoryReview(runtime, view, "pressure");
218
- }
254
+ // S24 review-on-compact: when pressure is high, the just-compacted region is
255
+ // exactly the context worth remembering, so review it immediately rather than
256
+ // waiting for the next turn-cadence tick. Uses the shared runMemoryReview
257
+ // helper (fire-and-forget; doCompact is sync). Best-effort + non-fatal. Only
258
+ // fires above the `high` band so low-pressure compactions don't pay the cost.
259
+ if (
260
+ !result.deduped &&
261
+ config.memoryAutoReview &&
262
+ runtime.pressureBand !== "low" &&
263
+ runtime.pressureBand !== "medium"
264
+ ) {
265
+ void runMemoryReview(runtime, view, "pressure");
266
+ }
219
267
 
220
- // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
221
- // skip re-vectorizing an already-compacted region (zero token cost).
222
- pi.appendEntry(MARKER_TYPE, {
223
- checkpointId: result.checkpointId,
224
- regionHash: result.regionHash,
225
- tokenEstimate: result.tokenEstimate,
226
- deduped: result.deduped,
227
- });
268
+ // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
269
+ // skip re-vectorizing an already-compacted region (zero token cost).
270
+ pi.appendEntry(MARKER_TYPE, {
271
+ checkpointId: result.checkpointId,
272
+ regionHash: result.regionHash,
273
+ tokenEstimate: result.tokenEstimate,
274
+ deduped: result.deduped,
275
+ });
228
276
 
229
- // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
230
- // serve high-level summaries. Best-effort + non-fatal: never block compaction.
231
- // Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
232
- if (config.raptorEnabled && !result.deduped) {
233
- try {
234
- const dd = loadDedupConfig();
235
- const all = runtime.store.list(sid);
236
- const leaves = all.map((cp) => ({
237
- id: cp.checkpointId,
238
- messages: [],
239
- sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
240
- embedding: cp.embedding,
241
- }));
242
- if (leaves.length >= 2) {
243
- // S25: stamp the tree with the newest checkpoint epoch so the
244
- // freshness guard in raptorSearchHits can reject stale trees after a
245
- // later compaction adds newer checkpoints.
246
- const builtAt = all.length > 0 ? Math.max(...all.map((c) => c.timestamp)) : Date.now();
247
- runRaptor(
248
- leaves,
249
- {
250
- stateDir: runtime.currentStateDir,
251
- sessionId: sid,
252
- budgetMs: dd.RAPTOR_BUDGET_MS,
253
- clustersPerLevel: dd.RAPTOR_CLUSTERS_PER_LEVEL,
254
- consistencyThreshold: dd.RAPTOR_CONSISTENCY,
255
- logger: runtime.logger,
256
- builtAt: Number.isFinite(builtAt) ? builtAt : Date.now(),
257
- },
258
- );
259
- }
260
- } catch {
261
- /* non-fatal: tree refresh never blocks a compaction */
262
- }
263
- }
277
+ // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
278
+ // serve high-level summaries. Best-effort + non-fatal: never block compaction.
279
+ // Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
280
+ if (config.raptorEnabled && !result.deduped) {
281
+ try {
282
+ const dd = loadDedupConfig();
283
+ const all = runtime.store.list(sid);
284
+ const leaves = all.map((cp) => ({
285
+ id: cp.checkpointId,
286
+ messages: [],
287
+ sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
288
+ embedding: cp.embedding,
289
+ }));
290
+ if (leaves.length >= 2) {
291
+ // S25: stamp the tree with the newest checkpoint epoch so the
292
+ // freshness guard in raptorSearchHits can reject stale trees after a
293
+ // later compaction adds newer checkpoints.
294
+ const builtAt =
295
+ all.length > 0
296
+ ? Math.max(...all.map((c) => c.timestamp))
297
+ : Date.now();
298
+ runRaptor(leaves, {
299
+ stateDir: runtime.currentStateDir,
300
+ sessionId: sid,
301
+ budgetMs: dd.RAPTOR_BUDGET_MS,
302
+ clustersPerLevel: dd.RAPTOR_CLUSTERS_PER_LEVEL,
303
+ consistencyThreshold: dd.RAPTOR_CONSISTENCY,
304
+ logger: runtime.logger,
305
+ builtAt: Number.isFinite(builtAt) ? builtAt : Date.now(),
306
+ });
307
+ }
308
+ } catch {
309
+ /* non-fatal: tree refresh never blocks a compaction */
310
+ }
311
+ }
264
312
 
265
- // Slice 2: best-effort mirror of the new checkpoint into the async global
266
- // PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
267
- // shared global dir is never hammered by concurrent test workers.
268
- // Non-fatal: a WASM init failure degrades to the sync scan silently.
269
- if (!result.deduped) {
270
- try {
271
- const all = runtime.store.list(sid);
272
- const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
273
- if (latest?.embedding) {
274
- void indexUpsertEmbedding(
275
- runtime.currentStateDir,
276
- sid,
277
- latest.checkpointId,
278
- latest.embedding,
279
- ).catch(() => {
280
- /* non-fatal: index refresh never blocks a compaction */
281
- });
282
- }
283
- } catch {
284
- /* non-fatal: index refresh never blocks a compaction */
285
- }
286
- }
313
+ // Slice 2: best-effort mirror of the new checkpoint into the async global
314
+ // PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
315
+ // shared global dir is never hammered by concurrent test workers.
316
+ // Non-fatal: a WASM init failure degrades to the sync scan silently.
317
+ if (!result.deduped) {
318
+ try {
319
+ const all = runtime.store.list(sid);
320
+ const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
321
+ if (latest?.embedding) {
322
+ void indexUpsertEmbedding(
323
+ runtime.currentStateDir,
324
+ sid,
325
+ latest.checkpointId,
326
+ latest.embedding,
327
+ ).catch(() => {
328
+ /* non-fatal: index refresh never blocks a compaction */
329
+ });
330
+ }
331
+ } catch {
332
+ /* non-fatal: index refresh never blocks a compaction */
333
+ }
334
+ }
287
335
 
288
- runtime.setStatus(
289
- ctx,
290
- runtime.rt.persistedThisSession
291
- ? `mega-compact: ${result.checkpointId} · ${saved} tok saved`
292
- : `mega-compact: ready`,
293
- );
294
- runtime.logger.info("compact", {
295
- sessionId: sid,
296
- checkpointId: result.checkpointId ?? "(deduped)",
297
- deduped: result.deduped,
298
- tokenEstimate: saved,
299
- compactedFrom: result.compactedFrom,
300
- });
301
- runtime.dashboard.event("compact", {
302
- sessionId: sid,
303
- checkpointId: result.checkpointId ?? "(deduped)",
304
- deduped: result.deduped,
305
- tokenEstimate: saved,
306
- compactedFrom: result.compactedFrom,
307
- });
308
- runtime.snapshot(ctx);
309
- return { skipped: false, result, keepFrom, saved };
336
+ runtime.setStatus(
337
+ ctx,
338
+ runtime.rt.persistedThisSession
339
+ ? `mega-compact: ${result.checkpointId} · ${saved} tok saved`
340
+ : `mega-compact: ready`,
341
+ );
342
+ runtime.logger.info("compact", {
343
+ sessionId: sid,
344
+ checkpointId: result.checkpointId ?? "(deduped)",
345
+ deduped: result.deduped,
346
+ tokenEstimate: saved,
347
+ compactedFrom: result.compactedFrom,
348
+ });
349
+ runtime.dashboard.event("compact", {
350
+ sessionId: sid,
351
+ checkpointId: result.checkpointId ?? "(deduped)",
352
+ deduped: result.deduped,
353
+ tokenEstimate: saved,
354
+ compactedFrom: result.compactedFrom,
355
+ });
356
+ runtime.snapshot(ctx);
357
+ return { skipped: false, result, keepFrom, saved };
310
358
  }
311
359
 
312
360
  /**
@@ -346,51 +394,55 @@ function doCompact(
346
394
  * is always safe; calling `ctx.compact()` on a no-op throws to the user.
347
395
  */
348
396
  export function piCompactWouldNoop(ctx: ExtensionContext): boolean {
349
- try {
350
- const branch = ctx.sessionManager.getBranch();
351
- if (branch.length === 0) return true;
352
- // (1) already compacted — pi throws "Already compacted"
353
- if (branch[branch.length - 1].type === "compaction") return true;
354
- // boundaryStart = index just after the most recent compaction entry (or 0)
355
- let boundaryStart = 0;
356
- for (let i = branch.length - 1; i >= 0; i--) {
357
- if (branch[i].type === "compaction") { boundaryStart = i + 1; break; }
358
- }
359
- let cutPoints = 0;
360
- let tokens = 0;
361
- for (let i = boundaryStart; i < branch.length; i++) {
362
- const e = branch[i];
363
- if (e.type === "compaction") continue;
364
- let isCut = false;
365
- for (const m of sessionEntryToContextMessages(e)) {
366
- // pi's isCutPointMessage: every role except toolResult
367
- if ((m as { role?: string }).role !== "toolResult") isCut = true;
368
- const c = (m as { content?: unknown }).content;
369
- const text =
370
- typeof c === "string" ? c
371
- : Array.isArray(c)
372
- ? (c as { text?: string }[]).map((b) => b?.text ?? "").join(" ")
373
- : "";
374
- if (text) tokens += estimateBlockTokens(text);
375
- }
376
- if (isCut) cutPoints++;
377
- }
378
- // (2) need >=2 cut points so the kept cut isn't the first message
379
- if (cutPoints < 2) return true;
380
- // (3) transcript under pi's keepRecentTokens budget → pi keeps everything
381
- if (tokens < durableTrimFloorTokens()) return true;
382
- return false;
383
- } catch {
384
- return true; // safe: skip the durable trim rather than risk a user-facing throw
385
- }
397
+ try {
398
+ const branch = ctx.sessionManager.getBranch();
399
+ if (branch.length === 0) return true;
400
+ // (1) already compacted — pi throws "Already compacted"
401
+ if (branch[branch.length - 1].type === "compaction") return true;
402
+ // boundaryStart = index just after the most recent compaction entry (or 0)
403
+ let boundaryStart = 0;
404
+ for (let i = branch.length - 1; i >= 0; i--) {
405
+ if (branch[i].type === "compaction") {
406
+ boundaryStart = i + 1;
407
+ break;
408
+ }
409
+ }
410
+ let cutPoints = 0;
411
+ let tokens = 0;
412
+ for (let i = boundaryStart; i < branch.length; i++) {
413
+ const e = branch[i];
414
+ if (e.type === "compaction") continue;
415
+ let isCut = false;
416
+ for (const m of sessionEntryToContextMessages(e)) {
417
+ // pi's isCutPointMessage: every role except toolResult
418
+ if ((m as { role?: string }).role !== "toolResult") isCut = true;
419
+ const c = (m as { content?: unknown }).content;
420
+ const text =
421
+ typeof c === "string"
422
+ ? c
423
+ : Array.isArray(c)
424
+ ? (c as { text?: string }[]).map((b) => b?.text ?? "").join(" ")
425
+ : "";
426
+ if (text) tokens += estimateBlockTokens(text);
427
+ }
428
+ if (isCut) cutPoints++;
429
+ }
430
+ // (2) need >=2 cut points so the kept cut isn't the first message
431
+ if (cutPoints < 2) return true;
432
+ // (3) transcript under pi's keepRecentTokens budget pi keeps everything
433
+ if (tokens < durableTrimFloorTokens()) return true;
434
+ return false;
435
+ } catch {
436
+ return true; // safe: skip the durable trim rather than risk a user-facing throw
437
+ }
386
438
  }
387
439
 
388
440
  /** pi's default keepRecentTokens (compaction settings). Override with
389
441
  * MEGACOMPACT_DURABLE_TRIM_FLOOR if you raise pi's compact.keepRecentTokens. */
390
442
  function durableTrimFloorTokens(): number {
391
- const raw = process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR;
392
- if (raw !== undefined && Number.isFinite(Number(raw))) return Number(raw);
393
- return 20_000;
443
+ const raw = process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR;
444
+ if (raw !== undefined && Number.isFinite(Number(raw))) return Number(raw);
445
+ return 20_000;
394
446
  }
395
447
 
396
448
  /**
@@ -399,42 +451,54 @@ function durableTrimFloorTokens(): number {
399
451
  * or report it (command).
400
452
  */
401
453
  export function doRecall(
402
- runtime: MegaRuntime,
403
- config: MegaConfig,
404
- ctx: ExtensionContext,
405
- query: string,
406
- source: "resume" | "command",
454
+ runtime: MegaRuntime,
455
+ config: MegaConfig,
456
+ ctx: ExtensionContext,
457
+ query: string,
458
+ source: "resume" | "command",
407
459
  ) {
408
- runtime.bindRepo(ctx.cwd);
409
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
410
- // Live window text for inline dedupe (Fix C): drop recalled checkpoints that
411
- // are already resident in the session, so recall never re-injects context the
412
- // model can already see. Best-effort — an empty window just skips dedupe.
413
- const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
414
- const result = recallAndInline(
415
- {
416
- sessionId: sid,
417
- query,
418
- limit: config.autoInlineK,
419
- source,
420
- skipInjected: true,
421
- recallMaxTokens: config.recallMaxTokens,
422
- windowDedupe: config.windowDedupe,
423
- liveWindow,
424
- dedupSim: config.dedupSim,
425
- },
426
- runtime.store,
427
- );
428
- runtime.dashboard.event("recall", { source, query: query.slice(0, 120), injected: result.toInject.length, empty: result.empty });
429
- if (!result.empty && result.toInject.length > 0) {
430
- const top = result.toInject[0];
431
- const scorePct = Math.round((top.score ?? 0) * 100);
432
- const files = top.checkpoint.filesModified ?? [];
433
- const label = files.length ? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ") : top.checkpoint.checkpointId;
434
- runtime.pushTicker(`${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`);
435
- runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
436
- }
437
- return result;
460
+ runtime.bindRepo(ctx.cwd);
461
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
462
+ // Live window text for inline dedupe (Fix C): drop recalled checkpoints that
463
+ // are already resident in the session, so recall never re-injects context the
464
+ // model can already see. Best-effort — an empty window just skips dedupe.
465
+ const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
466
+ const result = recallAndInline(
467
+ {
468
+ sessionId: sid,
469
+ query,
470
+ limit: config.autoInlineK,
471
+ source,
472
+ skipInjected: true,
473
+ recallMaxTokens: config.recallMaxTokens,
474
+ windowDedupe: config.windowDedupe,
475
+ liveWindow,
476
+ dedupSim: config.dedupSim,
477
+ },
478
+ runtime.store,
479
+ );
480
+ runtime.dashboard.event("recall", {
481
+ source,
482
+ query: query.slice(0, 120),
483
+ injected: result.toInject.length,
484
+ empty: result.empty,
485
+ });
486
+ if (!result.empty && result.toInject.length > 0) {
487
+ const top = result.toInject[0];
488
+ const scorePct = Math.round((top.score ?? 0) * 100);
489
+ const files = top.checkpoint.filesModified ?? [];
490
+ const label = files.length
491
+ ? files
492
+ .map((f) => f.split("/").pop() ?? f)
493
+ .slice(0, 2)
494
+ .join(", ")
495
+ : top.checkpoint.checkpointId;
496
+ runtime.pushTicker(
497
+ `${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`,
498
+ );
499
+ runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
500
+ }
501
+ return result;
438
502
  }
439
503
 
440
504
  /**
@@ -449,58 +513,81 @@ export function doRecall(
449
513
  * the same-repo result unchanged.
450
514
  */
451
515
  export async function doRecallAsync(
452
- runtime: MegaRuntime,
453
- config: MegaConfig,
454
- ctx: ExtensionContext,
455
- query: string,
456
- source: "resume" | "command",
457
- opts: { crossRepo?: boolean } = {},
516
+ runtime: MegaRuntime,
517
+ config: MegaConfig,
518
+ ctx: ExtensionContext,
519
+ query: string,
520
+ source: "resume" | "command",
521
+ opts: { crossRepo?: boolean } = {},
458
522
  ): Promise<RecallInjectResult> {
459
- runtime.bindRepo(ctx.cwd);
460
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
461
- const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
462
- // Sync same-repo first (fast, never blocks).
463
- const sameRepo = recallAndInline(
464
- {
465
- sessionId: sid, query, limit: config.autoInlineK, source, skipInjected: true,
466
- recallMaxTokens: config.recallMaxTokens, windowDedupe: config.windowDedupe,
467
- liveWindow, dedupSim: config.dedupSim,
468
- },
469
- runtime.store,
470
- );
471
- if (!config.crossRepoEnabled || !opts.crossRepo) return sameRepo;
472
- if (sameRepo.toInject.length >= config.autoInlineK) return sameRepo; // same-repo satisfied
473
- // Augment: cross-repo HNSW (async) with the stricter floor. Non-fatal.
474
- try {
475
- const x = await recallAndInlineAsync(
476
- {
477
- sessionId: sid, query, limit: config.autoInlineK, source, skipInjected: true,
478
- recallMaxTokens: config.recallMaxTokens, windowDedupe: config.windowDedupe,
479
- liveWindow, dedupSim: config.crossRepoCosine, crossRepo: true,
480
- globalIndexDir: process.env.MEGACOMPACT_INDEX_DIR,
481
- },
482
- runtime.store,
483
- );
484
- runtime.dashboard.event("recall-crossrepo", {
485
- source, query: query.slice(0, 120), injected: x.toInject.length,
486
- sourceRepos: x.toInject.map((h) => h.repoId).filter(Boolean),
487
- });
488
- // Merge, dedup by checkpointId, respect the same token cap by reformatting.
489
- const seen = new Set(sameRepo.toInject.map((h) => h.checkpoint.checkpointId));
490
- const merged = [...sameRepo.toInject];
491
- for (const h of x.toInject) {
492
- if (!seen.has(h.checkpoint.checkpointId)) { merged.push(h); seen.add(h.checkpoint.checkpointId); }
493
- }
494
- const block = merged.length ? formatRecallBlock(merged) : "";
495
- return {
496
- toInject: merged,
497
- report: merged.map((h) => ` • ${h.checkpoint.checkpointId}${h.repoId ? ` (from ${h.repoId.split("/").filter(Boolean).pop()})` : ""}`),
498
- block,
499
- empty: merged.length === 0,
500
- };
501
- } catch {
502
- return sameRepo; // cross-repo failure → same-repo only (non-fatal)
503
- }
523
+ runtime.bindRepo(ctx.cwd);
524
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
525
+ const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
526
+ // Sync same-repo first (fast, never blocks).
527
+ const sameRepo = recallAndInline(
528
+ {
529
+ sessionId: sid,
530
+ query,
531
+ limit: config.autoInlineK,
532
+ source,
533
+ skipInjected: true,
534
+ recallMaxTokens: config.recallMaxTokens,
535
+ windowDedupe: config.windowDedupe,
536
+ liveWindow,
537
+ dedupSim: config.dedupSim,
538
+ },
539
+ runtime.store,
540
+ );
541
+ if (!config.crossRepoEnabled || !opts.crossRepo) return sameRepo;
542
+ if (sameRepo.toInject.length >= config.autoInlineK) return sameRepo; // same-repo satisfied
543
+ // Augment: cross-repo HNSW (async) with the stricter floor. Non-fatal.
544
+ try {
545
+ const x = await recallAndInlineAsync(
546
+ {
547
+ sessionId: sid,
548
+ query,
549
+ limit: config.autoInlineK,
550
+ source,
551
+ skipInjected: true,
552
+ recallMaxTokens: config.recallMaxTokens,
553
+ windowDedupe: config.windowDedupe,
554
+ liveWindow,
555
+ dedupSim: config.crossRepoCosine,
556
+ crossRepo: true,
557
+ globalIndexDir: process.env.MEGACOMPACT_INDEX_DIR,
558
+ },
559
+ runtime.store,
560
+ );
561
+ runtime.dashboard.event("recall-crossrepo", {
562
+ source,
563
+ query: query.slice(0, 120),
564
+ injected: x.toInject.length,
565
+ sourceRepos: x.toInject.map((h) => h.repoId).filter(Boolean),
566
+ });
567
+ // Merge, dedup by checkpointId, respect the same token cap by reformatting.
568
+ const seen = new Set(
569
+ sameRepo.toInject.map((h) => h.checkpoint.checkpointId),
570
+ );
571
+ const merged = [...sameRepo.toInject];
572
+ for (const h of x.toInject) {
573
+ if (!seen.has(h.checkpoint.checkpointId)) {
574
+ merged.push(h);
575
+ seen.add(h.checkpoint.checkpointId);
576
+ }
577
+ }
578
+ const block = merged.length ? formatRecallBlock(merged) : "";
579
+ return {
580
+ toInject: merged,
581
+ report: merged.map(
582
+ (h) =>
583
+ ` • ${h.checkpoint.checkpointId}${h.repoId ? ` (from ${h.repoId.split("/").filter(Boolean).pop()})` : ""}`,
584
+ ),
585
+ block,
586
+ empty: merged.length === 0,
587
+ };
588
+ } catch {
589
+ return sameRepo; // cross-repo failure → same-repo only (non-fatal)
590
+ }
504
591
  }
505
592
 
506
593
  /**
@@ -510,18 +597,19 @@ export async function doRecallAsync(
510
597
  * Mirrors recentUserQuery's use of sessionEntryToContextMessages.
511
598
  */
512
599
  function extractLiveWindow(ctx: ExtensionContext): string[] {
513
- try {
514
- const entries = ctx.sessionManager.getEntries();
515
- const texts: string[] = [];
516
- for (const e of entries) {
517
- for (const m of sessionEntryToContextMessages(e)) {
518
- const c = (m as { content?: unknown }).content;
519
- if (typeof c === "string") texts.push(c);
520
- else if (Array.isArray(c)) texts.push(c.map((b: any) => b.text).join(" "));
521
- }
522
- }
523
- return texts;
524
- } catch {
525
- return [];
526
- }
600
+ try {
601
+ const entries = ctx.sessionManager.getEntries();
602
+ const texts: string[] = [];
603
+ for (const e of entries) {
604
+ for (const m of sessionEntryToContextMessages(e)) {
605
+ const c = (m as { content?: unknown }).content;
606
+ if (typeof c === "string") texts.push(c);
607
+ else if (Array.isArray(c))
608
+ texts.push(c.map((b: any) => b.text).join(" "));
609
+ }
610
+ }
611
+ return texts;
612
+ } catch {
613
+ return [];
614
+ }
527
615
  }