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,544 @@
1
+ /**
2
+ * vectorStore.ts — Layer 3 (CLUSTER): the local vector database.
3
+ *
4
+ * One store, three consumers (per PLAN.md): auto-inline on resume, on-demand
5
+ * /recall-context, and the dedup sentinel. All share `add / search / dedupe`.
6
+ *
7
+ * Backed by the gzipped on-disk checkpoint files (store.ts). Similarity is a
8
+ * linear cosine scan — checkpoint counts are small, so no ANN index is needed.
9
+ */
10
+
11
+ import { createHash } from "node:crypto";
12
+ import type { Embedder, Vector } from "./embedder.js";
13
+ import { cosineSimilarity, defaultEmbedder } from "./embedder.js";
14
+ import { loadDedupConfig, type DedupConfigShape, type DedupTier } from "./config/dedup.js";
15
+ import { logDecision } from "./monitoring.js";
16
+ import type { StoredCheckpoint, SessionState } from "./store.js";
17
+ import { getStateDir, normalizeSessionId, compressSmart, loadDedupStats, saveDedupStats } from "./store.js";
18
+ import { computeContentDigest } from "./dedup/digest.js";
19
+ import { minhashSignature, SIGNATURE_VERSION, NUM_HASHES } from "./dedup/l1-minhash.js";
20
+ import { lshBands } from "./dedup/l1-lsh.js";
21
+ import { isNearDuplicate } from "./dedup/l1-verify.js";
22
+ import { mmrRerank, type MmrItem } from "./dedup/mmr.js";
23
+ import { topK } from "./dedup/topk.js";
24
+ import { openBloom, saveBloom } from "./store/bloom.js";
25
+ import {
26
+ listCheckpoints,
27
+ nextCheckpointId,
28
+ upsertCheckpoint,
29
+ loadSessionState,
30
+ saveSessionState,
31
+ upsertMinhashSignature,
32
+ insertLshBuckets,
33
+ lshCandidateChunks,
34
+ setDedupStatus,
35
+ } from "./store/sqlite.js";
36
+ import { migrateJsonToSqlite } from "./store/migrate.js";
37
+
38
+ export interface SearchHit {
39
+ checkpoint: StoredCheckpoint;
40
+ score: number;
41
+ }
42
+
43
+ export interface AddInput {
44
+ sessionId: string;
45
+ summary: string;
46
+ /** Compressed topic summary (extractive). When present, embedded instead of regionText. */
47
+ topicSummary?: string;
48
+ keyDecisions?: string[];
49
+ nextSteps?: string[];
50
+ filesModified?: string[];
51
+ tokenEstimate?: number;
52
+ /** Raw text of the compacted region — used to derive the regionHash + vector. */
53
+ regionText: string;
54
+ timestamp: number;
55
+ }
56
+
57
+ /** Default L2 semantic-dedup enable flag (trigram embedder is local, zero-network). */
58
+ export const L2_ENABLED = true;
59
+
60
+ export interface AddResult {
61
+ checkpoint: StoredCheckpoint;
62
+ deduped: boolean; // true when an equivalent region already existed (skipped embed)
63
+ /** Which dedup tier matched: regionHash | summaryHash | contentSimilarity | undefined (new). */
64
+ reason?: string;
65
+ }
66
+
67
+ /** Stable hash of a compacted region, the dedup sentinel key. */
68
+ export function computeRegionHash(regionText: string): string {
69
+ // Normalize whitespace before hashing so "foo bar" and "foo bar" dedup.
70
+ const normalized = regionText.replace(/\s+/g, " ").trim();
71
+ return createHash("sha256").update(normalized).digest("hex").slice(0, 16);
72
+ }
73
+
74
+ export class VectorStore {
75
+ private readonly embedder: Embedder;
76
+ private readonly stateDir: string;
77
+ private readonly l2Threshold: number;
78
+ /** Single source of truth for tier flags + thresholds (Sprint 14). */
79
+ private readonly cfg: DedupConfigShape;
80
+ /** Optional monitoring target (Sprint 14). Undefined → no monitoring. */
81
+ private readonly eventsPath?: string;
82
+
83
+ constructor(
84
+ opts: {
85
+ embedder?: Embedder;
86
+ dedupSim?: number;
87
+ stateDir?: string;
88
+ l2Enabled?: boolean;
89
+ l2Threshold?: number;
90
+ /** Override the dedup config (defaults to env/file snapshot). */
91
+ config?: DedupConfigShape;
92
+ /** Optional events.log path for decision monitoring (Sprint 14). */
93
+ eventsPath?: string;
94
+ } = {},
95
+ ) {
96
+ this.embedder = opts.embedder ?? defaultEmbedder();
97
+ this.stateDir = opts.stateDir ?? getStateDir();
98
+ // Sprint 14: all tier flags/thresholds flow from the single config source
99
+ // (DedupConfig). The legacy opts.dedupSim / opts.l2Enabled remain accepted
100
+ // for backward-compat callers but flags are authoritative via `cfg`.
101
+ void opts.dedupSim;
102
+ void opts.l2Enabled;
103
+ // Sprint 12 L2 semantic tier. Threshold 0.85 is the default trigram
104
+ // embedder's honest firing point; a direct override is allowed for tests.
105
+ this.cfg = opts.config ?? loadDedupConfig();
106
+ this.l2Threshold = opts.l2Threshold ?? this.cfg.L2_COSINE;
107
+ this.eventsPath = opts.eventsPath;
108
+ // Sprint 8: bring any v0.1.0 JSON checkpoint files into SQLite (idempotent).
109
+ migrateJsonToSqlite(this.stateDir);
110
+ // Sprint 10: warm the bloom accelerator (accelerator only — SQLite stays
111
+ // source of truth; a bloom hit is always confirmed by a query below).
112
+ openBloom(this.stateDir);
113
+ }
114
+
115
+ /** Emit a structured dedup-decision event (best-effort, never throws). */
116
+ private record(tier: DedupTier, result: "deduped" | "new" | "mark_only", reason: string | undefined, latencyMs: number): void {
117
+ if (!this.eventsPath) return;
118
+ logDecision(this.eventsPath, {
119
+ ts: Date.now(),
120
+ tier,
121
+ result,
122
+ reason,
123
+ latencyMs: Math.round(latencyMs * 100) / 100,
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Add a checkpoint. Dedup cascade:
129
+ * 1. regionHash exact match (legacy, backward-compat)
130
+ * 2. summaryHash exact match (new: catches same-topic incremental compactions)
131
+ * 3. content similarity ≥ dedupSim (catches near-identical summaries)
132
+ * 4. If none match → create new checkpoint
133
+ */
134
+ add(input: AddInput): AddResult {
135
+ const t0 = Date.now();
136
+ const sessionId = normalizeSessionId(input.sessionId);
137
+ const regionHash = computeRegionHash(input.regionText);
138
+ const all = listCheckpoints(sessionId, this.stateDir);
139
+ const cfg = this.cfg;
140
+ // Cumulative store-wide dedup accounting (survives session resets).
141
+ const ds = loadDedupStats(this.stateDir);
142
+ ds.attempts++;
143
+ // Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
144
+ // and which tier.
145
+ let markOnly: DedupTier | null = null;
146
+
147
+ // 0. L0 content-hash dedup (Sprint 9) — catches identical content arriving
148
+ // under different regionText. Normalization handles case/whitespace/ANSI so
149
+ // variants collapse to one row. Dual-hash guards a single-hash collision.
150
+ // Sprint 10: bloom is the accelerator — a miss means "definitely new" and
151
+ // skips the scan; a hit is only a candidate, confirmed against `all` below.
152
+ // Gated by L0_ENABLED (Sprint 14). MARK_ONLY_L0 records the decision but
153
+ // does not collapse — the new region is still stored.
154
+ const digest = computeContentDigest(input.regionText);
155
+ const bloom = openBloom(this.stateDir);
156
+ if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
157
+ const contentMatch = all.find(
158
+ (cp) =>
159
+ cp.contentHash === digest.contentHash &&
160
+ cp.contentHash2 === digest.contentHash2,
161
+ );
162
+ if (contentMatch) {
163
+ if (cfg.MARK_ONLY_L0) {
164
+ markOnly = "L0"; // Record-but-don't-collapse: fall through.
165
+ } else {
166
+ contentMatch.timestamp = input.timestamp;
167
+ upsertCheckpoint(contentMatch, this.stateDir);
168
+ ds.deduped++;
169
+ saveDedupStats(ds, this.stateDir);
170
+ const r = { checkpoint: contentMatch, deduped: true, reason: "contentHash" };
171
+ this.record("L0", "deduped", "contentHash", Date.now() - t0);
172
+ return r;
173
+ }
174
+ }
175
+ }
176
+
177
+ // 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
178
+ if (cfg.L0_ENABLED) {
179
+ const regionMatch = all.find((cp) => cp.regionHash === regionHash);
180
+ if (regionMatch) {
181
+ if (cfg.MARK_ONLY_L0) {
182
+ markOnly = "L0"; // fall through
183
+ } else {
184
+ ds.deduped++;
185
+ saveDedupStats(ds, this.stateDir);
186
+ const r = { checkpoint: regionMatch, deduped: true, reason: "regionHash" };
187
+ this.record("L0", "deduped", "regionHash", Date.now() - t0);
188
+ return r;
189
+ }
190
+ }
191
+ }
192
+
193
+ // 2. SummaryHash dedup — catches same-topic incremental compactions.
194
+ // Full 64-hex SHA-256 (was 16-hex in Sprint 8 — collision-prone).
195
+ const summaryHash = input.topicSummary
196
+ ? createHash("sha256").update(input.topicSummary).digest("hex")
197
+ : undefined;
198
+ if (summaryHash && cfg.L0_ENABLED) {
199
+ const summaryMatch = all.find((cp) => cp.summaryHash === summaryHash);
200
+ if (summaryMatch) {
201
+ if (cfg.MARK_ONLY_L0) {
202
+ markOnly = "L0"; // fall through
203
+ } else {
204
+ summaryMatch.timestamp = input.timestamp;
205
+ upsertCheckpoint(summaryMatch, this.stateDir);
206
+ ds.deduped++;
207
+ saveDedupStats(ds, this.stateDir);
208
+ const r = { checkpoint: summaryMatch, deduped: true, reason: "summaryHash" };
209
+ this.record("L0", "deduped", "summaryHash", Date.now() - t0);
210
+ return r;
211
+ }
212
+ }
213
+ }
214
+
215
+ // 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
216
+ // edits / rewordings that L0's exact hash misses. Cheap LSH bucket
217
+ // retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
218
+ // Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
219
+ if (cfg.L1_ENABLED) {
220
+ const l1 = this.findL1Duplicate(sessionId, input.regionText, all);
221
+ if (l1 && !cfg.MARK_ONLY_L1) {
222
+ l1.timestamp = input.timestamp;
223
+ upsertCheckpoint(l1, this.stateDir);
224
+ ds.deduped++;
225
+ saveDedupStats(ds, this.stateDir);
226
+ const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
227
+ this.record("L1", "deduped", "l1MinHash", Date.now() - t0);
228
+ return r;
229
+ }
230
+ if (l1 && cfg.MARK_ONLY_L1) markOnly = "L1";
231
+ }
232
+
233
+ // 3. L2 semantic dedup — catches near-identical / semantically-similar regions
234
+ // via cosine over the embedding. topicSummary is used for summaryHash dedup
235
+ // (tier 2); the vector index is keyed on the original region for backward-
236
+ // compat search semantics. Threshold from cfg (L2_COSINE trigram honest
237
+ // firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
238
+ // degrade to "store without dedup this pass" so we never lose a checkpoint.
239
+ // Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
240
+ const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
241
+ const simThreshold = this.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
242
+ const embedding = this.embedder.embed(input.regionText);
243
+ if (cfg.L2_ENABLED && all.length > 0) {
244
+ const start = Date.now();
245
+ let timedOut = false;
246
+ const nearest = all.reduce(
247
+ (best, cp) => {
248
+ if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS) timedOut = true;
249
+ if (timedOut) return best;
250
+ const sim = cosineSimilarity(embedding, cp.embedding);
251
+ return sim > best.sim ? { checkpoint: cp, sim } : best;
252
+ },
253
+ { checkpoint: all[0], sim: -1 },
254
+ );
255
+ if (!timedOut && nearest.sim >= simThreshold) {
256
+ if (!cfg.MARK_ONLY_L2) {
257
+ // Near-identical — update timestamp on existing checkpoint
258
+ nearest.checkpoint.timestamp = input.timestamp;
259
+ upsertCheckpoint(nearest.checkpoint, this.stateDir);
260
+ ds.deduped++;
261
+ saveDedupStats(ds, this.stateDir);
262
+ const r = { checkpoint: nearest.checkpoint, deduped: true, reason: "contentSimilarity" };
263
+ this.record("L2", "deduped", "contentSimilarity", Date.now() - t0);
264
+ return r;
265
+ }
266
+ markOnly = "L2";
267
+ }
268
+ }
269
+
270
+ // 4. Genuinely new — create checkpoint
271
+ const checkpointId = nextCheckpointId(sessionId, this.stateDir);
272
+ const checkpoint: StoredCheckpoint = {
273
+ checkpointId,
274
+ sessionId,
275
+ summary: input.summary,
276
+ topicSummary: input.topicSummary,
277
+ summaryHash,
278
+ keyDecisions: input.keyDecisions ?? [],
279
+ nextSteps: input.nextSteps ?? [],
280
+ filesModified: input.filesModified ?? [],
281
+ tokenEstimate: input.tokenEstimate ?? 0,
282
+ regionHash,
283
+ contentHash: digest.contentHash,
284
+ contentHash2: digest.contentHash2,
285
+ contentHashVersion: digest.contentHashVersion,
286
+ normalizedText: digest.normalizedText,
287
+ compressedOriginal: compressSmart(Buffer.from(input.regionText, "utf-8")),
288
+ embedding,
289
+ timestamp: input.timestamp,
290
+ };
291
+ // Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
292
+ // idempotent-by-id semantics the old JSON append implied.
293
+ upsertCheckpoint(checkpoint, this.stateDir);
294
+ // L1: persist this checkpoint's MinHash signature + LSH buckets so future
295
+ // near-duplicate inserts can find it. Deterministic given the seed.
296
+ const sig = minhashSignature(input.regionText);
297
+ upsertMinhashSignature(checkpointId, sessionId, SIGNATURE_VERSION, sig, this.stateDir);
298
+ insertLshBuckets(
299
+ checkpointId,
300
+ sessionId,
301
+ SIGNATURE_VERSION,
302
+ lshBands(sig, sessionId, SIGNATURE_VERSION),
303
+ this.stateDir,
304
+ );
305
+ // Bloom accelerator: record the new content_hash so a future add() can short-
306
+ // circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
307
+ bloom.add(digest.contentHash);
308
+ saveBloom(this.stateDir);
309
+
310
+ // Track the region hash in session state for fast sentinel checks.
311
+ const state = loadSessionState(sessionId, this.stateDir);
312
+ if (!state.storedRegionHashes.includes(regionHash)) {
313
+ state.storedRegionHashes.push(regionHash);
314
+ saveSessionState(sessionId, state, this.stateDir);
315
+ }
316
+ // A new checkpoint. If a tier matched while MARK_ONLY, record that (the
317
+ // decision fired but we intentionally did not collapse).
318
+ if (markOnly) {
319
+ this.record(markOnly, "mark_only", "mark_only", Date.now() - t0);
320
+ } else {
321
+ this.record("L0", "new", undefined, Date.now() - t0);
322
+ }
323
+ saveDedupStats(ds, this.stateDir);
324
+ return { checkpoint, deduped: false };
325
+ }
326
+
327
+ /**
328
+ * L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
329
+ * Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
330
+ * and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
331
+ */
332
+ private findL1Duplicate(
333
+ sessionId: string,
334
+ regionText: string,
335
+ all: StoredCheckpoint[],
336
+ ): StoredCheckpoint | undefined {
337
+ if (all.length === 0) return undefined;
338
+ const sig = minhashSignature(regionText);
339
+ if (sig.length !== NUM_HASHES) return undefined;
340
+ const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
341
+ // Cheap candidate retrieval (single query, capped). Exclude nothing yet —
342
+ // the new checkpoint has no id, so pass a sentinel that never matches.
343
+ const candidateIds = lshCandidateChunks(
344
+ bands,
345
+ sessionId,
346
+ "__new__",
347
+ this.stateDir,
348
+ 100,
349
+ );
350
+ if (candidateIds.length === 0) return undefined;
351
+ const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
352
+ const VERIFY_BUDGET_MS = 20;
353
+ const start = Date.now();
354
+ for (const id of candidateIds) {
355
+ if (Date.now() - start > VERIFY_BUDGET_MS) break; // QA #15: abort → "not dup"
356
+ const cand = byId.get(id);
357
+ if (!cand) continue;
358
+ const candText = cand.normalizedText ?? cand.summary ?? "";
359
+ if (isNearDuplicate(regionText, candText)) return cand;
360
+ }
361
+ return undefined;
362
+ }
363
+
364
+ /**
365
+ * Semantic search within a session's checkpoints. Returns top-K by cosine
366
+ * similarity, diversified via MMR (QA #10) so a cluster of near-identical
367
+ * hits yields at most a few distinct-relevance results.
368
+ *
369
+ * Heap-based top-K (QA #4, O(N log k)) replaces the old full sort; MMR then
370
+ * reranks the candidate window for diversity.
371
+ */
372
+ search(sessionId: string, query: string, k = 3): SearchHit[] {
373
+ const sid = normalizeSessionId(sessionId);
374
+ const checkpoints = listCheckpoints(sid, this.stateDir).filter(
375
+ (cp) => cp.dedupStatus !== "removed", // SemDeDup: exclude removed rows
376
+ );
377
+ if (checkpoints.length === 0) return [];
378
+ const qv = this.embedder.embed(query);
379
+
380
+ const scored: SearchHit[] = checkpoints.map((cp) => ({
381
+ checkpoint: cp,
382
+ score: cosineSimilarity(qv, cp.embedding),
383
+ }));
384
+
385
+ // Heap top-K over a widened window (2k) so MMR has diverse candidates.
386
+ const window = topK(
387
+ scored.map((h) => ({ item: h, score: h.score })),
388
+ Math.max(k * 2, k),
389
+ ).map((s) => s.item);
390
+ // MMR (QA #10) is part of the L2 semantic tier: skip it when L2 is disabled
391
+ // (Sprint 14 flag), returning the plain relevance-ranked window instead.
392
+ if (!this.cfg.L2_ENABLED) return window.slice(0, k);
393
+ const mmrItems: MmrItem<SearchHit>[] = window.map((h) => ({
394
+ item: h,
395
+ vector: h.checkpoint.embedding,
396
+ relevance: h.score,
397
+ }));
398
+ const ranked = mmrRerank(mmrItems, k, this.cfg.MMR_LAMBDA);
399
+ return ranked;
400
+ }
401
+
402
+ /**
403
+ * SemDeDup offline cleanup (Sprint 12, QA #17): within a session, mark the
404
+ * lower-quality row of any pair scoring cosine > `threshold` as
405
+ * `dedup_status='removed'` (kept, not deleted — retrieval excludes it). Keeps
406
+ * the row with the higher `tokenEstimate` (more context preserved). Runs as a
407
+ * single scan; idempotent (re-running skips already-removed rows).
408
+ *
409
+ * Returns the number of rows marked removed.
410
+ */
411
+ semDedup(sessionId: string, threshold = this.cfg.SEMDEDUP_COSINE): number {
412
+ const sid = normalizeSessionId(sessionId);
413
+ const cps = listCheckpoints(sid, this.stateDir).filter(
414
+ (c) => c.dedupStatus !== "removed",
415
+ );
416
+ let removed = 0;
417
+ for (let i = 0; i < cps.length; i++) {
418
+ for (let j = i + 1; j < cps.length; j++) {
419
+ const a = cps[i];
420
+ const b = cps[j];
421
+ if (a.dedupStatus === "removed" || b.dedupStatus === "removed") continue;
422
+ if (cosineSimilarity(a.embedding, b.embedding) > threshold) {
423
+ // Keep the higher-tokenEstimate row; remove the other.
424
+ const keep = a.tokenEstimate >= b.tokenEstimate ? a : b;
425
+ const drop = keep === a ? b : a;
426
+ setDedupStatus(drop.checkpointId, sid, "removed", this.stateDir);
427
+ drop.dedupStatus = "removed";
428
+ removed++;
429
+ }
430
+ }
431
+ }
432
+ return removed;
433
+ }
434
+
435
+ /**
436
+ * Dedup sentinel check: has this region already been stored/represented?
437
+ * Consulted by both the persist path and the recall/inline path.
438
+ */
439
+ dedupe(sessionId: string, regionHashOrText: string, isText = false): boolean {
440
+ const sid = normalizeSessionId(sessionId);
441
+ const hash = isText
442
+ ? computeRegionHash(regionHashOrText)
443
+ : regionHashOrText;
444
+ const state = loadSessionState(sid, this.stateDir);
445
+ if (state.storedRegionHashes.includes(hash)) return true;
446
+ return listCheckpoints(sid, this.stateDir).some(
447
+ (c) => c.regionHash === hash,
448
+ );
449
+ }
450
+
451
+ /** Mark a checkpoint as injected into the window (recall dedup). */
452
+ markInjected(sessionId: string, checkpointId: string): void {
453
+ const sid = normalizeSessionId(sessionId);
454
+ const state = loadSessionState(sid, this.stateDir);
455
+ if (!state.injectedCheckpointIds.includes(checkpointId)) {
456
+ state.injectedCheckpointIds.push(checkpointId);
457
+ saveSessionState(sid, state, this.stateDir);
458
+ }
459
+ }
460
+
461
+ /** True if this checkpoint was already injected this session. */
462
+ wasInjected(sessionId: string, checkpointId: string): boolean {
463
+ const state: SessionState = loadSessionState(
464
+ normalizeSessionId(sessionId),
465
+ this.stateDir,
466
+ );
467
+ return state.injectedCheckpointIds.includes(checkpointId);
468
+ }
469
+
470
+ /** Convenience for a raw vector cosine (exposed for tests). */
471
+ similarity(a: Vector, b: Vector): number {
472
+ return cosineSimilarity(a, b);
473
+ }
474
+
475
+ /** All checkpoints for a session (sorted by checkpointId). */
476
+ list(sessionId: string): StoredCheckpoint[] {
477
+ return listCheckpoints(normalizeSessionId(sessionId), this.stateDir);
478
+ }
479
+
480
+ /**
481
+ * Return the n most similar checkpoints to the current (most recent) checkpoint
482
+ * by cosine similarity. Returns fewer than n if the session has fewer checkpoints.
483
+ * The current checkpoint itself is excluded from results.
484
+ */
485
+ topSimilar(sessionId: string, n: number): SearchHit[] {
486
+ const sid = normalizeSessionId(sessionId);
487
+ const checkpoints = listCheckpoints(sid, this.stateDir);
488
+ if (checkpoints.length <= 1) return [];
489
+
490
+ // Find the most recent checkpoint (by checkpointId, which is sequential)
491
+ const ordered = [...checkpoints].sort((a, b) =>
492
+ a.checkpointId.localeCompare(b.checkpointId),
493
+ );
494
+ const current = ordered[ordered.length - 1];
495
+
496
+ // Score all other checkpoints by similarity to current
497
+ const scored: SearchHit[] = ordered
498
+ .filter((cp) => cp.checkpointId !== current.checkpointId)
499
+ .map((cp) => ({
500
+ checkpoint: cp,
501
+ score: cosineSimilarity(current.embedding, cp.embedding),
502
+ }))
503
+ .sort((a, b) => b.score - a.score);
504
+
505
+ return scored.slice(0, n);
506
+ }
507
+
508
+ /**
509
+ * Store statistics for status reporting / logging. Returns counts + the last
510
+ * (highest-numbered) checkpoint, or nulls when the session is empty.
511
+ */
512
+ stats(sessionId: string): {
513
+ checkpointCount: number;
514
+ totalTokenEstimate: number;
515
+ lastCheckpointId: string | undefined;
516
+ lastSummary: string | undefined;
517
+ injectedCount: number;
518
+ dedupHitRate: number; // injected / checkpoints, 0..1
519
+ storageDedupRate: number; // deduped adds / total adds, 0..1 (cumulative)
520
+ dedupAttempts: number; // cumulative add() calls (store-wide)
521
+ dedupCollapsed: number; // cumulative deduped collapses (store-wide)
522
+ } {
523
+ const sid = normalizeSessionId(sessionId);
524
+ const cps = listCheckpoints(sid, this.stateDir);
525
+ const state = loadSessionState(sid, this.stateDir);
526
+ const ordered = [...cps].sort((a, b) =>
527
+ a.checkpointId.localeCompare(b.checkpointId),
528
+ );
529
+ const last = ordered[ordered.length - 1];
530
+ const injected = state.injectedCheckpointIds.length;
531
+ const ds = loadDedupStats(this.stateDir);
532
+ return {
533
+ checkpointCount: cps.length,
534
+ totalTokenEstimate: cps.reduce((s, c) => s + (c.tokenEstimate ?? 0), 0),
535
+ lastCheckpointId: last?.checkpointId,
536
+ lastSummary: last?.summary,
537
+ injectedCount: injected,
538
+ dedupHitRate: cps.length === 0 ? 0 : injected / cps.length,
539
+ storageDedupRate: ds.attempts === 0 ? 0 : ds.deduped / ds.attempts,
540
+ dedupAttempts: ds.attempts,
541
+ dedupCollapsed: ds.deduped,
542
+ };
543
+ }
544
+ }