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.
- package/README.md +26 -0
- package/dist/extensions/mega-compact-s38.test.js +263 -14
- package/dist/extensions/mega-compact.js +15 -0
- package/dist/extensions/mega-config.js +3 -0
- package/dist/extensions/mega-events/agent-handlers.js +211 -26
- package/dist/extensions/mega-events/context-handler.js +45 -7
- package/dist/extensions/mega-events/error-classifier.js +125 -18
- package/dist/extensions/mega-pipeline/compact.js +24 -13
- package/dist/extensions/mega-pipeline/recall.js +31 -2
- package/dist/extensions/mega-runtime/dashboard-snapshot.js +4 -0
- package/dist/extensions/mega-runtime/runtime-snapshot.js +4 -0
- package/dist/extensions/mega-runtime/runtime.js +58 -5
- package/dist/src/boundary.js +79 -43
- package/dist/src/boundary.test.js +119 -2
- package/dist/src/canary.js +10 -0
- package/dist/src/config/dedup.js +14 -0
- package/dist/src/config.js +3 -1
- package/dist/src/dedup/raptor/buildHistory.js +164 -0
- package/dist/src/dedup/raptor/buildHistory.test.js +292 -0
- package/dist/src/dedup/raptor/index.js +38 -0
- package/dist/src/dedup/raptor/multilevel-serve.test.js +229 -0
- package/dist/src/dedup/raptor/multilevel.js +17 -5
- package/dist/src/dedup/raptor/multilevel.test.js +36 -1
- package/dist/src/dedup/raptor/raptor.test.js +43 -0
- package/dist/src/dedup/raptor/retrieval.js +14 -2
- package/dist/src/dedup/raptor/retrieval.test.js +95 -0
- package/dist/src/dedup/raptor/serve-gate.test.js +298 -0
- package/dist/src/dedup/raptor/summarizer.js +1 -0
- package/dist/src/dedup/raptor/tree.js +16 -2
- package/dist/src/engine.js +18 -2
- package/dist/src/httpEmbedder.js +96 -6
- package/dist/src/httpEmbedder.test.js +277 -0
- package/dist/src/mechanical-fix.test.js +65 -0
- package/dist/src/raptor-inject-summaries.test.js +162 -0
- package/dist/src/recall.js +153 -24
- package/dist/src/recall.test.js +179 -4
- package/dist/src/store/sqlite/dedup-mirror.js +32 -15
- package/dist/src/store/sqlite/maintenance.js +2 -2
- package/dist/src/store/sqlite/mechanical-fix.test.js +146 -0
- package/dist/src/store/sqlite/memories.js +5 -5
- package/dist/src/store/sqlite/meta.js +1 -1
- package/dist/src/store/sqlite/raptor.js +56 -17
- package/dist/src/store/sqlite/raptor.test.js +106 -0
- package/dist/src/store/sqlite/schema.js +90 -1
- package/dist/src/store/sqlite/session-state.js +9 -3
- package/dist/src/store/sqlite/stats.js +9 -5
- package/dist/src/store/sqlite/turns.js +179 -0
- package/dist/src/store/sqlite/turns.test.js +183 -0
- package/dist/src/store/sqlite/utils.js +15 -4
- package/dist/src/store/sqlite.js +1 -0
- package/dist/src/store.js +2 -2
- package/dist/src/vector-search-cache.test.js +157 -0
- package/dist/src/vector-search.js +107 -15
- package/dist/src/vectorStore.js +36 -8
- package/extensions/mega-compact-s38.test.ts +259 -14
- package/extensions/mega-compact.ts +15 -0
- package/extensions/mega-config.ts +18 -0
- package/extensions/mega-dashboard.ts +10 -1
- package/extensions/mega-events/agent-handlers.ts +211 -26
- package/extensions/mega-events/context-handler.ts +43 -7
- package/extensions/mega-events/error-classifier.ts +125 -17
- package/extensions/mega-pipeline/compact.ts +28 -16
- package/extensions/mega-pipeline/recall.ts +34 -2
- package/extensions/mega-runtime/dashboard-snapshot.ts +8 -0
- package/extensions/mega-runtime/helpers.ts +25 -1
- package/extensions/mega-runtime/runtime-snapshot.ts +4 -0
- package/extensions/mega-runtime/runtime.ts +69 -23
- package/package.json +1 -1
- package/src/boundary.test.ts +128 -2
- package/src/boundary.ts +75 -39
- package/src/canary.ts +10 -0
- package/src/config/dedup.ts +25 -0
- package/src/config.ts +3 -1
- package/src/dedup/raptor/buildHistory.test.ts +353 -0
- package/src/dedup/raptor/buildHistory.ts +259 -0
- package/src/dedup/raptor/index.ts +38 -0
- package/src/dedup/raptor/multilevel-serve.test.ts +273 -0
- package/src/dedup/raptor/multilevel.test.ts +47 -0
- package/src/dedup/raptor/multilevel.ts +18 -8
- package/src/dedup/raptor/raptor.test.ts +59 -0
- package/src/dedup/raptor/retrieval.test.ts +118 -0
- package/src/dedup/raptor/retrieval.ts +14 -2
- package/src/dedup/raptor/serve-gate.test.ts +348 -0
- package/src/dedup/raptor/summarizer.ts +1 -0
- package/src/dedup/raptor/tree.ts +17 -2
- package/src/engine.ts +32 -3
- package/src/httpEmbedder.test.ts +286 -0
- package/src/httpEmbedder.ts +98 -8
- package/src/mechanical-fix.test.ts +70 -0
- package/src/raptor-inject-summaries.test.ts +228 -0
- package/src/recall.test.ts +220 -4
- package/src/recall.ts +462 -265
- package/src/store/sqlite/dedup-mirror.ts +35 -18
- package/src/store/sqlite/maintenance.ts +2 -2
- package/src/store/sqlite/mechanical-fix.test.ts +162 -0
- package/src/store/sqlite/memories.ts +5 -5
- package/src/store/sqlite/meta.ts +1 -1
- package/src/store/sqlite/raptor.test.ts +139 -0
- package/src/store/sqlite/raptor.ts +135 -81
- package/src/store/sqlite/schema.ts +90 -1
- package/src/store/sqlite/session-state.ts +9 -3
- package/src/store/sqlite/stats.ts +10 -8
- package/src/store/sqlite/turns.test.ts +218 -0
- package/src/store/sqlite/turns.ts +302 -0
- package/src/store/sqlite/utils.ts +14 -4
- package/src/store/sqlite.ts +1 -0
- package/src/store.ts +9 -2
- package/src/vector-search-cache.test.ts +190 -0
- package/src/vector-search.ts +273 -156
- package/src/vectorStore.ts +443 -382
- package/extensions/mega-runtime/reset-runtime.ts +0 -80
package/src/vectorStore.ts
CHANGED
|
@@ -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 {
|
|
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 {
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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)
|