pi-mega-compact 0.4.0

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 (69) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +375 -0
  3. package/extensions/DASHBOARD.md +160 -0
  4. package/extensions/dashboard-server.test.ts +124 -0
  5. package/extensions/dashboard-server.ts +459 -0
  6. package/extensions/error-patterns.ts +175 -0
  7. package/extensions/mega-compact.test.ts +351 -0
  8. package/extensions/mega-compact.ts +846 -0
  9. package/extensions/openclaw-mega-compact.ts +370 -0
  10. package/package.json +61 -0
  11. package/src/adapt.ts +120 -0
  12. package/src/boundary.test.ts +61 -0
  13. package/src/boundary.ts +94 -0
  14. package/src/canary.ts +126 -0
  15. package/src/compact.test.ts +99 -0
  16. package/src/compact.ts +262 -0
  17. package/src/config/dedup.ts +120 -0
  18. package/src/config.ts +15 -0
  19. package/src/dedup/dedup.test.ts +46 -0
  20. package/src/dedup/digest.ts +40 -0
  21. package/src/dedup/l1-lsh.ts +67 -0
  22. package/src/dedup/l1-minhash.ts +90 -0
  23. package/src/dedup/l1-verify.ts +55 -0
  24. package/src/dedup/l1.test.ts +57 -0
  25. package/src/dedup/mmr.ts +54 -0
  26. package/src/dedup/normalize.ts +41 -0
  27. package/src/dedup/raptor/guardrails.ts +112 -0
  28. package/src/dedup/raptor/index.ts +118 -0
  29. package/src/dedup/raptor/kmeans.ts +156 -0
  30. package/src/dedup/raptor/raptor.test.ts +238 -0
  31. package/src/dedup/raptor/retrieval.ts +102 -0
  32. package/src/dedup/raptor/summarizer.ts +91 -0
  33. package/src/dedup/raptor/tree.ts +254 -0
  34. package/src/dedup/sprint12.test.ts +242 -0
  35. package/src/dedup/topk.ts +61 -0
  36. package/src/dedup-engine.test.ts +609 -0
  37. package/src/e2e.test.ts +843 -0
  38. package/src/embedder.ts +111 -0
  39. package/src/engine.test.ts +123 -0
  40. package/src/engine.ts +192 -0
  41. package/src/extractive.test.ts +156 -0
  42. package/src/extractive.ts +265 -0
  43. package/src/httpEmbedder.ts +154 -0
  44. package/src/log.test.ts +47 -0
  45. package/src/log.ts +60 -0
  46. package/src/monitoring.ts +171 -0
  47. package/src/ratio.bench.test.ts +1316 -0
  48. package/src/recall.integration.test.ts +96 -0
  49. package/src/recall.test.ts +59 -0
  50. package/src/recall.ts +100 -0
  51. package/src/sprint14.test.ts +245 -0
  52. package/src/store/backfill.ts +263 -0
  53. package/src/store/bloom.ts +122 -0
  54. package/src/store/compression.test.ts +83 -0
  55. package/src/store/compression.ts +203 -0
  56. package/src/store/integrity.ts +65 -0
  57. package/src/store/migrate.test.ts +158 -0
  58. package/src/store/migrate.ts +108 -0
  59. package/src/store/sprint10.test.ts +182 -0
  60. package/src/store/sqlite.ts +519 -0
  61. package/src/store.test.ts +169 -0
  62. package/src/store.ts +192 -0
  63. package/src/supersede.test.ts +42 -0
  64. package/src/supersede.ts +67 -0
  65. package/src/tokens.ts +35 -0
  66. package/src/types.test.ts +10 -0
  67. package/src/types.ts +49 -0
  68. package/src/vectorStore.test.ts +480 -0
  69. package/src/vectorStore.ts +544 -0
@@ -0,0 +1,61 @@
1
+ /**
2
+ * topk.ts — min-heap based top-K selection (Sprint 12, QA #4).
3
+ *
4
+ * Replaces the O(N log N) full `.sort()` in search() with an O(N log k) heap,
5
+ * which matters once a session holds thousands of checkpoints. Generic over any
6
+ * scored item with a numeric `score`.
7
+ *
8
+ * Pure, no deps, no network (PREVENT-PI-004).
9
+ */
10
+
11
+ export interface Scored<T> {
12
+ item: T;
13
+ score: number;
14
+ }
15
+
16
+ /**
17
+ * Return the `k` highest-scoring items (stable insertion order on ties).
18
+ * O(N log k) — a bounded min-heap of size k.
19
+ */
20
+ export function topK<T>(items: Scored<T>[], k: number): Scored<T>[] {
21
+ if (k <= 0) return [];
22
+ if (items.length <= k) return [...items].sort((a, b) => b.score - a.score);
23
+
24
+ // Min-heap of the current top-k, stored as a flat array of Scored<T>.
25
+ const heap: Scored<T>[] = [];
26
+ const push = (e: Scored<T>): void => {
27
+ heap.push(e);
28
+ let i = heap.length - 1;
29
+ while (i > 0) {
30
+ const parent = (i - 1) >> 1;
31
+ if (heap[parent].score <= heap[i].score) break;
32
+ [heap[parent], heap[i]] = [heap[i], heap[parent]];
33
+ i = parent;
34
+ }
35
+ };
36
+ const siftDown = (start: number): void => {
37
+ let i = start;
38
+ for (;;) {
39
+ const l = 2 * i + 1;
40
+ const r = 2 * i + 2;
41
+ let smallest = i;
42
+ if (l < heap.length && heap[l].score < heap[smallest].score) smallest = l;
43
+ if (r < heap.length && heap[r].score < heap[smallest].score) smallest = r;
44
+ if (smallest === i) break;
45
+ [heap[smallest], heap[i]] = [heap[i], heap[smallest]];
46
+ i = smallest;
47
+ }
48
+ };
49
+
50
+ for (const it of items) {
51
+ if (heap.length < k) {
52
+ push(it);
53
+ } else if (it.score > heap[0].score) {
54
+ // Replace the current minimum with this better-scoring item, then sift
55
+ // it down to restore the min-heap invariant.
56
+ heap[0] = it;
57
+ siftDown(0);
58
+ }
59
+ }
60
+ return heap.sort((a, b) => b.score - a.score);
61
+ }
@@ -0,0 +1,609 @@
1
+ /**
2
+ * dedup-engine.test.ts — comprehensive compaction + dedup level test suite.
3
+ *
4
+ * Covers:
5
+ * 1. Compaction tier thresholds (low/medium/high/ultra/mega)
6
+ * 2. Dedup levels (L0/L1/L2/disabled, and combined)
7
+ * 3. Compaction ratios across conversation sizes
8
+ * 4. Store stats + injected-count tracking
9
+ * 5. Recall & dedup sentinel behavior
10
+ * 6. Edge cases (empty/single/near-end/unicode/large/mixed roles)
11
+ * 7. Tier switching via MEGACOMPACT_TIER env var
12
+ */
13
+
14
+ import { describe, it, beforeEach, afterEach } from "node:test";
15
+ import assert from "node:assert/strict";
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import os from "os";
19
+ import { compactSession } from "./engine.js";
20
+ import { VectorStore } from "./vectorStore.js";
21
+ import { extractiveSummarize } from "./extractive.js";
22
+ import { estimateSessionTokens, estimateMessageTokens } from "./tokens.js";
23
+ import { autoCompactCheck } from "./compact.js";
24
+ import { loadDedupConfig, type DedupConfigShape } from "./config/dedup.js";
25
+ import type { EngineMessage } from "./types.js";
26
+
27
+ // recallAndInline may or may not be exported; import safely.
28
+ import * as recallMod from "./recall.js";
29
+
30
+ interface RecallInjectResult {
31
+ toInject: unknown[];
32
+ empty: boolean;
33
+ }
34
+
35
+ const recallAndInline = (recallMod as any).recallAndInline as
36
+ | ((
37
+ opts: {
38
+ sessionId: string;
39
+ query: string;
40
+ limit?: number;
41
+ source: "command";
42
+ skipInjected?: boolean;
43
+ },
44
+ store: VectorStore,
45
+ ) => RecallInjectResult)
46
+ | undefined;
47
+
48
+ // -------------------- Helpers --------------------
49
+
50
+ function mkTmpDir(): string {
51
+ return fs.mkdtempSync(path.join(os.tmpdir(), "mc-dedup-"));
52
+ }
53
+
54
+ let currentTmpDir: string | undefined;
55
+
56
+ beforeEach(() => {
57
+ currentTmpDir = mkTmpDir();
58
+ });
59
+
60
+ afterEach(() => {
61
+ if (currentTmpDir && fs.existsSync(currentTmpDir)) {
62
+ fs.rmSync(currentTmpDir, { recursive: true, force: true });
63
+ }
64
+ currentTmpDir = undefined;
65
+ });
66
+
67
+ function baseConfig(): DedupConfigShape {
68
+ return loadDedupConfig();
69
+ }
70
+
71
+ function makeStore(over: Partial<DedupConfigShape> = {}): VectorStore {
72
+ return new VectorStore({
73
+ stateDir: currentTmpDir,
74
+ config: { ...baseConfig(), ...over },
75
+ });
76
+ }
77
+
78
+ function makeMsg(role: EngineMessage["role"], text: string): EngineMessage {
79
+ return { role, text };
80
+ }
81
+
82
+ function buildConversation(n: number, prefix = "turn"): EngineMessage[] {
83
+ const out: EngineMessage[] = [];
84
+ for (let i = 0; i < n; i++) {
85
+ const role = i % 2 === 0 ? "user" : "assistant";
86
+ out.push(
87
+ makeMsg(
88
+ role,
89
+ `${prefix} ${i + 1}: ${role} discusses implementation of feature ${i + 1} in src/module${i + 1}.ts and considers tradeoffs.`,
90
+ ),
91
+ );
92
+ }
93
+ return out;
94
+ }
95
+
96
+ function compactFull(
97
+ store: VectorStore,
98
+ sessionId: string,
99
+ messages: EngineMessage[],
100
+ keepFrom?: number,
101
+ ): ReturnType<typeof compactSession> {
102
+ return compactSession({ sessionId, messages, keepFrom: keepFrom ?? messages.length }, store);
103
+ }
104
+
105
+ // -------------------- 1. Compaction Levels --------------------
106
+
107
+ describe("Compaction Levels (Tier Behavior)", () => {
108
+ const TIER_CASES: Array<[string, number]> = [
109
+ ["low", 50_000],
110
+ ["medium", 100_000],
111
+ ["high", 200_000],
112
+ ["ultra", 1_000_000],
113
+ ["mega", 10_000_000],
114
+ ];
115
+
116
+ for (const [tier, threshold] of TIER_CASES) {
117
+ it(`tier "${tier}" (${threshold.toLocaleString()} threshold) triggers only when tokens exceed threshold`, () => {
118
+ // One token below threshold => should not compact.
119
+ const under = autoCompactCheck(threshold - 1, threshold);
120
+ assert.equal(under.shouldCompact, false, "one token below threshold should not trigger");
121
+ assert.equal(under.threshold, threshold);
122
+
123
+ // At threshold => should compact.
124
+ const at = autoCompactCheck(threshold, threshold);
125
+ assert.equal(at.shouldCompact, true, "at threshold should trigger");
126
+
127
+ // One token above threshold => should compact.
128
+ const over = autoCompactCheck(threshold + 1, threshold);
129
+ assert.equal(over.shouldCompact, true, "one token above threshold should trigger");
130
+
131
+ // Generate deterministic conversation of known token size.
132
+ const tokensPerMsg = estimateMessageTokens({
133
+ text: "deterministic sample message of moderate length for threshold testing.",
134
+ });
135
+ assert.ok(tokensPerMsg > 0);
136
+ const needed = Math.ceil((threshold + tokensPerMsg) / tokensPerMsg);
137
+ const messages = buildConversation(needed);
138
+ const estimate = estimateSessionTokens(messages);
139
+ assert.ok(
140
+ estimate >= threshold,
141
+ `expected estimate ${estimate} >= threshold ${threshold}`,
142
+ );
143
+ const longCheck = autoCompactCheck(estimate, threshold);
144
+ assert.equal(longCheck.shouldCompact, true);
145
+
146
+ // Smaller conversation should not trigger. Derive the average per-message
147
+ // cost from the large conversation we already tokenized, then leave margin below threshold.
148
+ const avgTokensPerMsg = estimate / messages.length;
149
+ const smallCount = Math.max(1, Math.floor((threshold * 0.95) / avgTokensPerMsg) - 5);
150
+ const smallMessages = buildConversation(smallCount);
151
+ const smallEstimate = estimateSessionTokens(smallMessages);
152
+ assert.ok(
153
+ smallEstimate < threshold,
154
+ `expected small estimate ${smallEstimate} < threshold ${threshold}`,
155
+ );
156
+ const smallCheck = autoCompactCheck(smallEstimate, threshold);
157
+ assert.equal(smallCheck.shouldCompact, false, "small conversation should not trigger tier");
158
+ });
159
+ }
160
+ });
161
+
162
+ // -------------------- 2. Dedupe Levels --------------------
163
+
164
+ describe("Dedupe Levels", () => {
165
+ const SESS = "sess_dedup";
166
+
167
+ it("L0 only: identical content stored twice collapses to one checkpoint", () => {
168
+ const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
169
+ const region = "exact same user request about database migration and index setup";
170
+
171
+ const r1 = compactFull(s, SESS, [makeMsg("user", region)]);
172
+ assert.equal(r1.deduped, false);
173
+ assert.ok(r1.checkpointId);
174
+
175
+ const r2 = compactFull(s, SESS, [makeMsg("user", region)]);
176
+ assert.equal(r2.deduped, true);
177
+ assert.equal(r2.checkpointId, r1.checkpointId);
178
+ assert.equal(s.list(SESS).length, 1);
179
+ });
180
+
181
+ it("L0 only: distinct content stored twice creates two checkpoints", () => {
182
+ const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
183
+ const regionA = "first exact region about authentication module refactoring";
184
+ const regionB = "second distinct region about frontend component testing";
185
+
186
+ const r1 = compactFull(s, SESS, [makeMsg("user", regionA)]);
187
+ const r2 = compactFull(s, SESS, [makeMsg("user", regionB)]);
188
+ assert.equal(r1.deduped, false);
189
+ assert.equal(r2.deduped, false);
190
+ assert.notEqual(r1.checkpointId, r2.checkpointId);
191
+ assert.equal(s.list(SESS).length, 2);
192
+ });
193
+
194
+ it("L1 only: one-word variants collapse; major rewrites do not", () => {
195
+ const s = makeStore({ L0_ENABLED: false, L1_ENABLED: true, L2_ENABLED: false });
196
+
197
+ const base = "the database migration added three new indexes to the users table for faster lookups";
198
+ const variant = "the database migration added three new indexes to the users table for faster lookup";
199
+ const rewrite = "the frontend dark mode toggle uses css custom properties for theming";
200
+
201
+ const r1 = s.add({ sessionId: SESS, summary: "migration", regionText: base, timestamp: 1 });
202
+ assert.equal(r1.deduped, false);
203
+
204
+ const r2 = s.add({ sessionId: SESS, summary: "migration", regionText: variant, timestamp: 2 });
205
+ assert.equal(r2.deduped, true, "one-word variant should be collapsed by L1");
206
+ assert.equal(s.list(SESS).length, 1);
207
+
208
+ const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: rewrite, timestamp: 3 });
209
+ assert.equal(r3.deduped, false, "major rewrite should not be collapsed by L1");
210
+ assert.equal(s.list(SESS).length, 2);
211
+ });
212
+
213
+ it("L2 only: semantic paraphrases collapse; unrelated topics do not", () => {
214
+ // Use a lower threshold and longer, lexically-overlapping paraphrase so the
215
+ // deterministic trigram embedder reliably catches it while still distinguishing
216
+ // unrelated topics.
217
+ const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: true, L2_COSINE: 0.60 });
218
+
219
+ const original =
220
+ "user authentication and session token management login validation session expiry handling secure cookie";
221
+ const paraphrase =
222
+ "login validation session expiry handling secure cookie user authentication and session token management";
223
+ const unrelated = "the frontend added a dark mode toggle with css custom properties";
224
+
225
+ const r1 = s.add({ sessionId: SESS, summary: "auth", regionText: original, timestamp: 1 });
226
+ assert.equal(r1.deduped, false);
227
+
228
+ const r2 = s.add({ sessionId: SESS, summary: "auth paraphrase", regionText: paraphrase, timestamp: 2 });
229
+ assert.equal(r2.deduped, true, "semantic paraphrase should be collapsed by L2");
230
+ assert.equal(s.list(SESS).length, 1);
231
+
232
+ const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: unrelated, timestamp: 3 });
233
+ assert.equal(r3.deduped, false, "unrelated topic should not be collapsed by L2");
234
+ assert.equal(s.list(SESS).length, 2);
235
+ });
236
+
237
+ it("All tiers disabled: every store.add() with different region text creates a distinct checkpoint", () => {
238
+ // Even with all dedup tiers disabled, the store still enforces a unique
239
+ // content_hash constraint, so we vary the region text slightly for each add.
240
+ const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: false });
241
+
242
+ const r1 = s.add({ sessionId: SESS, summary: "a", regionText: "region alpha", timestamp: 1 });
243
+ const r2 = s.add({ sessionId: SESS, summary: "a", regionText: "region beta", timestamp: 2 });
244
+ const r3 = s.add({ sessionId: SESS, summary: "a", regionText: "region gamma", timestamp: 3 });
245
+
246
+ assert.equal(r1.deduped, false);
247
+ assert.equal(r2.deduped, false);
248
+ assert.equal(r3.deduped, false);
249
+ assert.notEqual(r1.checkpoint.checkpointId, r2.checkpoint.checkpointId);
250
+ assert.notEqual(r2.checkpoint.checkpointId, r3.checkpoint.checkpointId);
251
+ assert.equal(s.list(SESS).length, 3);
252
+ });
253
+
254
+ it("Combined L0+L1+L2: layered behavior exact -> near -> semantic", () => {
255
+ const s = makeStore({ L0_ENABLED: true, L1_ENABLED: true, L2_ENABLED: true });
256
+
257
+ // First checkpoint establishes baseline.
258
+ const original = "implement user authentication with session tokens and secure cookies";
259
+ const r1 = compactFull(s, SESS, [makeMsg("user", original)]);
260
+ assert.equal(r1.deduped, false);
261
+
262
+ // Exact duplicate -> L0.
263
+ const r2 = compactFull(s, SESS, [makeMsg("user", original)]);
264
+ assert.equal(r2.deduped, true);
265
+ okReason(r2.dedupReason, ["regionHash", "contentHash", "summaryHash"]);
266
+
267
+ // One-word edit -> L1 (if not caught by L0 first).
268
+ const near = "implement user authentication with session token and secure cookies";
269
+ const r3 = compactFull(s, SESS, [makeMsg("user", near)]);
270
+ if (r3.deduped) {
271
+ okReason(r3.dedupReason, ["l1MinHash", "contentSimilarity"]);
272
+ }
273
+
274
+ // Semantic paraphrase -> L2 (if distinct from above).
275
+ const para = "build login validation and session cookie security for users";
276
+ const r4 = compactFull(s, SESS, [makeMsg("user", para)]);
277
+ if (r4.deduped) {
278
+ okReason(r4.dedupReason, ["contentSimilarity", "l1MinHash"]);
279
+ }
280
+
281
+ assert.ok(s.list(SESS).length >= 1, "layered dedup keeps at least one checkpoint");
282
+ assert.ok(s.list(SESS).length <= 4, "layered dedup should not explode to many checkpoints");
283
+ });
284
+ });
285
+
286
+ function okReason(reason: string | undefined, expected: string[]): void {
287
+ assert.ok(
288
+ reason !== undefined && expected.includes(reason),
289
+ `expected dedupReason one of ${expected.join(", ")}, got ${reason}`,
290
+ );
291
+ }
292
+
293
+ // -------------------- 3. Compaction Ratios --------------------
294
+
295
+ describe("Compaction Ratios", () => {
296
+ const SESS = "sess_ratios";
297
+
298
+ for (const n of [10, 50, 100, 200, 400]) {
299
+ it(`${n} messages: extractive summary is smaller than input; strictly smaller when > 50`, () => {
300
+ const s = makeStore();
301
+ const messages = buildConversation(n, `feature work item ${n}`);
302
+ const inputTokens = estimateSessionTokens(messages);
303
+
304
+ const ext = extractiveSummarize(messages);
305
+ const outputTokens = ext.tokenEstimate;
306
+
307
+ console.log(
308
+ `[ratio] ${n} messages: input=${inputTokens} output=${outputTokens} ratio=${
309
+ inputTokens ? (outputTokens / inputTokens).toFixed(3) : "n/a"
310
+ }`,
311
+ );
312
+
313
+ assert.ok(
314
+ outputTokens <= inputTokens || inputTokens === 0,
315
+ "output should not exceed input",
316
+ );
317
+ if (n > 50) {
318
+ assert.ok(
319
+ outputTokens < inputTokens,
320
+ `expected output smaller than input for ${n} messages`,
321
+ );
322
+ }
323
+
324
+ // Also run through compactSession and verify a checkpoint exists.
325
+ const r = compactSession(
326
+ { sessionId: SESS, messages, keepFrom: messages.length, useExtractiveSummary: true },
327
+ s,
328
+ );
329
+ assert.equal(r.skipped, false);
330
+ assert.ok(r.checkpointId);
331
+ assert.ok(r.tokenEstimate <= inputTokens);
332
+ });
333
+ }
334
+ });
335
+
336
+ // -------------------- 4. Compression / Store Stats --------------------
337
+
338
+ describe("Compression / Store Stats", () => {
339
+ const SESS = "sess_stats";
340
+
341
+ it("stats reflect checkpoints, tokens, injection and dedup hit rate", () => {
342
+ const s = makeStore();
343
+
344
+ // Mixed duplicate and unique stores.
345
+ const unique = "unique topic about payment gateway integration";
346
+ compactFull(s, SESS, [makeMsg("user", unique)], 1);
347
+
348
+ const dup = "duplicate topic about payment gateway integration";
349
+ compactFull(s, SESS, [makeMsg("user", dup)], 1);
350
+
351
+ const statsBefore = s.stats(SESS);
352
+ assert.ok(statsBefore.checkpointCount >= 1, "checkpointCount should be positive");
353
+ assert.ok(statsBefore.totalTokenEstimate >= 0, "totalTokenEstimate should be non-negative");
354
+ assert.equal(statsBefore.dedupHitRate, 0, "no injections yet => dedupHitRate 0");
355
+ assert.equal(statsBefore.injectedCount, 0, "no injections yet => injectedCount 0");
356
+
357
+ const hits = s.search(SESS, "payment gateway", 5);
358
+ assert.ok(hits.length > 0, "should find the stored checkpoint");
359
+ const cpId = hits[0].checkpoint.checkpointId;
360
+
361
+ s.markInjected(SESS, cpId);
362
+ const statsAfter = s.stats(SESS);
363
+ assert.equal(statsAfter.injectedCount, 1, "injectedCount tracks markInjected");
364
+ if (statsAfter.checkpointCount > 0) {
365
+ assert.ok(
366
+ Math.abs(statsAfter.dedupHitRate - 1 / statsAfter.checkpointCount) < 0.001,
367
+ "dedupHitRate = injected / checkpoints",
368
+ );
369
+ }
370
+ assert.ok(statsAfter.totalTokenEstimate > 0, "totalTokenEstimate positive after inserts");
371
+ });
372
+
373
+ it("dedupHitRate increases with duplicate content", () => {
374
+ const s = makeStore();
375
+ const base = "repeated region for hit-rate measurement";
376
+
377
+ // Insert several duplicates; only first survives.
378
+ for (let i = 0; i < 5; i++) {
379
+ compactFull(s, SESS, [makeMsg("user", base)], 1);
380
+ }
381
+ compactFull(s, SESS, [makeMsg("user", "unique region for hit-rate measurement variant")], 1);
382
+
383
+ // Mark the first as injected.
384
+ const first = s.search(SESS, base, 1)[0]?.checkpoint.checkpointId;
385
+ if (first) s.markInjected(SESS, first);
386
+
387
+ const stats = s.stats(SESS);
388
+ assert.ok(stats.checkpointCount >= 1);
389
+ assert.ok(
390
+ stats.dedupHitRate > 0 || stats.checkpointCount === 1,
391
+ "hit rate should be positive when there are multiple checkpoint",
392
+ );
393
+ });
394
+ });
395
+
396
+ // -------------------- 5. Recall & Dedup Sentinel --------------------
397
+
398
+ describe("Recall & Dedup Sentinel", () => {
399
+ const SESS = "sess_recall";
400
+
401
+ it("recallAndInline returns toInject on first call and empty on second due to skipInjected", () => {
402
+ const s = makeStore();
403
+ const region = "detailed work on the vector store dedup sentinel and recall pipeline";
404
+ compactFull(s, SESS, [makeMsg("user", region)]);
405
+
406
+ assert.ok(
407
+ recallAndInline,
408
+ "recallAndInline should be exported from recall.js for this test",
409
+ );
410
+
411
+ const r1 = recallAndInline!(
412
+ {
413
+ sessionId: SESS,
414
+ query: "dedup sentinel recall",
415
+ limit: 3,
416
+ source: "command",
417
+ skipInjected: true,
418
+ },
419
+ s,
420
+ );
421
+ assert.ok(r1.toInject.length > 0, "first recall should return hits to inject");
422
+
423
+ const r2 = recallAndInline!(
424
+ {
425
+ sessionId: SESS,
426
+ query: "dedup sentinel recall",
427
+ limit: 3,
428
+ source: "command",
429
+ skipInjected: true,
430
+ },
431
+ s,
432
+ );
433
+ assert.ok(r2.empty, "second recall should be empty because sentinel marked injected");
434
+ });
435
+
436
+ it("manual markInjected creates skip behavior when recallAndInline is unavailable", () => {
437
+ const s = makeStore();
438
+ const region = "manual sentinel tracking without recallAndInline";
439
+ compactFull(s, SESS, [makeMsg("user", region)]);
440
+
441
+ const hits = s.search(SESS, "manual sentinel", 3);
442
+ assert.ok(hits.length > 0, "search should return checkpoint");
443
+ const cpId = hits[0].checkpoint.checkpointId;
444
+ assert.equal(s.wasInjected(SESS, cpId), false, "not yet injected");
445
+
446
+ s.markInjected(SESS, cpId);
447
+ assert.equal(s.wasInjected(SESS, cpId), true, "markInjected recorded");
448
+
449
+ const hits2 = s.search(SESS, "manual sentinel", 3).filter(
450
+ (h) => !s.wasInjected(SESS, h.checkpoint.checkpointId),
451
+ );
452
+ assert.equal(hits2.length, 0, "filtered search excludes injected checkpoint");
453
+ });
454
+ });
455
+
456
+ // -------------------- 6. Edge Cases --------------------
457
+
458
+ describe("Edge Cases", () => {
459
+ const SESS = "sess_edge";
460
+
461
+ it("empty message list returns skipped", () => {
462
+ const s = makeStore();
463
+ const r = compactSession({ sessionId: SESS, messages: [], keepFrom: 0 }, s);
464
+ assert.equal(r.skipped, true);
465
+ assert.equal(r.summary, "");
466
+ assert.equal(s.list(SESS).length, 0);
467
+ });
468
+
469
+ it("single message with keepFrom=0 returns skipped", () => {
470
+ const s = makeStore();
471
+ const r = compactSession(
472
+ { sessionId: SESS, messages: [makeMsg("user", "only one message")], keepFrom: 0 },
473
+ s,
474
+ );
475
+ assert.equal(r.skipped, true);
476
+ assert.equal(s.list(SESS).length, 0);
477
+ });
478
+
479
+ it("keepFrom at messages.length compacts all prior messages (verified behavior)", () => {
480
+ // The engine treats keepFrom as the compactable boundary: messages[0..keepFrom)
481
+ // are compacted. When keepFrom equals messages.length the entire conversation is
482
+ // compactable, so it is NOT skipped. This test documents that behavior.
483
+ const s = makeStore();
484
+ const messages = buildConversation(6);
485
+ const r = compactSession({ sessionId: SESS, messages, keepFrom: messages.length }, s);
486
+ assert.equal(r.skipped, false);
487
+ assert.ok(r.checkpointId);
488
+ assert.equal(s.list(SESS).length, 1);
489
+ });
490
+
491
+ it("unicode and emoji messages store and retrieve intact", () => {
492
+ const s = makeStore();
493
+ const text =
494
+ "用户请求:创建 🎉 庆祝页面,包含 café 菜单 — déjà vu! " +
495
+ "日本語テキスト 日本語テキスト 👍🔥";
496
+ const r = compactFull(s, SESS, [makeMsg("user", text)], 1);
497
+ assert.equal(r.skipped, false);
498
+ const stored = s.list(SESS)[0];
499
+ assert.ok(stored);
500
+ const recovered = Buffer.from(stored.compressedOriginal ?? Buffer.alloc(0));
501
+ assert.ok(
502
+ recovered.toString("utf-8").includes("🎉"),
503
+ "emoji recovered from compressedOriginal",
504
+ );
505
+ assert.ok(stored.summary.includes("café") || stored.summary.includes("cafe"));
506
+ });
507
+
508
+ it("very large single message (>10k chars) compacts and stores successfully", () => {
509
+ const s = makeStore();
510
+ const big = "bigint ".repeat(2000);
511
+ assert.ok(big.length > 10_000, `message length ${big.length}`);
512
+ const r = compactFull(s, SESS, [makeMsg("user", big)], 1);
513
+ assert.equal(r.skipped, false);
514
+ assert.ok(r.checkpointId);
515
+ assert.equal(s.list(SESS).length, 1);
516
+ const stats = s.stats(SESS);
517
+ assert.ok(stats.totalTokenEstimate > 0);
518
+ });
519
+
520
+ it("mixed roles (user/assistant/tool) are included in summary", () => {
521
+ const s = makeStore();
522
+ const messages: EngineMessage[] = [
523
+ { role: "user", text: "fix the bug" },
524
+ { role: "assistant", text: "will do", toolName: "Read", input: "src/bug.ts" },
525
+ { role: "tool", text: "", toolName: "Read", output: "function foo() {}" },
526
+ { role: "assistant", text: "fixed it", toolName: "Edit" },
527
+ ];
528
+ const r = compactFull(s, SESS, messages, messages.length);
529
+ assert.equal(r.skipped, false);
530
+ assert.ok(r.summary.length > 0);
531
+ assert.ok(
532
+ r.summary.includes("tool") ||
533
+ r.summary.includes("Read") ||
534
+ r.summary.includes("Edit") ||
535
+ r.summary.includes("user") ||
536
+ r.summary.includes("assistant"),
537
+ "summary should reference roles or tools",
538
+ );
539
+ assert.equal(s.list(SESS).length, 1);
540
+ });
541
+ });
542
+
543
+ // -------------------- 7. Tier Switching --------------------
544
+
545
+ describe("Tier Switching", () => {
546
+ it("MEGACOMPACT_TIER env changes produce expected thresholds via extension logic", () => {
547
+ const tiers: Array<[string, number]> = [
548
+ ["low", 50_000],
549
+ ["medium", 100_000],
550
+ ["high", 200_000],
551
+ ["ultra", 1_000_000],
552
+ ["mega", 10_000_000],
553
+ ];
554
+
555
+ for (const [tier, expectedThreshold] of tiers) {
556
+ const original = process.env.MEGACOMPACT_TIER;
557
+ process.env.MEGACOMPACT_TIER = tier;
558
+ try {
559
+ // Re-import to pick up env change. Since modules are cached, resolve threshold
560
+ // directly via COMPACT_TIERS local replica mirroring extensions/mega-compact.ts.
561
+ const threshold = resolveThresholdFromEnv();
562
+ assert.equal(
563
+ threshold,
564
+ expectedThreshold,
565
+ `tier ${tier} should resolve to ${expectedThreshold}`,
566
+ );
567
+ } finally {
568
+ if (original === undefined) {
569
+ delete process.env.MEGACOMPACT_TIER;
570
+ } else {
571
+ process.env.MEGACOMPACT_TIER = original;
572
+ }
573
+ }
574
+ }
575
+ });
576
+
577
+ it("explicit MEGACOMPACT_THRESHOLD_TOKENS overrides tier", () => {
578
+ const originalTier = process.env.MEGACOMPACT_TIER;
579
+ const originalThreshold = process.env.MEGACOMPACT_THRESHOLD_TOKENS;
580
+ process.env.MEGACOMPACT_TIER = "mega";
581
+ process.env.MEGACOMPACT_THRESHOLD_TOKENS = "123456";
582
+ try {
583
+ const threshold = resolveThresholdFromEnv();
584
+ assert.equal(threshold, 123_456, "explicit token threshold should win");
585
+ } finally {
586
+ if (originalTier === undefined) delete process.env.MEGACOMPACT_TIER;
587
+ else process.env.MEGACOMPACT_TIER = originalTier;
588
+ if (originalThreshold === undefined) delete process.env.MEGACOMPACT_THRESHOLD_TOKENS;
589
+ else process.env.MEGACOMPACT_THRESHOLD_TOKENS = originalThreshold;
590
+ }
591
+ });
592
+ });
593
+
594
+ function resolveThresholdFromEnv(): number {
595
+ const explicit = process.env.MEGACOMPACT_THRESHOLD_TOKENS;
596
+ if (explicit != null && explicit !== "") {
597
+ const n = Number(explicit);
598
+ if (Number.isFinite(n)) return n;
599
+ }
600
+ const COMPACT_TIERS: Record<string, number> = {
601
+ low: 50_000,
602
+ medium: 100_000,
603
+ high: 200_000,
604
+ ultra: 1_000_000,
605
+ mega: 10_000_000,
606
+ };
607
+ const tier = process.env.MEGACOMPACT_TIER ?? "low";
608
+ return COMPACT_TIERS[tier.toLowerCase()] ?? COMPACT_TIERS.low;
609
+ }