pi-mega-compact 0.8.24 → 0.8.26

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.
Files changed (111) hide show
  1. package/README.md +26 -0
  2. package/dist/extensions/mega-compact-s38.test.js +263 -14
  3. package/dist/extensions/mega-compact.js +15 -0
  4. package/dist/extensions/mega-config.js +3 -0
  5. package/dist/extensions/mega-events/agent-handlers.js +211 -26
  6. package/dist/extensions/mega-events/context-handler.js +45 -7
  7. package/dist/extensions/mega-events/error-classifier.js +125 -18
  8. package/dist/extensions/mega-pipeline/compact.js +24 -13
  9. package/dist/extensions/mega-pipeline/recall.js +31 -2
  10. package/dist/extensions/mega-runtime/dashboard-snapshot.js +4 -0
  11. package/dist/extensions/mega-runtime/runtime-snapshot.js +4 -0
  12. package/dist/extensions/mega-runtime/runtime.js +58 -5
  13. package/dist/src/boundary.js +79 -43
  14. package/dist/src/boundary.test.js +119 -2
  15. package/dist/src/canary.js +10 -0
  16. package/dist/src/config/dedup.js +14 -0
  17. package/dist/src/config.js +3 -1
  18. package/dist/src/dedup/raptor/buildHistory.js +164 -0
  19. package/dist/src/dedup/raptor/buildHistory.test.js +292 -0
  20. package/dist/src/dedup/raptor/index.js +38 -0
  21. package/dist/src/dedup/raptor/multilevel-serve.test.js +229 -0
  22. package/dist/src/dedup/raptor/multilevel.js +17 -5
  23. package/dist/src/dedup/raptor/multilevel.test.js +36 -1
  24. package/dist/src/dedup/raptor/raptor.test.js +43 -0
  25. package/dist/src/dedup/raptor/retrieval.js +14 -2
  26. package/dist/src/dedup/raptor/retrieval.test.js +95 -0
  27. package/dist/src/dedup/raptor/serve-gate.test.js +298 -0
  28. package/dist/src/dedup/raptor/summarizer.js +1 -0
  29. package/dist/src/dedup/raptor/tree.js +16 -2
  30. package/dist/src/engine.js +18 -2
  31. package/dist/src/httpEmbedder.js +96 -6
  32. package/dist/src/httpEmbedder.test.js +277 -0
  33. package/dist/src/mechanical-fix.test.js +65 -0
  34. package/dist/src/raptor-inject-summaries.test.js +162 -0
  35. package/dist/src/recall.js +153 -24
  36. package/dist/src/recall.test.js +179 -4
  37. package/dist/src/store/sqlite/dedup-mirror.js +32 -15
  38. package/dist/src/store/sqlite/maintenance.js +2 -2
  39. package/dist/src/store/sqlite/mechanical-fix.test.js +146 -0
  40. package/dist/src/store/sqlite/memories.js +5 -5
  41. package/dist/src/store/sqlite/meta.js +1 -1
  42. package/dist/src/store/sqlite/raptor.js +56 -17
  43. package/dist/src/store/sqlite/raptor.test.js +106 -0
  44. package/dist/src/store/sqlite/schema.js +90 -1
  45. package/dist/src/store/sqlite/session-state.js +9 -3
  46. package/dist/src/store/sqlite/stats.js +9 -5
  47. package/dist/src/store/sqlite/turns.js +179 -0
  48. package/dist/src/store/sqlite/turns.test.js +183 -0
  49. package/dist/src/store/sqlite/utils.js +15 -4
  50. package/dist/src/store/sqlite.js +1 -0
  51. package/dist/src/store.js +2 -2
  52. package/dist/src/vector-search-cache.test.js +157 -0
  53. package/dist/src/vector-search.js +107 -15
  54. package/dist/src/vectorStore.js +36 -8
  55. package/extensions/mega-compact-s38.test.ts +259 -14
  56. package/extensions/mega-compact.ts +15 -0
  57. package/extensions/mega-config.ts +18 -0
  58. package/extensions/mega-dashboard.ts +10 -1
  59. package/extensions/mega-events/agent-handlers.ts +211 -26
  60. package/extensions/mega-events/context-handler.ts +43 -7
  61. package/extensions/mega-events/error-classifier.ts +125 -17
  62. package/extensions/mega-pipeline/compact.ts +28 -16
  63. package/extensions/mega-pipeline/recall.ts +34 -2
  64. package/extensions/mega-runtime/dashboard-snapshot.ts +8 -0
  65. package/extensions/mega-runtime/helpers.ts +25 -1
  66. package/extensions/mega-runtime/runtime-snapshot.ts +4 -0
  67. package/extensions/mega-runtime/runtime.ts +69 -23
  68. package/package.json +1 -1
  69. package/src/boundary.test.ts +128 -2
  70. package/src/boundary.ts +75 -39
  71. package/src/canary.ts +10 -0
  72. package/src/config/dedup.ts +25 -0
  73. package/src/config.ts +3 -1
  74. package/src/dedup/raptor/buildHistory.test.ts +353 -0
  75. package/src/dedup/raptor/buildHistory.ts +259 -0
  76. package/src/dedup/raptor/index.ts +38 -0
  77. package/src/dedup/raptor/multilevel-serve.test.ts +273 -0
  78. package/src/dedup/raptor/multilevel.test.ts +47 -0
  79. package/src/dedup/raptor/multilevel.ts +18 -8
  80. package/src/dedup/raptor/raptor.test.ts +59 -0
  81. package/src/dedup/raptor/retrieval.test.ts +118 -0
  82. package/src/dedup/raptor/retrieval.ts +14 -2
  83. package/src/dedup/raptor/serve-gate.test.ts +348 -0
  84. package/src/dedup/raptor/summarizer.ts +1 -0
  85. package/src/dedup/raptor/tree.ts +17 -2
  86. package/src/engine.ts +32 -3
  87. package/src/httpEmbedder.test.ts +286 -0
  88. package/src/httpEmbedder.ts +98 -8
  89. package/src/mechanical-fix.test.ts +70 -0
  90. package/src/raptor-inject-summaries.test.ts +228 -0
  91. package/src/recall.test.ts +220 -4
  92. package/src/recall.ts +462 -265
  93. package/src/store/sqlite/dedup-mirror.ts +35 -18
  94. package/src/store/sqlite/maintenance.ts +2 -2
  95. package/src/store/sqlite/mechanical-fix.test.ts +162 -0
  96. package/src/store/sqlite/memories.ts +5 -5
  97. package/src/store/sqlite/meta.ts +1 -1
  98. package/src/store/sqlite/raptor.test.ts +139 -0
  99. package/src/store/sqlite/raptor.ts +135 -81
  100. package/src/store/sqlite/schema.ts +90 -1
  101. package/src/store/sqlite/session-state.ts +9 -3
  102. package/src/store/sqlite/stats.ts +10 -8
  103. package/src/store/sqlite/turns.test.ts +218 -0
  104. package/src/store/sqlite/turns.ts +302 -0
  105. package/src/store/sqlite/utils.ts +14 -4
  106. package/src/store/sqlite.ts +1 -0
  107. package/src/store.ts +9 -2
  108. package/src/vector-search-cache.test.ts +190 -0
  109. package/src/vector-search.ts +273 -156
  110. package/src/vectorStore.ts +443 -382
  111. package/extensions/mega-runtime/reset-runtime.ts +0 -80
@@ -0,0 +1,302 @@
1
+ /**
2
+ * turns.ts — S43 per-turn vector + conversation tracking.
3
+ *
4
+ * The relational spine for per-turn + per-conversation memories:
5
+ * - `turns`: one row per turn_end (metrics + epoch link + conversation id)
6
+ * - `turn_recall`: which checkpoints/cluster summaries were injected at a turn
7
+ * - `conversation_branches`: fork registry (parent → child at a turn point)
8
+ *
9
+ * `conversationId` (on SessionState) groups turns across pi session resumes;
10
+ * `/clear` or any fresh root generates a new one via `newConversationId()`.
11
+ *
12
+ * `forkConversation(parent, forkTurnId)` copies a parent conversation's
13
+ * recall state at `forkTurnId` into a fresh conversation's injected-set, so a
14
+ * forked session starts with exactly the context conversation X had at turn N
15
+ * (a recall-fork, not a live-window replay — see docs/specs/s48-per-turn-vector-tracking.md).
16
+ *
17
+ * No network. Pure SQLite (PREVENT-PI-004). All queries parameterized (PREVENT-002).
18
+ */
19
+
20
+ import { randomBytes } from "node:crypto";
21
+ import { openStore, withTx } from "./utils.js";
22
+ import { getStateDir, normalizeSessionId } from "../../store.js";
23
+ import { loadSessionState, saveSessionState } from "./session-state.js";
24
+ import type { DatabaseSync } from "node:sqlite";
25
+
26
+ /** A row in `turns`. */
27
+ export interface TurnRow {
28
+ id: number;
29
+ conversationId: string;
30
+ sessionId: string;
31
+ turnIndex: number;
32
+ role: string | null;
33
+ startedAt: number;
34
+ endedAt: number | null;
35
+ ctxTokens: number | null;
36
+ ctxPercent: number | null;
37
+ pressureBand: string | null;
38
+ modelId: string | null;
39
+ epochId: string | null;
40
+ }
41
+
42
+ /** A row in `turn_recall`. */
43
+ export interface TurnRecallRow {
44
+ id: number;
45
+ turnId: number;
46
+ checkpointId: string;
47
+ score: number;
48
+ source: string;
49
+ raptorLevel: number | null;
50
+ }
51
+
52
+ /** Where a recalled hit came from (recorded on turn_recall.source). */
53
+ export type RecallSource = "flat" | "raptor" | "cross-repo" | "memory";
54
+
55
+ /** Generate a new conversation id (`conv_` + 16 hex). */
56
+ export function newConversationId(): string {
57
+ return `conv_${randomBytes(8).toString("hex")}`;
58
+ }
59
+
60
+ function rowToTurn(r: Record<string, unknown>): TurnRow {
61
+ return {
62
+ id: r.id as number,
63
+ conversationId: r.conversation_id as string,
64
+ sessionId: r.session_id as string,
65
+ turnIndex: r.turn_index as number,
66
+ role: (r.role as string | null) ?? null,
67
+ startedAt: r.started_at as number,
68
+ endedAt: (r.ended_at as number | null) ?? null,
69
+ ctxTokens: (r.ctx_tokens as number | null) ?? null,
70
+ ctxPercent: (r.ctx_percent as number | null) ?? null,
71
+ pressureBand: (r.pressure_band as string | null) ?? null,
72
+ modelId: (r.model_id as string | null) ?? null,
73
+ epochId: (r.epoch_id as string | null) ?? null,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Upsert a turn row at turn_end. Returns the turn id. `startedAt` defaults to
79
+ * now (the turn_start write can update it; turn_end sets ended_at + metrics).
80
+ * Idempotent on (session_id, turn_index) — re-upserting overwrites metrics.
81
+ */
82
+ export function recordTurn(
83
+ input: {
84
+ conversationId: string;
85
+ sessionId: string;
86
+ turnIndex: number;
87
+ role?: string;
88
+ startedAt?: number;
89
+ endedAt?: number;
90
+ ctxTokens?: number;
91
+ ctxPercent?: number;
92
+ pressureBand?: string;
93
+ modelId?: string;
94
+ epochId?: string;
95
+ },
96
+ stateDir: string = getStateDir(),
97
+ ): number {
98
+ const db = openStore(stateDir);
99
+ const sid = normalizeSessionId(input.sessionId);
100
+ const startedAt = input.startedAt ?? Date.now();
101
+ db.prepare(
102
+ `INSERT INTO turns (conversation_id, session_id, turn_index, role, started_at,
103
+ ended_at, ctx_tokens, ctx_percent, pressure_band, model_id, epoch_id)
104
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
105
+ ON CONFLICT(session_id, turn_index) DO UPDATE SET
106
+ conversation_id = excluded.conversation_id,
107
+ role = COALESCE(excluded.role, role),
108
+ started_at = COALESCE(excluded.started_at, started_at),
109
+ ended_at = COALESCE(excluded.ended_at, ended_at),
110
+ ctx_tokens = COALESCE(excluded.ctx_tokens, ctx_tokens),
111
+ ctx_percent = COALESCE(excluded.ctx_percent, ctx_percent),
112
+ pressure_band = COALESCE(excluded.pressure_band, pressure_band),
113
+ model_id = COALESCE(excluded.model_id, model_id),
114
+ epoch_id = COALESCE(excluded.epoch_id, epoch_id)`,
115
+ ).run(
116
+ input.conversationId,
117
+ sid,
118
+ input.turnIndex,
119
+ input.role ?? null,
120
+ startedAt,
121
+ input.endedAt ?? null,
122
+ input.ctxTokens ?? null,
123
+ input.ctxPercent ?? null,
124
+ input.pressureBand ?? null,
125
+ input.modelId ?? null,
126
+ input.epochId ?? null,
127
+ );
128
+ const row = db
129
+ .prepare("SELECT id FROM turns WHERE session_id = ? AND turn_index = ?")
130
+ .get(sid, input.turnIndex) as { id: number };
131
+ return row.id;
132
+ }
133
+
134
+ /**
135
+ * Record what was recalled at a turn. Called from recallAndInline with the
136
+ * resolved toInject list — each hit becomes a turn_recall row with its source
137
+ * path + score. RAPTOR cluster hits carry raptorLevel. Best-effort + non-fatal.
138
+ */
139
+ export function recordTurnRecall(
140
+ turnId: number,
141
+ hits: {
142
+ checkpointId: string;
143
+ score: number;
144
+ source: RecallSource;
145
+ raptorLevel?: number;
146
+ }[],
147
+ stateDir: string = getStateDir(),
148
+ ): void {
149
+ if (hits.length === 0) return;
150
+ const db = openStore(stateDir);
151
+ const stmt = db.prepare(
152
+ `INSERT INTO turn_recall (turn_id, checkpoint_id, score, source, raptor_level)
153
+ VALUES (?, ?, ?, ?, ?)
154
+ ON CONFLICT(turn_id, checkpoint_id) DO UPDATE SET
155
+ score = excluded.score, source = excluded.source,
156
+ raptor_level = excluded.raptor_level`,
157
+ );
158
+ withTx(db, () => {
159
+ for (const h of hits) {
160
+ stmt.run(
161
+ turnId,
162
+ h.checkpointId,
163
+ h.score,
164
+ h.source,
165
+ h.raptorLevel ?? null,
166
+ );
167
+ }
168
+ });
169
+ }
170
+
171
+ /** Get a turn by conversation id + turn index (the lookup a fork uses). */
172
+ export function getTurn(
173
+ conversationId: string,
174
+ turnIndex: number,
175
+ stateDir: string = getStateDir(),
176
+ ): TurnRow | null {
177
+ const db = openStore(stateDir);
178
+ const row = db
179
+ .prepare(`SELECT * FROM turns WHERE conversation_id = ? AND turn_index = ?`)
180
+ .get(conversationId, turnIndex) as Record<string, unknown> | undefined;
181
+ return row ? rowToTurn(row) : null;
182
+ }
183
+
184
+ /** Get a turn by its global id. */
185
+ export function getTurnById(
186
+ turnId: number,
187
+ stateDir: string = getStateDir(),
188
+ ): TurnRow | null {
189
+ const db = openStore(stateDir);
190
+ const row = db.prepare("SELECT * FROM turns WHERE id = ?").get(turnId) as
191
+ | Record<string, unknown>
192
+ | undefined;
193
+ return row ? rowToTurn(row) : null;
194
+ }
195
+
196
+ /** All turn_recall rows for a turn (what was injected at that turn). */
197
+ export function listTurnRecall(
198
+ turnId: number,
199
+ stateDir: string = getStateDir(),
200
+ ): TurnRecallRow[] {
201
+ const db = openStore(stateDir);
202
+ const rows = db
203
+ .prepare(
204
+ `SELECT id, turn_id, checkpoint_id, score, source, raptor_level
205
+ FROM turn_recall WHERE turn_id = ? ORDER BY score DESC`,
206
+ )
207
+ .all(turnId) as Array<Record<string, unknown>>;
208
+ return rows.map((r) => ({
209
+ id: r.id as number,
210
+ turnId: r.turn_id as number,
211
+ checkpointId: r.checkpoint_id as string,
212
+ score: r.score as number,
213
+ source: r.source as string,
214
+ raptorLevel: (r.raptor_level as number | null) ?? null,
215
+ }));
216
+ }
217
+
218
+ /** All turns in a conversation, ascending by turn_index. */
219
+ export function listConversationTurns(
220
+ conversationId: string,
221
+ stateDir: string = getStateDir(),
222
+ ): TurnRow[] {
223
+ const db = openStore(stateDir);
224
+ const rows = db
225
+ .prepare(
226
+ `SELECT * FROM turns WHERE conversation_id = ? ORDER BY turn_index ASC`,
227
+ )
228
+ .all(conversationId) as Array<Record<string, unknown>>;
229
+ return rows.map(rowToTurn);
230
+ }
231
+
232
+ /** Resolve a session's conversation id, generating + persisting one if none.
233
+ * A resumed session inherits its existing conversationId from session_state. */
234
+ export function ensureConversationId(
235
+ sessionId: string,
236
+ stateDir: string = getStateDir(),
237
+ ): string {
238
+ const st = loadSessionState(sessionId, stateDir);
239
+ if (st.conversationId) return st.conversationId;
240
+ const conv = newConversationId();
241
+ saveSessionState(
242
+ sessionId,
243
+ {
244
+ ...st,
245
+ conversationId: conv,
246
+ },
247
+ stateDir,
248
+ );
249
+ return conv;
250
+ }
251
+
252
+ /**
253
+ * Fork a conversation at `forkTurnId`: create a new conversation id, record the
254
+ * branch lineage, and return the parent's recall set at that turn (the
255
+ * checkpoint_ids + scores that were injected) so the caller can seed the forked
256
+ * session's injected-set with exactly that context.
257
+ *
258
+ * Returns the new conversation id + the recall-set rows to replay. The caller
259
+ * (the engine/extension) is responsible for marking those checkpoint_ids as
260
+ * injected in the new session's session_state so they're not re-recalled.
261
+ */
262
+ export function forkConversation(
263
+ parentConversationId: string,
264
+ forkTurnId: number,
265
+ stateDir: string = getStateDir(),
266
+ ): { conversationId: string; recalled: TurnRecallRow[] } {
267
+ const childId = newConversationId();
268
+ const db: DatabaseSync = openStore(stateDir);
269
+ withTx(db, () => {
270
+ db.prepare(
271
+ `INSERT INTO conversation_branches
272
+ (conversation_id, parent_conversation_id, fork_turn_id, created_at)
273
+ VALUES (?, ?, ?, ?)
274
+ ON CONFLICT(conversation_id) DO NOTHING`,
275
+ ).run(childId, parentConversationId, forkTurnId, Date.now());
276
+ });
277
+ // Replay set: the parent's injected checkpoints at the fork turn.
278
+ const recalled = listTurnRecall(forkTurnId, stateDir);
279
+ return { conversationId: childId, recalled };
280
+ }
281
+
282
+ /** Clear turn tracking rows for a session (tests / DR). */
283
+ export function clearTurns(
284
+ sessionId: string,
285
+ stateDir: string = getStateDir(),
286
+ ): void {
287
+ const db: DatabaseSync = openStore(stateDir);
288
+ const sid = normalizeSessionId(sessionId);
289
+ withTx(db, () => {
290
+ const turnIds = db
291
+ .prepare("SELECT id FROM turns WHERE session_id = ?")
292
+ .all(sid) as Array<{ id: number }>;
293
+ const ids = turnIds.map((t) => t.id);
294
+ if (ids.length > 0) {
295
+ const placeholders = ids.map(() => "?").join(",");
296
+ db.prepare(
297
+ `DELETE FROM turn_recall WHERE turn_id IN (${placeholders})`,
298
+ ).run(...ids);
299
+ }
300
+ db.prepare("DELETE FROM turns WHERE session_id = ?").run(sid);
301
+ });
302
+ }
@@ -41,6 +41,16 @@ export function jsonText(v: unknown): string {
41
41
  return JSON.stringify(v ?? []);
42
42
  }
43
43
 
44
+ /** Safe JSON parse — returns `fallback` on null/undefined/corrupt input. */
45
+ export function safeJson<T>(s: string | null | undefined, fallback: T): T {
46
+ if (!s) return fallback;
47
+ try {
48
+ return JSON.parse(s) as T;
49
+ } catch {
50
+ return fallback;
51
+ }
52
+ }
53
+
44
54
  // In-process cache so the same stateDir reuses one connection (and so a fresh
45
55
  // VectorStore over the same dir shares the open DB). Cross-process durability
46
56
  // comes from reopening the same file path — proven by the integration test.
@@ -54,7 +64,7 @@ export function openStore(stateDir: string = getStateDir()): DatabaseSync {
54
64
  // instead of closeStore) would surface as "database is not open" on the
55
65
  // next reuse. Detect and evict so callers never see a dead handle.
56
66
  try {
57
- existing.prepare("SELECT 1");
67
+ existing.exec("SELECT 1");
58
68
  return existing;
59
69
  } catch {
60
70
  cache.delete(stateDir);
@@ -105,9 +115,9 @@ export function rowToCheckpoint(row: any): StoredCheckpoint {
105
115
  summary: row.summary ?? "",
106
116
  topicSummary: row.topic_summary ?? undefined,
107
117
  summaryHash: row.summary_hash ?? undefined,
108
- keyDecisions: row.key_decisions ? JSON.parse(row.key_decisions) : [],
109
- nextSteps: row.next_steps ? JSON.parse(row.next_steps) : [],
110
- filesModified: row.files_modified ? JSON.parse(row.files_modified) : [],
118
+ keyDecisions: safeJson<string[]>(row.key_decisions, []),
119
+ nextSteps: safeJson<string[]>(row.next_steps, []),
120
+ filesModified: safeJson<string[]>(row.files_modified, []),
111
121
  tokenEstimate: row.token_estimate ?? 0,
112
122
  originalTokenEstimate: row.original_token_estimate ?? undefined,
113
123
  regionHash: row.region_hash ?? "",
@@ -24,3 +24,4 @@ export * from "./sqlite/game-state.js";
24
24
  export * from "./sqlite/game-scores.js";
25
25
  export * from "./sqlite/game-achievements.js";
26
26
  export * from "./sqlite/perf-samples.js";
27
+ export * from "./sqlite/turns.js";
package/src/store.ts CHANGED
@@ -41,7 +41,7 @@ export function normalizeSessionId(sessionId: string | undefined | null): string
41
41
  if (!sessionId) return `sess_${randomBytes(8).toString("hex")}`;
42
42
  if (sessionId.startsWith("sess_")) return sessionId;
43
43
  if (sessionId.length >= 32 && sessionId.includes("-")) {
44
- return `sess_${sessionId.replace(/-/g, "").slice(0, 16)}`;
44
+ return `sess_${sessionId.replace(/-/g, "").toLowerCase().slice(0, 16)}`;
45
45
  }
46
46
  return `sess_${sessionId}`;
47
47
  }
@@ -113,7 +113,7 @@ export function writeGzJson(path: string, data: unknown): void {
113
113
 
114
114
  /** Append a checkpoint to the per-session checkpoint file (gzipped). */
115
115
  export function appendCheckpoint(cp: StoredCheckpoint, stateDir: string = getStateDir()): void {
116
- const file = join(stateDir, `${cp.sessionId}.checkpoints.json.gz`);
116
+ const file = join(stateDir, `${normalizeSessionId(cp.sessionId)}.checkpoints.json.gz`);
117
117
  const existing = readGzJson<StoredCheckpoint[]>(file, []);
118
118
  existing.push(cp);
119
119
  writeGzJson(file, existing);
@@ -157,6 +157,13 @@ export interface SessionState {
157
157
  injectedCheckpointIds: string[];
158
158
  /** regionHashes already represented (for sentinel dedup). */
159
159
  storedRegionHashes: string[];
160
+ /** S43: conversation id grouping turns across pi session resumes. A resumed
161
+ * session inherits its parent's; /clear (or any fresh root) generates a new
162
+ * one. A fork copies the parent's turn-N injected-set and starts a new id. */
163
+ conversationId?: string;
164
+ /** S43: the global turn id of the most recent turn_end in this conversation.
165
+ * Carried across resumes so fork-turn references stay stable. */
166
+ lastTurnId?: number;
160
167
  }
161
168
 
162
169
  /** Load mutable session state (created on demand). */
@@ -0,0 +1,190 @@
1
+ /**
2
+ * vector-search-cache.test.ts — QA perf/correctness regression tests for the
3
+ * RAPTOR serve path and the per-session raptorCache.
4
+ *
5
+ * Guards two invariants the S42B/S25 wiring introduced:
6
+ * (a) Enabling RAPTOR (multilevel ON) never returns FEWER relevant hits than
7
+ * flat-only at the same k — no cache-hit loss / MMR starvation.
8
+ * (b) The per-search listCheckpoints is shared (not double-loaded): the
9
+ * warm-search latency at 200 checkpoints stays under the QA budget.
10
+ *
11
+ * No network. Real stores, temp state dirs.
12
+ */
13
+
14
+ import { test, beforeEach, afterEach } from "node:test";
15
+ import assert from "node:assert/strict";
16
+ import { mkdtempSync, rmSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { join } from "node:path";
19
+ import { VectorStore, vectorList, vectorSearch } from "./vectorStore.js";
20
+ import { runRaptor } from "./dedup/raptor/index.js";
21
+ import { compactSession } from "./engine.js";
22
+ import { loadDedupConfig } from "./config/dedup.js";
23
+ import { normalizeSessionId } from "./store.js";
24
+ import type { EngineMessage } from "./types.js";
25
+ import type { DedupConfigShape } from "./config/dedup.js";
26
+
27
+ let tmpDir: string;
28
+ let counter = 0;
29
+
30
+ beforeEach(() => {
31
+ tmpDir = mkdtempSync(join(tmpdir(), "mc-vc-"));
32
+ });
33
+
34
+ afterEach(() => {
35
+ rmSync(tmpDir, { recursive: true, force: true });
36
+ });
37
+
38
+ function stateDir(): string {
39
+ return join(tmpDir, `run-${counter++}`);
40
+ }
41
+
42
+ function cfg(overrides?: Record<string, unknown>): DedupConfigShape {
43
+ return {
44
+ ...loadDedupConfig(),
45
+ RAPTOR_ENABLED: true,
46
+ L0_ENABLED: false,
47
+ L1_ENABLED: false,
48
+ L2_ENABLED: true,
49
+ ...overrides,
50
+ };
51
+ }
52
+
53
+ function msg(text: string, toolName?: string): EngineMessage {
54
+ return toolName
55
+ ? { role: "assistant", text, toolName, input: text, output: text }
56
+ : { role: "user", text };
57
+ }
58
+
59
+ function seedTwoTopics(store: VectorStore, sid: string, perTopic: number) {
60
+ const topics = [
61
+ "database connection pool postgres query optimizer",
62
+ "user interface button render react component",
63
+ ];
64
+ for (let i = 1; i <= perTopic * 2; i++) {
65
+ const t = topics[i % 2];
66
+ compactSession(
67
+ {
68
+ sessionId: sid,
69
+ messages: [msg(`${t} checkpoint ${i} alpha beta gamma`), msg(`ack ${i}`, "Edit")],
70
+ keepFrom: 2,
71
+ timestamp: i,
72
+ },
73
+ store,
74
+ );
75
+ }
76
+ }
77
+
78
+ // ─── (a) RAPTOR ON never loses hits vs OFF ──────────────────────────────────
79
+
80
+ test("QA cache: RAPTOR-ON returns >= flat-only hits at same k (no MMR starvation)", () => {
81
+ const k = 5;
82
+ // Build the same session twice (isolated state dirs) so the comparison is
83
+ // exact: same checkpoints, same embeddings, only the RAPTOR flag differs.
84
+ const queries = ["database connection pool", "user interface button", "alpha beta gamma"];
85
+
86
+ for (const q of queries) {
87
+ let offHits = 0;
88
+ let onHits = 0;
89
+ for (const raptorOn of [false, true]) {
90
+ const sd = stateDir();
91
+ const s = new VectorStore({
92
+ dedupSim: 0.9,
93
+ stateDir: sd,
94
+ config: raptorOn
95
+ ? cfg({ RAPTOR_MULTILEVEL_ENABLED: true, RAPTOR_LEAF_EXPANSION: true })
96
+ : cfg({ RAPTOR_ENABLED: false }),
97
+ });
98
+ const sid = `cache-${q.length}-${raptorOn ? 1 : 0}`;
99
+ seedTwoTopics(s, sid, 8); // 16 checkpoints, 2 topics
100
+ if (raptorOn) {
101
+ const nsid = normalizeSessionId(sid);
102
+ runRaptor(
103
+ vectorList(s, nsid).map((cp) => ({
104
+ id: cp.checkpointId,
105
+ messages: [],
106
+ sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
107
+ embedding: cp.embedding,
108
+ })),
109
+ { stateDir: sd, sessionId: nsid },
110
+ );
111
+ }
112
+ process.env.RAPTOR_SHADOW_MODE = raptorOn ? "false" : "true";
113
+ const hits = vectorSearch(s, sid, q, k);
114
+ if (raptorOn) onHits = hits.length;
115
+ else offHits = hits.length;
116
+ }
117
+ assert.ok(
118
+ onHits >= offHits,
119
+ `RAPTOR ON (${onHits}) >= OFF (${offHits}) for query "${q}"`,
120
+ );
121
+ }
122
+ });
123
+
124
+ // ─── (b) Warm-search latency budget at 200 checkpoints ─────────────────────
125
+
126
+ test("QA perf: warm RAPTOR search at 200 checkpoints stays under budget (no double scan)", () => {
127
+ const sd = stateDir();
128
+ const s = new VectorStore({
129
+ dedupSim: 0.9,
130
+ stateDir: sd,
131
+ config: cfg({ RAPTOR_MULTILEVEL_ENABLED: true }),
132
+ });
133
+ const sid = "perf";
134
+ seedTwoTopics(s, sid, 100); // 200 checkpoints
135
+ const nsid = normalizeSessionId(sid);
136
+ runRaptor(
137
+ vectorList(s, nsid).map((cp) => ({
138
+ id: cp.checkpointId,
139
+ messages: [],
140
+ sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
141
+ embedding: cp.embedding,
142
+ })),
143
+ { stateDir: sd, sessionId: nsid },
144
+ );
145
+ process.env.RAPTOR_SHADOW_MODE = "false";
146
+ // Warm the cache + embedder.
147
+ vectorSearch(s, sid, "database connection pool", 5);
148
+ vectorSearch(s, sid, "database connection pool", 5);
149
+ // Time a burst of warm searches. The double-scan fix keeps this well under
150
+ // the pre-fix cost. Budget is generous (10ms/search) to avoid CI flake;
151
+ // the regression it guards is the ~2x blowup from listCheckpoints running
152
+ // twice per search.
153
+ const ITERS = 50;
154
+ const t0 = Date.now();
155
+ for (let i = 0; i < ITERS; i++)
156
+ vectorSearch(s, sid, "database connection pool", 5);
157
+ const perSearch = (Date.now() - t0) / ITERS;
158
+ assert.ok(
159
+ perSearch < 10,
160
+ `warm search ${perSearch.toFixed(2)}ms < 10ms budget (double-scan regression guard)`,
161
+ );
162
+ });
163
+
164
+ // ─── (c) No duplicate checkpointIds in merged results ──────────────────────
165
+
166
+ test("QA cache: RAPTOR merge produces no duplicate checkpointIds", () => {
167
+ const sd = stateDir();
168
+ const s = new VectorStore({
169
+ dedupSim: 0.9,
170
+ stateDir: sd,
171
+ config: cfg({ RAPTOR_MULTILEVEL_ENABLED: true, RAPTOR_LEAF_EXPANSION: false }),
172
+ });
173
+ const sid = "dup";
174
+ seedTwoTopics(s, sid, 8);
175
+ const nsid = normalizeSessionId(sid);
176
+ runRaptor(
177
+ vectorList(s, nsid).map((cp) => ({
178
+ id: cp.checkpointId,
179
+ messages: [],
180
+ sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
181
+ embedding: cp.embedding,
182
+ })),
183
+ { stateDir: sd, sessionId: nsid },
184
+ );
185
+ process.env.RAPTOR_SHADOW_MODE = "false";
186
+ const hits = vectorSearch(s, sid, "database connection pool", 8);
187
+ const ids = hits.map((h) => h.checkpoint.checkpointId);
188
+ const dupes = ids.filter((id, i) => ids.indexOf(id) !== i);
189
+ assert.equal(dupes.length, 0, "no duplicate checkpointIds in merged results");
190
+ });