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
@@ -11,431 +11,492 @@
11
11
  import { createHash } from "node:crypto";
12
12
  import type { Embedder } from "./embedder.js";
13
13
  import { cosineSimilarity, defaultEmbedder } from "./embedder.js";
14
- import { loadDedupConfig, type DedupConfigShape, type DedupTier } from "./config/dedup.js";
14
+ import {
15
+ loadDedupConfig,
16
+ type DedupConfigShape,
17
+ type DedupTier,
18
+ } from "./config/dedup.js";
15
19
  import { logDecision } from "./monitoring.js";
16
20
  import type { StoredCheckpoint } from "./store.js";
17
21
  import { getStateDir, normalizeSessionId, compressSmart } from "./store.js";
18
22
  import { computeContentDigest } from "./dedup/digest.js";
19
- import { minhashSignature, SIGNATURE_VERSION, NUM_HASHES } from "./dedup/l1-minhash.js";
23
+ import type { RaptorTree } from "./dedup/raptor/tree.js";
24
+ import {
25
+ minhashSignature,
26
+ SIGNATURE_VERSION,
27
+ NUM_HASHES,
28
+ } from "./dedup/l1-minhash.js";
20
29
  import { lshBands } from "./dedup/l1-lsh.js";
21
30
  import { isNearDuplicate } from "./dedup/l1-verify.js";
22
31
  import { openBloom, saveBloom } from "./store/bloom.js";
23
32
  import {
24
- listCheckpoints,
25
- nextCheckpointId,
26
- upsertCheckpoint,
27
- loadSessionState,
28
- saveSessionState,
29
- upsertMinhashSignature,
30
- insertLshBuckets,
31
- lshCandidateChunks,
32
- addTokensSaved,
33
- bumpDedupStats,
33
+ listCheckpoints,
34
+ nextCheckpointId,
35
+ upsertCheckpoint,
36
+ loadSessionState,
37
+ saveSessionState,
38
+ upsertMinhashSignature,
39
+ insertLshBuckets,
40
+ lshCandidateChunks,
41
+ addTokensSaved,
42
+ bumpDedupStats,
34
43
  } from "./store/sqlite.js";
35
44
  import { migrateJsonToSqlite } from "./store/migrate.js";
36
45
 
37
46
  export interface SearchHit {
38
- checkpoint: StoredCheckpoint;
39
- score: number;
40
- /** Source repo id (the foreign repo's stateDir) for cross-repo hits, set by
41
- * `searchAsync` so the recall block can label foreign checkpoints. Undefined
42
- * for same-repo hits (the default path). */
43
- repoId?: string;
47
+ checkpoint: StoredCheckpoint;
48
+ score: number;
49
+ /** Source repo id (the foreign repo's stateDir) for cross-repo hits, set by
50
+ * `searchAsync` so the recall block can label foreign checkpoints. Undefined
51
+ * for same-repo hits (the default path). */
52
+ repoId?: string;
53
+ /** S42B: when set, this hit is a RAPTOR cluster node (not a stored checkpoint).
54
+ * The recall block uses `raptorSummary` instead of checkpoint.summary. */
55
+ raptorSummary?: string;
56
+ /** S42B: the tree level of the cluster node (0 = leaves, 1+ = internal). */
57
+ raptorLevel?: number;
44
58
  }
45
59
 
46
60
  export interface AddInput {
47
- sessionId: string;
48
- summary: string;
49
- /** Compressed topic summary (extractive). When present, embedded instead of regionText. */
50
- topicSummary?: string;
51
- keyDecisions?: string[];
52
- nextSteps?: string[];
53
- filesModified?: string[];
54
- tokenEstimate?: number;
55
- /** Token count of the ORIGINAL dropped region (before compaction). Drives the
56
- * honest "tokens saved" = originalTokenEstimate − tokenEstimate (stored), or
57
- * the full originalTokenEstimate when the region dedups (nothing new stored).
58
- * Optional for back-compat with direct add() callers; defaults to stored. */
59
- originalTokenEstimate?: number;
60
- /** Raw text of the compacted region — used to derive the regionHash + vector. */
61
- regionText: string;
62
- timestamp: number;
63
- /** Sync progress callback fired as each dedup tier is evaluated (L0→L1→L2→new).
64
- * Lets the UI render live per-tier progress during compaction. Never awaited;
65
- * must be cheap. Optional for back-compat. */
66
- onTier?: (ev: { tier: "L0" | "L1" | "L2" | "new"; status: "scanning" | "deduped" | "passed" | "stored"; detail?: string }) => void;
67
- /** Context-window pressure (0–1) escalates the stored checkpoint's sync
68
- * compression strength (Fix E). Optional; defaults to 0 (brotli-4). */
69
- compressionPressure?: number;
61
+ sessionId: string;
62
+ summary: string;
63
+ /** Compressed topic summary (extractive). When present, embedded instead of regionText. */
64
+ topicSummary?: string;
65
+ keyDecisions?: string[];
66
+ nextSteps?: string[];
67
+ filesModified?: string[];
68
+ tokenEstimate?: number;
69
+ /** Token count of the ORIGINAL dropped region (before compaction). Drives the
70
+ * honest "tokens saved" = originalTokenEstimate − tokenEstimate (stored), or
71
+ * the full originalTokenEstimate when the region dedups (nothing new stored).
72
+ * Optional for back-compat with direct add() callers; defaults to stored. */
73
+ originalTokenEstimate?: number;
74
+ /** Raw text of the compacted region — used to derive the regionHash + vector. */
75
+ regionText: string;
76
+ timestamp: number;
77
+ /** Sync progress callback fired as each dedup tier is evaluated (L0→L1→L2→new).
78
+ * Lets the UI render live per-tier progress during compaction. Never awaited;
79
+ * must be cheap. Optional for back-compat. */
80
+ onTier?: (ev: {
81
+ tier: "L0" | "L1" | "L2" | "new";
82
+ status: "scanning" | "deduped" | "passed" | "stored";
83
+ detail?: string;
84
+ }) => void;
85
+ /** Context-window pressure (0–1) — escalates the stored checkpoint's sync
86
+ * compression strength (Fix E). Optional; defaults to 0 (brotli-4). */
87
+ compressionPressure?: number;
70
88
  }
71
89
 
72
90
  /** Default L2 semantic-dedup enable flag (trigram embedder is local, zero-network). */
73
91
  export const L2_ENABLED = true;
74
92
 
75
93
  export interface AddResult {
76
- checkpoint: StoredCheckpoint;
77
- deduped: boolean; // true when an equivalent region already existed (skipped embed)
78
- /** Which dedup tier matched: regionHash | summaryHash | contentSimilarity | undefined (new). */
79
- reason?: string;
94
+ checkpoint: StoredCheckpoint;
95
+ deduped: boolean; // true when an equivalent region already existed (skipped embed)
96
+ /** Which dedup tier matched: regionHash | summaryHash | contentSimilarity | undefined (new). */
97
+ reason?: string;
80
98
  }
81
99
 
82
100
  /** Stable hash of a compacted region, the dedup sentinel key. */
83
101
  export function computeRegionHash(regionText: string): string {
84
- // Normalize whitespace before hashing so "foo bar" and "foo bar" dedup.
85
- const normalized = regionText.replace(/\s+/g, " ").trim();
86
- return createHash("sha256").update(normalized).digest("hex").slice(0, 16);
102
+ // Normalize whitespace before hashing so "foo bar" and "foo bar" dedup.
103
+ const normalized = regionText.replace(/\s+/g, " ").trim();
104
+ return createHash("sha256").update(normalized).digest("hex").slice(0, 16);
87
105
  }
88
106
 
89
107
  export class VectorStore {
90
- // These fields are `readonly` (set once in the constructor) but NOT private:
91
- // the read/search/dedup helpers split into vector-read.ts, vector-search.ts,
92
- // and vector-dedup.ts access them directly. Marking them private would force
93
- // ugly `as unknown as` casts in those modules; keeping them package-public
94
- // makes VectorStore a thin barrel whose helpers live in sibling files.
95
- readonly embedder: Embedder;
96
- readonly stateDir: string;
97
- private readonly l2Threshold: number;
98
- /** Single source of truth for tier flags + thresholds (Sprint 14). */
99
- readonly cfg: DedupConfigShape;
100
- /** Optional monitoring target (Sprint 14). Undefined → no monitoring. */
101
- private readonly eventsPath?: string;
102
- /**
103
- * Repo key for the async PGlite vector index (Slice 2). We use the stateDir
104
- * itself as the repo id — it is already unique per repo and available here
105
- * without crossing into the pi-runtime layer (src/ stays pi-agnostic). The
106
- * global index keys on repoId so recall can span repos.
107
- */
108
- readonly repoId: string;
108
+ // These fields are `readonly` (set once in the constructor) but NOT private:
109
+ // the read/search/dedup helpers split into vector-read.ts, vector-search.ts,
110
+ // and vector-dedup.ts access them directly. Marking them private would force
111
+ // ugly `as unknown as` casts in those modules; keeping them package-public
112
+ // makes VectorStore a thin barrel whose helpers live in sibling files.
113
+ readonly embedder: Embedder;
114
+ readonly stateDir: string;
115
+ private readonly l2Threshold: number;
116
+ /** Single source of truth for tier flags + thresholds (Sprint 14). */
117
+ readonly cfg: DedupConfigShape;
118
+ /** Optional monitoring target (Sprint 14). Undefined → no monitoring. */
119
+ private readonly eventsPath?: string;
120
+ /**
121
+ * Repo key for the async PGlite vector index (Slice 2). We use the stateDir
122
+ * itself as the repo id — it is already unique per repo and available here
123
+ * without crossing into the pi-runtime layer (src/ stays pi-agnostic). The
124
+ * global index keys on repoId so recall can span repos.
125
+ */
126
+ readonly repoId: string;
127
+ /** S25: per-session cached rehydrated RaptorTree. Keyed by sessionId.
128
+ * Freshness-validated via maxRaptorNodeBuiltAt on each lookup — a cheap
129
+ * indexed MAX query replaces the O(n·leaves) rehydrate on every search. */
130
+ readonly raptorCache = new Map<
131
+ string,
132
+ { tree: RaptorTree; builtAt: number }
133
+ >();
109
134
 
110
- constructor(
111
- opts: {
112
- embedder?: Embedder;
113
- dedupSim?: number;
114
- stateDir?: string;
115
- l2Enabled?: boolean;
116
- l2Threshold?: number;
117
- /** Override the dedup config (defaults to env/file snapshot). */
118
- config?: DedupConfigShape;
119
- /** Optional events.log path for decision monitoring (Sprint 14). */
120
- eventsPath?: string;
121
- /** Repo id for the async cross-repo vector index. Defaults to stateDir. */
122
- repoId?: string;
123
- } = {},
124
- ) {
125
- this.embedder = opts.embedder ?? defaultEmbedder();
126
- this.stateDir = opts.stateDir ?? getStateDir();
127
- this.repoId = opts.repoId ?? this.stateDir;
128
- // Sprint 14: all tier flags/thresholds flow from the single config source
129
- // (DedupConfig). The legacy opts.dedupSim / opts.l2Enabled remain accepted
130
- // for backward-compat callers but flags are authoritative via `cfg`.
131
- void opts.dedupSim;
132
- void opts.l2Enabled;
133
- // Sprint 12 L2 semantic tier. Threshold 0.85 is the default trigram
134
- // embedder's honest firing point; a direct override is allowed for tests.
135
- this.cfg = opts.config ?? loadDedupConfig();
136
- this.l2Threshold = opts.l2Threshold ?? this.cfg.L2_COSINE;
137
- this.eventsPath = opts.eventsPath;
138
- // Sprint 8: bring any v0.1.0 JSON checkpoint files into SQLite (idempotent).
139
- migrateJsonToSqlite(this.stateDir);
140
- // Sprint 10: warm the bloom accelerator (accelerator only — SQLite stays
141
- // source of truth; a bloom hit is always confirmed by a query below).
142
- openBloom(this.stateDir);
143
- }
135
+ constructor(
136
+ opts: {
137
+ embedder?: Embedder;
138
+ dedupSim?: number;
139
+ stateDir?: string;
140
+ l2Enabled?: boolean;
141
+ l2Threshold?: number;
142
+ /** Override the dedup config (defaults to env/file snapshot). */
143
+ config?: DedupConfigShape;
144
+ /** Optional events.log path for decision monitoring (Sprint 14). */
145
+ eventsPath?: string;
146
+ /** Repo id for the async cross-repo vector index. Defaults to stateDir. */
147
+ repoId?: string;
148
+ } = {},
149
+ ) {
150
+ this.embedder = opts.embedder ?? defaultEmbedder();
151
+ this.stateDir = opts.stateDir ?? getStateDir();
152
+ this.repoId = opts.repoId ?? this.stateDir;
153
+ // Sprint 14: all tier flags/thresholds flow from the single config source
154
+ // (DedupConfig). The legacy opts.dedupSim / opts.l2Enabled remain accepted
155
+ // for backward-compat callers but flags are authoritative via `cfg`.
156
+ void opts.dedupSim;
157
+ void opts.l2Enabled;
158
+ // Sprint 12 L2 semantic tier. Threshold 0.85 is the default trigram
159
+ // embedder's honest firing point; a direct override is allowed for tests.
160
+ this.cfg = opts.config ?? loadDedupConfig();
161
+ this.l2Threshold = opts.l2Threshold ?? this.cfg.L2_COSINE;
162
+ this.eventsPath = opts.eventsPath;
163
+ // Sprint 8: bring any v0.1.0 JSON checkpoint files into SQLite (idempotent).
164
+ migrateJsonToSqlite(this.stateDir);
165
+ // Sprint 10: warm the bloom accelerator (accelerator only — SQLite stays
166
+ // source of truth; a bloom hit is always confirmed by a query below).
167
+ openBloom(this.stateDir);
168
+ }
144
169
 
145
- /** Emit a structured dedup-decision event (best-effort, never throws). */
146
- record(tier: DedupTier, result: "deduped" | "new" | "mark_only", reason: string | undefined, latencyMs: number): void {
147
- if (!this.eventsPath) return;
148
- logDecision(this.eventsPath, {
149
- ts: Date.now(),
150
- tier,
151
- result,
152
- reason,
153
- latencyMs: Math.round(latencyMs * 100) / 100,
154
- });
155
- }
170
+ /** Emit a structured dedup-decision event (best-effort, never throws). */
171
+ record(
172
+ tier: DedupTier,
173
+ result: "deduped" | "new" | "mark_only",
174
+ reason: string | undefined,
175
+ latencyMs: number,
176
+ ): void {
177
+ if (!this.eventsPath) return;
178
+ logDecision(this.eventsPath, {
179
+ ts: Date.now(),
180
+ tier,
181
+ result,
182
+ reason,
183
+ latencyMs: Math.round(latencyMs * 100) / 100,
184
+ });
185
+ }
156
186
 
157
- /**
158
- * Add a checkpoint. Dedup cascade:
159
- * 1. regionHash exact match (legacy, backward-compat)
160
- * 2. summaryHash exact match (new: catches same-topic incremental compactions)
161
- * 3. content similarity ≥ dedupSim (catches near-identical summaries)
162
- * 4. If none match → create new checkpoint
163
- */
164
- add(input: AddInput): AddResult {
165
- const t0 = Date.now();
166
- const sessionId = normalizeSessionId(input.sessionId);
167
- const regionHash = computeRegionHash(input.regionText);
168
- const all = listCheckpoints(sessionId, this.stateDir);
169
- // Honest "tokens saved" base for this region. For a deduped add the whole
170
- // original region is discarded (nothing new stored); for a new checkpoint
171
- // we persist (orig − stored). Falls back to stored when orig is unknown.
172
- const origTokens = input.originalTokenEstimate ?? input.tokenEstimate ?? 0;
173
- const cfg = this.cfg;
174
- // Live per-tier progress hook (Phase 1). Sync + optional; fired at each tier
175
- // so the UI can paint "L0 ✓ → L1 ✓ → L2 0.91 → stored" during a compaction.
176
- const onTier = input.onTier;
177
- // Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
178
- // and which tier.
179
- let markOnly: DedupTier | null = null;
187
+ /**
188
+ * Add a checkpoint. Dedup cascade:
189
+ * 1. regionHash exact match (legacy, backward-compat)
190
+ * 2. summaryHash exact match (new: catches same-topic incremental compactions)
191
+ * 3. content similarity ≥ dedupSim (catches near-identical summaries)
192
+ * 4. If none match → create new checkpoint
193
+ */
194
+ add(input: AddInput): AddResult {
195
+ const t0 = Date.now();
196
+ const sessionId = normalizeSessionId(input.sessionId);
197
+ const regionHash = computeRegionHash(input.regionText);
198
+ const all = listCheckpoints(sessionId, this.stateDir);
199
+ // Honest "tokens saved" base for this region. For a deduped add the whole
200
+ // original region is discarded (nothing new stored); for a new checkpoint
201
+ // we persist (orig − stored). Falls back to stored when orig is unknown.
202
+ const origTokens = input.originalTokenEstimate ?? input.tokenEstimate ?? 0;
203
+ const cfg = this.cfg;
204
+ // Live per-tier progress hook (Phase 1). Sync + optional; fired at each tier
205
+ // so the UI can paint "L0 ✓ → L1 ✓ → L2 0.91 → stored" during a compaction.
206
+ const onTier = input.onTier;
207
+ // Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
208
+ // and which tier.
209
+ let markOnly: DedupTier | null = null;
180
210
 
181
- // 0. L0 content-hash dedup (Sprint 9) — catches identical content arriving
182
- // under different regionText. Normalization handles case/whitespace/ANSI so
183
- // variants collapse to one row. Dual-hash guards a single-hash collision.
184
- // Sprint 10: bloom is the accelerator — a miss means "definitely new" and
185
- // skips the scan; a hit is only a candidate, confirmed against `all` below.
186
- // Gated by L0_ENABLED (Sprint 14). MARK_ONLY_L0 records the decision but
187
- // does not collapse — the new region is still stored.
188
- onTier?.({ tier: "L0", status: "scanning" });
189
- const digest = computeContentDigest(input.regionText);
190
- const bloom = openBloom(this.stateDir);
191
- if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
192
- const contentMatch = all.find(
193
- (cp) =>
194
- cp.contentHash === digest.contentHash &&
195
- cp.contentHash2 === digest.contentHash2,
196
- );
197
- if (contentMatch) {
198
- if (cfg.MARK_ONLY_L0) {
199
- markOnly = "L0"; // Record-but-don't-collapse: fall through.
200
- } else {
201
- contentMatch.timestamp = input.timestamp;
202
- upsertCheckpoint(contentMatch, this.stateDir);
203
- bumpDedupStats(true, this.stateDir);
204
- // Deduped: whole original region discarded, nothing new stored.
205
- addTokensSaved(origTokens, this.stateDir);
206
- const r = { checkpoint: contentMatch, deduped: true, reason: "contentHash" };
207
- this.record("L0", "deduped", "contentHash", Date.now() - t0);
208
- onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
209
- return r;
210
- }
211
- }
212
- }
211
+ // 0. L0 content-hash dedup (Sprint 9) — catches identical content arriving
212
+ // under different regionText. Normalization handles case/whitespace/ANSI so
213
+ // variants collapse to one row. Dual-hash guards a single-hash collision.
214
+ // Sprint 10: bloom is the accelerator — a miss means "definitely new" and
215
+ // skips the scan; a hit is only a candidate, confirmed against `all` below.
216
+ // Gated by L0_ENABLED (Sprint 14). MARK_ONLY_L0 records the decision but
217
+ // does not collapse — the new region is still stored.
218
+ onTier?.({ tier: "L0", status: "scanning" });
219
+ const digest = computeContentDigest(input.regionText);
220
+ const bloom = openBloom(this.stateDir);
221
+ if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
222
+ const contentMatch = all.find(
223
+ (cp) =>
224
+ cp.contentHash === digest.contentHash &&
225
+ cp.contentHash2 === digest.contentHash2,
226
+ );
227
+ if (contentMatch) {
228
+ if (cfg.MARK_ONLY_L0) {
229
+ markOnly = "L0"; // Record-but-don't-collapse: fall through.
230
+ } else {
231
+ contentMatch.timestamp = input.timestamp;
232
+ upsertCheckpoint(contentMatch, this.stateDir);
233
+ bumpDedupStats(true, this.stateDir);
234
+ // Deduped: whole original region discarded, nothing new stored.
235
+ addTokensSaved(origTokens, this.stateDir);
236
+ const r = {
237
+ checkpoint: contentMatch,
238
+ deduped: true,
239
+ reason: "contentHash",
240
+ };
241
+ this.record("L0", "deduped", "contentHash", Date.now() - t0);
242
+ onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
243
+ return r;
244
+ }
245
+ }
246
+ }
213
247
 
214
- // 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
215
- if (cfg.L0_ENABLED) {
216
- const regionMatch = all.find((cp) => cp.regionHash === regionHash);
217
- if (regionMatch) {
218
- if (cfg.MARK_ONLY_L0) {
219
- markOnly = "L0"; // fall through
220
- } else {
221
- bumpDedupStats(true, this.stateDir);
222
- // Deduped: whole original region discarded, nothing new stored.
223
- addTokensSaved(origTokens, this.stateDir);
224
- const r = { checkpoint: regionMatch, deduped: true, reason: "regionHash" };
225
- this.record("L0", "deduped", "regionHash", Date.now() - t0);
226
- onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
227
- return r;
228
- }
229
- }
230
- }
248
+ // 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
249
+ if (cfg.L0_ENABLED) {
250
+ const regionMatch = all.find((cp) => cp.regionHash === regionHash);
251
+ if (regionMatch) {
252
+ if (cfg.MARK_ONLY_L0) {
253
+ markOnly = "L0"; // fall through
254
+ } else {
255
+ bumpDedupStats(true, this.stateDir);
256
+ // Deduped: whole original region discarded, nothing new stored.
257
+ addTokensSaved(origTokens, this.stateDir);
258
+ const r = {
259
+ checkpoint: regionMatch,
260
+ deduped: true,
261
+ reason: "regionHash",
262
+ };
263
+ this.record("L0", "deduped", "regionHash", Date.now() - t0);
264
+ onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
265
+ return r;
266
+ }
267
+ }
268
+ }
231
269
 
232
- // 2. SummaryHash dedup — catches same-topic incremental compactions.
233
- // Full 64-hex SHA-256 (was 16-hex in Sprint 8 — collision-prone).
234
- const summaryHash = input.topicSummary
235
- ? createHash("sha256").update(input.topicSummary).digest("hex")
236
- : undefined;
237
- if (summaryHash && cfg.L0_ENABLED) {
238
- const summaryMatch = all.find((cp) => cp.summaryHash === summaryHash);
239
- if (summaryMatch) {
240
- if (cfg.MARK_ONLY_L0) {
241
- markOnly = "L0"; // fall through
242
- } else {
243
- summaryMatch.timestamp = input.timestamp;
244
- upsertCheckpoint(summaryMatch, this.stateDir);
245
- bumpDedupStats(true, this.stateDir);
246
- // Deduped: whole original region discarded, nothing new stored.
247
- addTokensSaved(origTokens, this.stateDir);
248
- const r = { checkpoint: summaryMatch, deduped: true, reason: "summaryHash" };
249
- this.record("L0", "deduped", "summaryHash", Date.now() - t0);
250
- onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
251
- return r;
252
- }
253
- }
254
- }
255
- // L0 did not collapse this region.
256
- onTier?.({ tier: "L0", status: "passed" });
270
+ // 2. SummaryHash dedup — catches same-topic incremental compactions.
271
+ // Full 64-hex SHA-256 (was 16-hex in Sprint 8 — collision-prone).
272
+ const summaryHash = input.topicSummary
273
+ ? createHash("sha256").update(input.topicSummary).digest("hex")
274
+ : undefined;
275
+ if (summaryHash && cfg.L0_ENABLED) {
276
+ const summaryMatch = all.find((cp) => cp.summaryHash === summaryHash);
277
+ if (summaryMatch) {
278
+ if (cfg.MARK_ONLY_L0) {
279
+ markOnly = "L0"; // fall through
280
+ } else {
281
+ summaryMatch.timestamp = input.timestamp;
282
+ upsertCheckpoint(summaryMatch, this.stateDir);
283
+ bumpDedupStats(true, this.stateDir);
284
+ // Deduped: whole original region discarded, nothing new stored.
285
+ addTokensSaved(origTokens, this.stateDir);
286
+ const r = {
287
+ checkpoint: summaryMatch,
288
+ deduped: true,
289
+ reason: "summaryHash",
290
+ };
291
+ this.record("L0", "deduped", "summaryHash", Date.now() - t0);
292
+ onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
293
+ return r;
294
+ }
295
+ }
296
+ }
297
+ // L0 did not collapse this region.
298
+ onTier?.({ tier: "L0", status: "passed" });
257
299
 
258
- // 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
259
- // edits / rewordings that L0's exact hash misses. Cheap LSH bucket
260
- // retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
261
- // Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
262
- onTier?.({ tier: "L1", status: "scanning" });
263
- if (cfg.L1_ENABLED) {
264
- const l1 = this.findL1Duplicate(sessionId, input.regionText, all);
265
- if (l1 && !cfg.MARK_ONLY_L1) {
266
- l1.timestamp = input.timestamp;
267
- upsertCheckpoint(l1, this.stateDir);
268
- bumpDedupStats(true, this.stateDir);
269
- const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
270
- this.record("L1", "deduped", "l1MinHash", Date.now() - t0);
271
- onTier?.({ tier: "L1", status: "deduped", detail: "l1MinHash" });
272
- return r;
273
- }
274
- if (l1 && cfg.MARK_ONLY_L1) markOnly = "L1";
275
- }
276
- onTier?.({ tier: "L1", status: "passed" });
300
+ // 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
301
+ // edits / rewordings that L0's exact hash misses. Cheap LSH bucket
302
+ // retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
303
+ // Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
304
+ onTier?.({ tier: "L1", status: "scanning" });
305
+ if (cfg.L1_ENABLED) {
306
+ const l1 = this.findL1Duplicate(sessionId, input.regionText, all);
307
+ if (l1 && !cfg.MARK_ONLY_L1) {
308
+ l1.timestamp = input.timestamp;
309
+ upsertCheckpoint(l1, this.stateDir);
310
+ bumpDedupStats(true, this.stateDir);
311
+ const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
312
+ this.record("L1", "deduped", "l1MinHash", Date.now() - t0);
313
+ onTier?.({ tier: "L1", status: "deduped", detail: "l1MinHash" });
314
+ return r;
315
+ }
316
+ if (l1 && cfg.MARK_ONLY_L1) markOnly = "L1";
317
+ }
318
+ onTier?.({ tier: "L1", status: "passed" });
277
319
 
278
- // 3. L2 semantic dedup — catches near-identical / semantically-similar regions
279
- // via cosine over the embedding. topicSummary is used for summaryHash dedup
280
- // (tier 2); the vector index is keyed on the original region for backward-
281
- // compat search semantics. Threshold from cfg (L2_COSINE trigram honest
282
- // firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
283
- // degrade to "store without dedup this pass" so we never lose a checkpoint.
284
- // Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
285
- const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
286
- const simThreshold = this.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
287
- const embedding = this.embedder.embed(input.regionText);
288
- onTier?.({ tier: "L2", status: "scanning" });
289
- if (cfg.L2_ENABLED && all.length > 0) {
290
- const start = Date.now();
291
- let timedOut = false;
292
- const nearest = all.reduce(
293
- (best, cp) => {
294
- if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS) timedOut = true;
295
- if (timedOut) return best;
296
- const sim = cosineSimilarity(embedding, cp.embedding);
297
- return sim > best.sim ? { checkpoint: cp, sim } : best;
298
- },
299
- { checkpoint: all[0], sim: -1 },
300
- );
301
- if (!timedOut && nearest.sim >= simThreshold) {
302
- if (!cfg.MARK_ONLY_L2) {
303
- // Near-identical — update timestamp on existing checkpoint
304
- nearest.checkpoint.timestamp = input.timestamp;
305
- upsertCheckpoint(nearest.checkpoint, this.stateDir);
306
- bumpDedupStats(true, this.stateDir);
307
- // Deduped: whole original region discarded, nothing new stored.
308
- addTokensSaved(origTokens, this.stateDir);
309
- const r = { checkpoint: nearest.checkpoint, deduped: true, reason: "contentSimilarity" };
310
- this.record("L2", "deduped", "contentSimilarity", Date.now() - t0);
311
- onTier?.({ tier: "L2", status: "deduped", detail: nearest.sim.toFixed(2) });
312
- return r;
313
- }
314
- markOnly = "L2";
315
- }
316
- onTier?.({ tier: "L2", status: "passed", detail: `best ${nearest.sim.toFixed(2)}` });
317
- }
320
+ // 3. L2 semantic dedup — catches near-identical / semantically-similar regions
321
+ // via cosine over the embedding. topicSummary is used for summaryHash dedup
322
+ // (tier 2); the vector index is keyed on the original region for backward-
323
+ // compat search semantics. Threshold from cfg (L2_COSINE trigram honest
324
+ // firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
325
+ // degrade to "store without dedup this pass" so we never lose a checkpoint.
326
+ // Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
327
+ const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
328
+ const simThreshold = this.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
329
+ const embedding = this.embedder.embed(input.regionText);
330
+ onTier?.({ tier: "L2", status: "scanning" });
331
+ if (cfg.L2_ENABLED && all.length > 0) {
332
+ const start = Date.now();
333
+ let timedOut = false;
334
+ const nearest = all.reduce(
335
+ (best, cp) => {
336
+ if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS)
337
+ timedOut = true;
338
+ if (timedOut) return best;
339
+ const sim = cosineSimilarity(embedding, cp.embedding);
340
+ return sim > best.sim ? { checkpoint: cp, sim } : best;
341
+ },
342
+ { checkpoint: all[0], sim: -1 },
343
+ );
344
+ if (!timedOut && nearest.sim >= simThreshold) {
345
+ if (!cfg.MARK_ONLY_L2) {
346
+ // Near-identical — update timestamp on existing checkpoint
347
+ nearest.checkpoint.timestamp = input.timestamp;
348
+ upsertCheckpoint(nearest.checkpoint, this.stateDir);
349
+ bumpDedupStats(true, this.stateDir);
350
+ // Deduped: whole original region discarded, nothing new stored.
351
+ addTokensSaved(origTokens, this.stateDir);
352
+ const r = {
353
+ checkpoint: nearest.checkpoint,
354
+ deduped: true,
355
+ reason: "contentSimilarity",
356
+ };
357
+ this.record("L2", "deduped", "contentSimilarity", Date.now() - t0);
358
+ onTier?.({
359
+ tier: "L2",
360
+ status: "deduped",
361
+ detail: nearest.sim.toFixed(2),
362
+ });
363
+ return r;
364
+ }
365
+ markOnly = "L2";
366
+ }
367
+ onTier?.({
368
+ tier: "L2",
369
+ status: "passed",
370
+ detail: `best ${nearest.sim.toFixed(2)}`,
371
+ });
372
+ }
318
373
 
319
- // 4. Genuinely new — create checkpoint
320
- const checkpointId = nextCheckpointId(sessionId, this.stateDir);
321
- const checkpoint: StoredCheckpoint = {
322
- checkpointId,
323
- sessionId,
324
- repoId: this.repoId,
325
- summary: input.summary,
326
- topicSummary: input.topicSummary,
327
- summaryHash,
328
- keyDecisions: input.keyDecisions ?? [],
329
- nextSteps: input.nextSteps ?? [],
330
- filesModified: input.filesModified ?? [],
331
- tokenEstimate: input.tokenEstimate ?? 0,
332
- originalTokenEstimate: input.originalTokenEstimate,
333
- regionHash,
334
- contentHash: digest.contentHash,
335
- contentHash2: digest.contentHash2,
336
- contentHashVersion: digest.contentHashVersion,
337
- normalizedText: digest.normalizedText,
338
- compressedOriginal: compressSmart(
339
- Buffer.from(input.regionText, "utf-8"),
340
- input.compressionPressure,
341
- ),
342
- embedding,
343
- timestamp: input.timestamp,
344
- };
345
- // Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
346
- // idempotent-by-id semantics the old JSON append implied.
347
- upsertCheckpoint(checkpoint, this.stateDir);
348
- // Cumulative "tokens saved" counter (per-repo SQLite meta). For a NEW
349
- // checkpoint the saved amount is (original − stored); for a deduped add the
350
- // whole original region is discarded (handled in the deduped return paths
351
- // below). Survives sessions and travels with the repo.
352
- const stored = input.tokenEstimate ?? 0;
353
- addTokensSaved(Math.max(0, origTokens - stored), this.stateDir);
354
- // L1: persist this checkpoint's MinHash signature + LSH buckets so future
355
- // near-duplicate inserts can find it. Deterministic given the seed.
356
- const sig = minhashSignature(input.regionText);
357
- upsertMinhashSignature(checkpointId, sessionId, SIGNATURE_VERSION, sig, this.stateDir);
358
- insertLshBuckets(
359
- checkpointId,
360
- sessionId,
361
- SIGNATURE_VERSION,
362
- lshBands(sig, sessionId, SIGNATURE_VERSION),
363
- this.stateDir,
364
- );
365
- // Bloom accelerator: record the new content_hash so a future add() can short-
366
- // circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
367
- bloom.add(digest.contentHash);
368
- saveBloom(this.stateDir);
374
+ // 4. Genuinely new — create checkpoint
375
+ const checkpointId = nextCheckpointId(sessionId, this.stateDir);
376
+ const checkpoint: StoredCheckpoint = {
377
+ checkpointId,
378
+ sessionId,
379
+ repoId: this.repoId,
380
+ summary: input.summary,
381
+ topicSummary: input.topicSummary,
382
+ summaryHash,
383
+ keyDecisions: input.keyDecisions ?? [],
384
+ nextSteps: input.nextSteps ?? [],
385
+ filesModified: input.filesModified ?? [],
386
+ tokenEstimate: input.tokenEstimate ?? 0,
387
+ originalTokenEstimate: input.originalTokenEstimate,
388
+ regionHash,
389
+ contentHash: digest.contentHash,
390
+ contentHash2: digest.contentHash2,
391
+ contentHashVersion: digest.contentHashVersion,
392
+ normalizedText: digest.normalizedText,
393
+ compressedOriginal: compressSmart(
394
+ Buffer.from(input.regionText, "utf-8"),
395
+ input.compressionPressure,
396
+ ),
397
+ embedding,
398
+ timestamp: input.timestamp,
399
+ };
400
+ // Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
401
+ // idempotent-by-id semantics the old JSON append implied.
402
+ upsertCheckpoint(checkpoint, this.stateDir);
403
+ // Cumulative "tokens saved" counter (per-repo SQLite meta). For a NEW
404
+ // checkpoint the saved amount is (original − stored); for a deduped add the
405
+ // whole original region is discarded (handled in the deduped return paths
406
+ // below). Survives sessions and travels with the repo.
407
+ const stored = input.tokenEstimate ?? 0;
408
+ addTokensSaved(Math.max(0, origTokens - stored), this.stateDir);
409
+ // L1: persist this checkpoint's MinHash signature + LSH buckets so future
410
+ // near-duplicate inserts can find it. Deterministic given the seed.
411
+ const sig = minhashSignature(input.regionText);
412
+ upsertMinhashSignature(
413
+ checkpointId,
414
+ sessionId,
415
+ SIGNATURE_VERSION,
416
+ sig,
417
+ this.stateDir,
418
+ );
419
+ insertLshBuckets(
420
+ checkpointId,
421
+ sessionId,
422
+ SIGNATURE_VERSION,
423
+ lshBands(sig, sessionId, SIGNATURE_VERSION),
424
+ this.stateDir,
425
+ );
426
+ // Bloom accelerator: record the new content_hash so a future add() can short-
427
+ // circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
428
+ bloom.add(digest.contentHash);
429
+ saveBloom(this.stateDir);
369
430
 
370
- // Track the region hash in session state for fast sentinel checks.
371
- const state = loadSessionState(sessionId, this.stateDir);
372
- if (!state.storedRegionHashes.includes(regionHash)) {
373
- state.storedRegionHashes.push(regionHash);
374
- saveSessionState(sessionId, state, this.stateDir);
375
- }
376
- // A new checkpoint. If a tier matched while MARK_ONLY, record that (the
377
- // decision fired but we intentionally did not collapse).
378
- if (markOnly) {
379
- this.record(markOnly, "mark_only", "mark_only", Date.now() - t0);
380
- } else {
381
- this.record("L0", "new", undefined, Date.now() - t0);
382
- }
383
- // Cumulative store-wide dedup accounting (attempt, not collapsed).
384
- bumpDedupStats(false, this.stateDir);
385
- onTier?.({ tier: "new", status: "stored" });
386
- return { checkpoint, deduped: false };
387
- }
431
+ // Track the region hash in session state for fast sentinel checks.
432
+ const state = loadSessionState(sessionId, this.stateDir);
433
+ if (!state.storedRegionHashes.includes(regionHash)) {
434
+ state.storedRegionHashes.push(regionHash);
435
+ saveSessionState(sessionId, state, this.stateDir);
436
+ }
437
+ // A new checkpoint. If a tier matched while MARK_ONLY, record that (the
438
+ // decision fired but we intentionally did not collapse).
439
+ if (markOnly) {
440
+ this.record(markOnly, "mark_only", "mark_only", Date.now() - t0);
441
+ } else {
442
+ this.record("L0", "new", undefined, Date.now() - t0);
443
+ }
444
+ // Cumulative store-wide dedup accounting (attempt, not collapsed).
445
+ bumpDedupStats(false, this.stateDir);
446
+ onTier?.({ tier: "new", status: "stored" });
447
+ return { checkpoint, deduped: false };
448
+ }
388
449
 
389
- /**
390
- * L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
391
- * Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
392
- * and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
393
- */
394
- private findL1Duplicate(
395
- sessionId: string,
396
- regionText: string,
397
- all: StoredCheckpoint[],
398
- ): StoredCheckpoint | undefined {
399
- if (all.length === 0) return undefined;
400
- const sig = minhashSignature(regionText);
401
- if (sig.length !== NUM_HASHES) return undefined;
402
- const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
403
- // Cheap candidate retrieval (single query, capped). Exclude nothing yet —
404
- // the new checkpoint has no id, so pass a sentinel that never matches.
405
- const candidateIds = lshCandidateChunks(
406
- bands,
407
- sessionId,
408
- "__new__",
409
- this.stateDir,
410
- 100,
411
- );
412
- if (candidateIds.length === 0) return undefined;
413
- const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
414
- const VERIFY_BUDGET_MS = 20;
415
- const start = Date.now();
416
- for (const id of candidateIds) {
417
- if (Date.now() - start > VERIFY_BUDGET_MS) break; // QA #15: abort → "not dup"
418
- const cand = byId.get(id);
419
- if (!cand) continue;
420
- const candText = cand.normalizedText ?? cand.summary ?? "";
421
- if (isNearDuplicate(regionText, candText)) return cand;
422
- }
423
- return undefined;
424
- }
450
+ /**
451
+ * L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
452
+ * Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
453
+ * and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
454
+ */
455
+ private findL1Duplicate(
456
+ sessionId: string,
457
+ regionText: string,
458
+ all: StoredCheckpoint[],
459
+ ): StoredCheckpoint | undefined {
460
+ if (all.length === 0) return undefined;
461
+ const sig = minhashSignature(regionText);
462
+ if (sig.length !== NUM_HASHES) return undefined;
463
+ const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
464
+ // Cheap candidate retrieval (single query, capped). Exclude nothing yet —
465
+ // the new checkpoint has no id, so pass a sentinel that never matches.
466
+ const candidateIds = lshCandidateChunks(
467
+ bands,
468
+ sessionId,
469
+ "__new__",
470
+ this.stateDir,
471
+ 100,
472
+ );
473
+ if (candidateIds.length === 0) return undefined;
474
+ const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
475
+ const VERIFY_BUDGET_MS = 20;
476
+ const start = Date.now();
477
+ for (const id of candidateIds) {
478
+ if (Date.now() - start > VERIFY_BUDGET_MS) break; // QA #15: abort → "not dup"
479
+ const cand = byId.get(id);
480
+ if (!cand) continue;
481
+ const candText = cand.normalizedText ?? cand.summary ?? "";
482
+ if (isNearDuplicate(regionText, candText)) return cand;
483
+ }
484
+ return undefined;
485
+ }
425
486
  }
426
487
 
427
488
  // Re-exports (back-compat): existing call sites keep importing from "./vectorStore.js"
428
489
  export {
429
- vectorSemDedup,
430
- vectorDedupe,
431
- vectorMarkInjected,
432
- vectorWasInjected,
433
- vectorSimilarity,
434
- vectorList,
435
- vectorTopSimilar,
436
- vectorStats,
437
- vectorRepoStats,
438
- vectorDataInvariant,
490
+ vectorSemDedup,
491
+ vectorDedupe,
492
+ vectorMarkInjected,
493
+ vectorWasInjected,
494
+ vectorSimilarity,
495
+ vectorList,
496
+ vectorTopSimilar,
497
+ vectorStats,
498
+ vectorRepoStats,
499
+ vectorDataInvariant,
439
500
  } from "./vector-read.js";
440
501
 
441
502
  // Re-exports: vectorSearch / vectorSearchAsync (moved to vector-search.ts)