pi-mega-compact 0.20.6 → 0.20.7
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/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +3 -32
- package/dist/extensions/dashboard-server/routes-rag-settings-types.js +11 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +43 -0
- package/dist/src/config/dedup.js +1 -0
- package/dist/src/dedup-audit.test-helpers.js +43 -0
- package/dist/src/monitoring.js +9 -0
- package/dist/src/vectorStore/add-l0.js +108 -0
- package/dist/src/vectorStore/add-l1.js +35 -0
- package/dist/src/vectorStore/add.js +229 -0
- package/dist/src/vectorStore/class.js +15 -291
- package/dist/src/vectorStore/dedup-audit.js +104 -0
- package/dist/src/vectorStore.js +1 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +11 -135
- package/extensions/dashboard-server/routes-rag-settings-types.ts +34 -0
- package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +142 -0
- package/package.json +1 -1
- package/src/config/dedup.ts +9 -0
- package/src/dedup-audit.test-helpers.ts +49 -0
- package/src/monitoring.ts +10 -0
- package/src/vectorStore/add-l0.ts +152 -0
- package/src/vectorStore/add-l1.ts +57 -0
- package/src/vectorStore/add.ts +269 -0
- package/src/vectorStore/class.ts +17 -327
- package/src/vectorStore/dedup-audit.ts +199 -0
- package/src/vectorStore.ts +1 -0
|
@@ -1,34 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
* class.ts — VectorStore implementation (extracted from vectorStore.ts).
|
|
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
|
-
import { createHash } from "node:crypto";
|
|
11
|
-
import { cosineSimilarity, defaultEmbedder } from "../embedder.js";
|
|
1
|
+
import { defaultEmbedder } from "../embedder.js";
|
|
12
2
|
import { loadDedupConfig, } from "../config/dedup.js";
|
|
13
3
|
import { logDecision } from "../monitoring.js";
|
|
14
4
|
import { repoKey } from "../store/repoKey.js";
|
|
15
|
-
import { getStateDir
|
|
16
|
-
import {
|
|
17
|
-
import { minhashSignature, SIGNATURE_VERSION, NUM_HASHES, } from "../dedup/l1-minhash.js";
|
|
18
|
-
import { lshBands } from "../dedup/l1-lsh.js";
|
|
19
|
-
import { isNearDuplicate } from "../dedup/l1-verify.js";
|
|
20
|
-
import { openBloom, saveBloom } from "../store/bloom.js";
|
|
21
|
-
import { listCheckpoints, nextCheckpointId, upsertCheckpoint, loadSessionState, saveSessionState, upsertMinhashSignature, insertLshBuckets, lshCandidateChunks, addTokensSaved, bumpDedupStats, } from "../store/sqlite.js";
|
|
5
|
+
import { getStateDir } from "../store.js";
|
|
6
|
+
import { openBloom } from "../store/bloom.js";
|
|
22
7
|
import { migrateJsonToSqlite } from "../store/migrate.js";
|
|
23
|
-
import {
|
|
8
|
+
import { addCheckpoint } from "./add.js";
|
|
24
9
|
export class VectorStore {
|
|
25
10
|
// These fields are `readonly` (set once in the constructor) but NOT private:
|
|
26
|
-
// the read/search/dedup helpers split into
|
|
27
|
-
// and vector-dedup.ts access them directly. Marking them
|
|
28
|
-
// ugly `as unknown as` casts in those modules; keeping
|
|
29
|
-
// makes VectorStore a thin barrel whose helpers live in
|
|
11
|
+
// the add/read/search/dedup helpers split into add.ts, vector-read.ts,
|
|
12
|
+
// vector-search.ts, and vector-dedup.ts access them directly. Marking them
|
|
13
|
+
// private would force ugly `as unknown as` casts in those modules; keeping
|
|
14
|
+
// them package-public makes VectorStore a thin barrel whose helpers live in
|
|
15
|
+
// sibling files.
|
|
30
16
|
embedder;
|
|
31
17
|
stateDir;
|
|
18
|
+
/** L2 semantic firing point (cfg.L2_COSINE, or a direct test override). */
|
|
32
19
|
l2Threshold;
|
|
33
20
|
/** Single source of truth for tier flags + thresholds (Sprint 14). */
|
|
34
21
|
cfg;
|
|
@@ -82,275 +69,12 @@ export class VectorStore {
|
|
|
82
69
|
});
|
|
83
70
|
}
|
|
84
71
|
/**
|
|
85
|
-
* Add a checkpoint
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
* 4. If none match → create new checkpoint
|
|
72
|
+
* Add a checkpoint, deduping it against the session's existing checkpoints.
|
|
73
|
+
*
|
|
74
|
+
* The cascade itself lives in ./add.ts (sibling-helper pattern) so this class
|
|
75
|
+
* stays a thin shell over the fields its helpers read.
|
|
90
76
|
*/
|
|
91
77
|
add(input) {
|
|
92
|
-
|
|
93
|
-
const sessionId = normalizeSessionId(input.sessionId);
|
|
94
|
-
const regionHash = computeRegionHash(input.regionText);
|
|
95
|
-
const all = listCheckpoints(sessionId, this.stateDir);
|
|
96
|
-
// Honest "tokens saved" base for this region. For a deduped add the whole
|
|
97
|
-
// original region is discarded (nothing new stored); for a new checkpoint
|
|
98
|
-
// we persist (orig − stored). Falls back to stored when orig is unknown.
|
|
99
|
-
const origTokens = input.originalTokenEstimate ?? input.tokenEstimate ?? 0;
|
|
100
|
-
const cfg = this.cfg;
|
|
101
|
-
// Live per-tier progress hook (Phase 1). Sync + optional; fired at each tier
|
|
102
|
-
// so the UI can paint "L0 ✓ → L1 ✓ → L2 0.91 → stored" during a compaction.
|
|
103
|
-
const onTier = input.onTier;
|
|
104
|
-
// Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
|
|
105
|
-
// and which tier.
|
|
106
|
-
let markOnly = null;
|
|
107
|
-
// 0. L0 content-hash dedup (Sprint 9) — catches identical content arriving
|
|
108
|
-
// under different regionText. Normalization handles case/whitespace/ANSI so
|
|
109
|
-
// variants collapse to one row. Dual-hash guards a single-hash collision.
|
|
110
|
-
// Sprint 10: bloom is the accelerator — a miss means "definitely new" and
|
|
111
|
-
// skips the scan; a hit is only a candidate, confirmed against `all` below.
|
|
112
|
-
// Gated by L0_ENABLED (Sprint 14). MARK_ONLY_L0 records the decision but
|
|
113
|
-
// does not collapse — the new region is still stored.
|
|
114
|
-
onTier?.({ tier: "L0", status: "scanning" });
|
|
115
|
-
const digest = computeContentDigest(input.regionText);
|
|
116
|
-
const bloom = openBloom(this.stateDir);
|
|
117
|
-
if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
|
|
118
|
-
const contentMatch = all.find((cp) => cp.contentHash === digest.contentHash &&
|
|
119
|
-
cp.contentHash2 === digest.contentHash2);
|
|
120
|
-
if (contentMatch) {
|
|
121
|
-
if (cfg.MARK_ONLY_L0) {
|
|
122
|
-
markOnly = "L0"; // Record-but-don't-collapse: fall through.
|
|
123
|
-
}
|
|
124
|
-
else {
|
|
125
|
-
contentMatch.timestamp = input.timestamp;
|
|
126
|
-
upsertCheckpoint(contentMatch, this.stateDir);
|
|
127
|
-
bumpDedupStats(true, this.stateDir);
|
|
128
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
129
|
-
addTokensSaved(origTokens, this.stateDir);
|
|
130
|
-
const r = {
|
|
131
|
-
checkpoint: contentMatch,
|
|
132
|
-
deduped: true,
|
|
133
|
-
reason: "contentHash",
|
|
134
|
-
};
|
|
135
|
-
this.record("L0", "deduped", "contentHash", Date.now() - t0, 1, contentMatch.checkpointId);
|
|
136
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
|
|
137
|
-
return r;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
// 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
|
|
142
|
-
if (cfg.L0_ENABLED) {
|
|
143
|
-
const regionMatch = all.find((cp) => cp.regionHash === regionHash);
|
|
144
|
-
if (regionMatch) {
|
|
145
|
-
if (cfg.MARK_ONLY_L0) {
|
|
146
|
-
markOnly = "L0"; // fall through
|
|
147
|
-
}
|
|
148
|
-
else {
|
|
149
|
-
bumpDedupStats(true, this.stateDir);
|
|
150
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
151
|
-
addTokensSaved(origTokens, this.stateDir);
|
|
152
|
-
const r = {
|
|
153
|
-
checkpoint: regionMatch,
|
|
154
|
-
deduped: true,
|
|
155
|
-
reason: "regionHash",
|
|
156
|
-
};
|
|
157
|
-
this.record("L0", "deduped", "regionHash", Date.now() - t0, 1, regionMatch.checkpointId);
|
|
158
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
|
|
159
|
-
return r;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
// 2. SummaryHash dedup — catches same-topic incremental compactions.
|
|
164
|
-
// Full 64-hex SHA-256 (was 16-hex in Sprint 8 — collision-prone).
|
|
165
|
-
const summaryHash = input.topicSummary
|
|
166
|
-
? createHash("sha256").update(input.topicSummary).digest("hex")
|
|
167
|
-
: undefined;
|
|
168
|
-
if (summaryHash && cfg.L0_ENABLED) {
|
|
169
|
-
const summaryMatch = all.find((cp) => cp.summaryHash === summaryHash);
|
|
170
|
-
if (summaryMatch) {
|
|
171
|
-
if (cfg.MARK_ONLY_L0) {
|
|
172
|
-
markOnly = "L0"; // fall through
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
summaryMatch.timestamp = input.timestamp;
|
|
176
|
-
upsertCheckpoint(summaryMatch, this.stateDir);
|
|
177
|
-
bumpDedupStats(true, this.stateDir);
|
|
178
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
179
|
-
addTokensSaved(origTokens, this.stateDir);
|
|
180
|
-
const r = {
|
|
181
|
-
checkpoint: summaryMatch,
|
|
182
|
-
deduped: true,
|
|
183
|
-
reason: "summaryHash",
|
|
184
|
-
};
|
|
185
|
-
this.record("L0", "deduped", "summaryHash", Date.now() - t0, 1, summaryMatch.checkpointId);
|
|
186
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
|
|
187
|
-
return r;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
// L0 did not collapse this region.
|
|
192
|
-
onTier?.({ tier: "L0", status: "passed" });
|
|
193
|
-
// 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
|
|
194
|
-
// edits / rewordings that L0's exact hash misses. Cheap LSH bucket
|
|
195
|
-
// retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
|
|
196
|
-
// Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
|
|
197
|
-
onTier?.({ tier: "L1", status: "scanning" });
|
|
198
|
-
if (cfg.L1_ENABLED) {
|
|
199
|
-
const l1 = this.findL1Duplicate(sessionId, input.regionText, all);
|
|
200
|
-
if (l1 && !cfg.MARK_ONLY_L1) {
|
|
201
|
-
l1.timestamp = input.timestamp;
|
|
202
|
-
upsertCheckpoint(l1, this.stateDir);
|
|
203
|
-
bumpDedupStats(true, this.stateDir);
|
|
204
|
-
const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
|
|
205
|
-
this.record("L1", "deduped", "l1MinHash", Date.now() - t0, 1, l1.checkpointId);
|
|
206
|
-
onTier?.({ tier: "L1", status: "deduped", detail: "l1MinHash" });
|
|
207
|
-
return r;
|
|
208
|
-
}
|
|
209
|
-
if (l1 && cfg.MARK_ONLY_L1)
|
|
210
|
-
markOnly = "L1";
|
|
211
|
-
}
|
|
212
|
-
onTier?.({ tier: "L1", status: "passed" });
|
|
213
|
-
// 3. L2 semantic dedup — catches near-identical / semantically-similar regions
|
|
214
|
-
// via cosine over the embedding. topicSummary is used for summaryHash dedup
|
|
215
|
-
// (tier 2); the vector index is keyed on the original region for backward-
|
|
216
|
-
// compat search semantics. Threshold from cfg (L2_COSINE trigram honest
|
|
217
|
-
// firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
|
|
218
|
-
// degrade to "store without dedup this pass" so we never lose a checkpoint.
|
|
219
|
-
// Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
|
|
220
|
-
const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
|
|
221
|
-
const simThreshold = this.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
|
|
222
|
-
const embedding = this.embedder.embed(input.regionText);
|
|
223
|
-
onTier?.({ tier: "L2", status: "scanning" });
|
|
224
|
-
if (cfg.L2_ENABLED && all.length > 0) {
|
|
225
|
-
const start = Date.now();
|
|
226
|
-
let timedOut = false;
|
|
227
|
-
const nearest = all.reduce((best, cp) => {
|
|
228
|
-
if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS)
|
|
229
|
-
timedOut = true;
|
|
230
|
-
if (timedOut)
|
|
231
|
-
return best;
|
|
232
|
-
const sim = cosineSimilarity(embedding, cp.embedding);
|
|
233
|
-
return sim > best.sim ? { checkpoint: cp, sim } : best;
|
|
234
|
-
}, { checkpoint: all[0], sim: -1 });
|
|
235
|
-
if (!timedOut && nearest.sim >= simThreshold) {
|
|
236
|
-
if (!cfg.MARK_ONLY_L2) {
|
|
237
|
-
// Near-identical — update timestamp on existing checkpoint
|
|
238
|
-
nearest.checkpoint.timestamp = input.timestamp;
|
|
239
|
-
upsertCheckpoint(nearest.checkpoint, this.stateDir);
|
|
240
|
-
bumpDedupStats(true, this.stateDir);
|
|
241
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
242
|
-
addTokensSaved(origTokens, this.stateDir);
|
|
243
|
-
const r = {
|
|
244
|
-
checkpoint: nearest.checkpoint,
|
|
245
|
-
deduped: true,
|
|
246
|
-
reason: "contentSimilarity",
|
|
247
|
-
};
|
|
248
|
-
this.record("L2", "deduped", "contentSimilarity", Date.now() - t0, nearest.sim, nearest.checkpoint.checkpointId);
|
|
249
|
-
onTier?.({
|
|
250
|
-
tier: "L2",
|
|
251
|
-
status: "deduped",
|
|
252
|
-
detail: nearest.sim.toFixed(2),
|
|
253
|
-
});
|
|
254
|
-
return r;
|
|
255
|
-
}
|
|
256
|
-
markOnly = "L2";
|
|
257
|
-
}
|
|
258
|
-
onTier?.({
|
|
259
|
-
tier: "L2",
|
|
260
|
-
status: "passed",
|
|
261
|
-
detail: `best ${nearest.sim.toFixed(2)}`,
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
// 4. Genuinely new — create checkpoint
|
|
265
|
-
const checkpointId = nextCheckpointId(sessionId, this.stateDir);
|
|
266
|
-
const checkpoint = {
|
|
267
|
-
checkpointId,
|
|
268
|
-
sessionId,
|
|
269
|
-
repoId: this.repoId,
|
|
270
|
-
summary: input.summary,
|
|
271
|
-
topicSummary: input.topicSummary,
|
|
272
|
-
summaryHash,
|
|
273
|
-
keyDecisions: input.keyDecisions ?? [],
|
|
274
|
-
nextSteps: input.nextSteps ?? [],
|
|
275
|
-
filesModified: input.filesModified ?? [],
|
|
276
|
-
tokenEstimate: input.tokenEstimate ?? 0,
|
|
277
|
-
originalTokenEstimate: input.originalTokenEstimate,
|
|
278
|
-
regionHash,
|
|
279
|
-
contentHash: digest.contentHash,
|
|
280
|
-
contentHash2: digest.contentHash2,
|
|
281
|
-
contentHashVersion: digest.contentHashVersion,
|
|
282
|
-
normalizedText: digest.normalizedText,
|
|
283
|
-
compressedOriginal: compressSmart(Buffer.from(input.regionText, "utf-8"), input.compressionPressure),
|
|
284
|
-
embedding,
|
|
285
|
-
timestamp: input.timestamp,
|
|
286
|
-
};
|
|
287
|
-
// Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
|
|
288
|
-
// idempotent-by-id semantics the old JSON append implied.
|
|
289
|
-
upsertCheckpoint(checkpoint, this.stateDir);
|
|
290
|
-
// Cumulative "tokens saved" counter (per-repo SQLite meta). For a NEW
|
|
291
|
-
// checkpoint the saved amount is (original − stored); for a deduped add the
|
|
292
|
-
// whole original region is discarded (handled in the deduped return paths
|
|
293
|
-
// below). Survives sessions and travels with the repo.
|
|
294
|
-
const stored = input.tokenEstimate ?? 0;
|
|
295
|
-
addTokensSaved(Math.max(0, origTokens - stored), this.stateDir);
|
|
296
|
-
// L1: persist this checkpoint's MinHash signature + LSH buckets so future
|
|
297
|
-
// near-duplicate inserts can find it. Deterministic given the seed.
|
|
298
|
-
const sig = minhashSignature(input.regionText);
|
|
299
|
-
upsertMinhashSignature(checkpointId, sessionId, SIGNATURE_VERSION, sig, this.stateDir);
|
|
300
|
-
insertLshBuckets(checkpointId, sessionId, SIGNATURE_VERSION, lshBands(sig, sessionId, SIGNATURE_VERSION), this.stateDir);
|
|
301
|
-
// Bloom accelerator: record the new content_hash so a future add() can short-
|
|
302
|
-
// circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
|
|
303
|
-
bloom.add(digest.contentHash);
|
|
304
|
-
saveBloom(this.stateDir);
|
|
305
|
-
// Track the region hash in session state for fast sentinel checks.
|
|
306
|
-
const state = loadSessionState(sessionId, this.stateDir);
|
|
307
|
-
if (!state.storedRegionHashes.includes(regionHash)) {
|
|
308
|
-
state.storedRegionHashes.push(regionHash);
|
|
309
|
-
saveSessionState(sessionId, state, this.stateDir);
|
|
310
|
-
}
|
|
311
|
-
// A new checkpoint. If a tier matched while MARK_ONLY, record that (the
|
|
312
|
-
// decision fired but we intentionally did not collapse).
|
|
313
|
-
if (markOnly) {
|
|
314
|
-
this.record(markOnly, "mark_only", "mark_only", Date.now() - t0);
|
|
315
|
-
}
|
|
316
|
-
else {
|
|
317
|
-
this.record("L0", "new", undefined, Date.now() - t0);
|
|
318
|
-
}
|
|
319
|
-
// Cumulative store-wide dedup accounting (attempt, not collapsed).
|
|
320
|
-
bumpDedupStats(false, this.stateDir);
|
|
321
|
-
onTier?.({ tier: "new", status: "stored" });
|
|
322
|
-
return { checkpoint, deduped: false };
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
|
|
326
|
-
* Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
|
|
327
|
-
* and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
|
|
328
|
-
*/
|
|
329
|
-
findL1Duplicate(sessionId, regionText, all) {
|
|
330
|
-
if (all.length === 0)
|
|
331
|
-
return undefined;
|
|
332
|
-
const sig = minhashSignature(regionText);
|
|
333
|
-
if (sig.length !== NUM_HASHES)
|
|
334
|
-
return undefined;
|
|
335
|
-
const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
|
|
336
|
-
// Cheap candidate retrieval (single query, capped). Exclude nothing yet —
|
|
337
|
-
// the new checkpoint has no id, so pass a sentinel that never matches.
|
|
338
|
-
const candidateIds = lshCandidateChunks(bands, sessionId, "__new__", this.stateDir, 100);
|
|
339
|
-
if (candidateIds.length === 0)
|
|
340
|
-
return undefined;
|
|
341
|
-
const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
|
|
342
|
-
const VERIFY_BUDGET_MS = 20;
|
|
343
|
-
const start = Date.now();
|
|
344
|
-
for (const id of candidateIds) {
|
|
345
|
-
if (Date.now() - start > VERIFY_BUDGET_MS)
|
|
346
|
-
break; // QA #15: abort → "not dup"
|
|
347
|
-
const cand = byId.get(id);
|
|
348
|
-
if (!cand)
|
|
349
|
-
continue;
|
|
350
|
-
const candText = cand.normalizedText ?? cand.summary ?? "";
|
|
351
|
-
if (isNearDuplicate(regionText, candText))
|
|
352
|
-
return cand;
|
|
353
|
-
}
|
|
354
|
-
return undefined;
|
|
78
|
+
return addCheckpoint(this, input);
|
|
355
79
|
}
|
|
356
80
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dedup-audit.ts — durable audit trail for dedup tier decisions
|
|
3
|
+
* (external-audit item #2).
|
|
4
|
+
*
|
|
5
|
+
* Before this module a tier decision existed only as the in-process `onTier`
|
|
6
|
+
* callback that paints the live UI; nothing survived the process, so an
|
|
7
|
+
* operator could not answer "which layer collapsed this region, onto what, at
|
|
8
|
+
* what similarity?" — the inputs needed to tune the thresholds in
|
|
9
|
+
* config/dedup.ts. Here each decision is appended to the repo's events.log as
|
|
10
|
+
* one structured JSON line (see `DedupAuditEvent` below).
|
|
11
|
+
*
|
|
12
|
+
* The event type and its append helper live HERE rather than in monitoring.ts:
|
|
13
|
+
* monitoring.ts already owns three concerns (decision events, the dashboard.json
|
|
14
|
+
* metrics snapshot, FP alerting) and sits close to its 300-line soft limit, so
|
|
15
|
+
* co-locating the shape with the only recorder that produces it keeps both files
|
|
16
|
+
* under the headroom gate. monitoring.ts re-exports both for callers (and the
|
|
17
|
+
* dashboard SSE tail) that treat it as the events.log barrel.
|
|
18
|
+
*
|
|
19
|
+
* Design constraints:
|
|
20
|
+
* - PURE INSTRUMENTATION. Nothing in this file may influence a dedup outcome.
|
|
21
|
+
* - Best-effort/non-fatal: `logDedupAudit` swallows IO errors, and the emitter
|
|
22
|
+
* itself is wrapped so a malformed field can never break add().
|
|
23
|
+
* - Honest fields only: a value is emitted only where the caller actually
|
|
24
|
+
* computed it. L0/L1 are hash/verify tiers and pass no `similarity`.
|
|
25
|
+
* - Signal, not chatter: callers emit on DECISIONS (a match, a scored
|
|
26
|
+
* candidate, the final outcome), never on every "scanning" transition.
|
|
27
|
+
* - Flag-gated by cfg.DEDUP_AUDIT (default ON; OFF writes nothing at all).
|
|
28
|
+
*
|
|
29
|
+
* PREVENT-PI-004: local filesystem append only, no network.
|
|
30
|
+
*/
|
|
31
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
32
|
+
import { dirname } from "node:path";
|
|
33
|
+
import { defaultEventsPath } from "../monitoring.js";
|
|
34
|
+
/**
|
|
35
|
+
* Append one audit event to events.log (best-effort, never throws).
|
|
36
|
+
*
|
|
37
|
+
* Same append-one-JSON-line contract as monitoring.ts's logDecision — an
|
|
38
|
+
* unwritable path is swallowed so instrumentation can never break add().
|
|
39
|
+
*/
|
|
40
|
+
export function logDedupAudit(path, ev) {
|
|
41
|
+
try {
|
|
42
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
43
|
+
appendFileSync(path, `${JSON.stringify(ev)}\n`, "utf-8");
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
/* best-effort — never break the extension on a log failure */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Build a recorder bound to one add() cascade. */
|
|
50
|
+
export function dedupAuditRecorder(ctx, scope) {
|
|
51
|
+
const base = {
|
|
52
|
+
sessionId: scope.sessionId,
|
|
53
|
+
originalTokenEstimate: scope.originalTokenEstimate,
|
|
54
|
+
tokenEstimate: scope.tokenEstimate,
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
deduped: (tier, matchedEntry, dedupReason, similarity) => emitDedupAudit(ctx, {
|
|
58
|
+
...base,
|
|
59
|
+
tier,
|
|
60
|
+
status: "deduped",
|
|
61
|
+
matchedEntry,
|
|
62
|
+
dedupReason,
|
|
63
|
+
...(similarity === undefined ? {} : { similarity }),
|
|
64
|
+
}),
|
|
65
|
+
passed: (tier, matchedEntry, similarity) => emitDedupAudit(ctx, {
|
|
66
|
+
...base,
|
|
67
|
+
tier,
|
|
68
|
+
status: "passed",
|
|
69
|
+
matchedEntry,
|
|
70
|
+
similarity,
|
|
71
|
+
}),
|
|
72
|
+
stored: (storedEntry, dedupReason, tokenEstimate) => emitDedupAudit(ctx, {
|
|
73
|
+
...base,
|
|
74
|
+
tier: "new",
|
|
75
|
+
status: "stored",
|
|
76
|
+
storedEntry,
|
|
77
|
+
dedupReason,
|
|
78
|
+
tokenEstimate,
|
|
79
|
+
}),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Append one dedup decision to events.log.
|
|
84
|
+
*
|
|
85
|
+
* Resolves the target path from the explicit `eventsPath` when a caller opted
|
|
86
|
+
* in (Sprint 14 monitoring / tests), otherwise from the store's own per-repo
|
|
87
|
+
* state dir — production never passes `eventsPath`, so defaulting is what makes
|
|
88
|
+
* the audit trail actually exist on a real device.
|
|
89
|
+
*/
|
|
90
|
+
export function emitDedupAudit(ctx, input) {
|
|
91
|
+
if (!ctx.auditEnabled)
|
|
92
|
+
return;
|
|
93
|
+
try {
|
|
94
|
+
const path = ctx.eventsPath ?? defaultEventsPath(ctx.stateDir);
|
|
95
|
+
logDedupAudit(path, {
|
|
96
|
+
type: "dedup_audit",
|
|
97
|
+
ts: new Date().toISOString(),
|
|
98
|
+
...input,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
/* instrumentation must never break the add() path */
|
|
103
|
+
}
|
|
104
|
+
}
|
package/dist/src/vectorStore.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* "./vectorStore.js" are unchanged.
|
|
9
9
|
*/
|
|
10
10
|
export { VectorStore } from "./vectorStore/class.js";
|
|
11
|
+
export { addCheckpoint } from "./vectorStore/add.js";
|
|
11
12
|
export { computeRegionHash } from "./vectorStore/hash.js";
|
|
12
13
|
export { L2_ENABLED, } from "./vectorStore/types.js";
|
|
13
14
|
// Re-exports (back-compat): existing call sites keep importing from "./vectorStore.js"
|
|
@@ -7,25 +7,10 @@
|
|
|
7
7
|
*
|
|
8
8
|
* PREVENT-011: no `any` type.
|
|
9
9
|
*/
|
|
10
|
+
import type { SettingSpec, SettingGroup } from "./routes-rag-settings-types.js";
|
|
11
|
+
import { VECTOR_CORTEX_SETTINGS } from "./routes-rag-settings-vector-cortex.js";
|
|
10
12
|
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Base metadata for a single setting entry before its live `value` is resolved.
|
|
14
|
-
* `category` and `value` are filled in at read time by the handler.
|
|
15
|
-
*/
|
|
16
|
-
export interface SettingSpec {
|
|
17
|
-
key: string;
|
|
18
|
-
label: string;
|
|
19
|
-
description: string;
|
|
20
|
-
type: "boolean" | "number" | "string";
|
|
21
|
-
default: string | number | boolean;
|
|
22
|
-
/** True when this is a `_DISABLED`-convention opt-out flag. */
|
|
23
|
-
disabledConvention: boolean;
|
|
24
|
-
requiresLlm: boolean;
|
|
25
|
-
unit?: string;
|
|
26
|
-
min?: number;
|
|
27
|
-
max?: number;
|
|
28
|
-
}
|
|
13
|
+
export type { SettingSpec } from "./routes-rag-settings-types.js";
|
|
29
14
|
|
|
30
15
|
// Shorthand builders to keep the inventory terse and unambiguous.
|
|
31
16
|
const boolFlag = (
|
|
@@ -96,10 +81,7 @@ const str = (
|
|
|
96
81
|
});
|
|
97
82
|
|
|
98
83
|
/** Every adjustable setting, grouped by category. Read-only after module load. */
|
|
99
|
-
export const SETTINGS: ReadonlyArray<
|
|
100
|
-
name: string;
|
|
101
|
-
settings: SettingSpec[];
|
|
102
|
-
}> = [
|
|
84
|
+
export const SETTINGS: ReadonlyArray<SettingGroup> = [
|
|
103
85
|
{
|
|
104
86
|
name: "RAG Pipeline",
|
|
105
87
|
settings: [
|
|
@@ -233,6 +215,12 @@ export const SETTINGS: ReadonlyArray<{
|
|
|
233
215
|
boolDirect("MEGACOMPACT_MARK_ONLY_L1", "Mark Only L1", "L1 runs but does not collapse", false),
|
|
234
216
|
boolDirect("MEGACOMPACT_MARK_ONLY_L2", "Mark Only L2", "L2 runs but does not collapse", false),
|
|
235
217
|
boolDirect("MEGACOMPACT_MINILM", "MiniLM Embedder", "Use MiniLM instead of trigram", false),
|
|
218
|
+
boolDirect(
|
|
219
|
+
"MEGACOMPACT_DEDUP_AUDIT",
|
|
220
|
+
"Dedup Audit Trail",
|
|
221
|
+
"Append one events.log line per tier decision (which layer collapsed a region, onto what, at what similarity) to tune the thresholds below. Pure instrumentation — dedup behavior is identical either way.",
|
|
222
|
+
true,
|
|
223
|
+
),
|
|
236
224
|
],
|
|
237
225
|
},
|
|
238
226
|
{
|
|
@@ -274,119 +262,7 @@ export const SETTINGS: ReadonlyArray<{
|
|
|
274
262
|
num("MEGACOMPACT_EMBEDDING_CHARS_PER_TOKEN", "Embedding Chars per Token", "Estimated characters per token used for embedder chunking size", 4, 1, 32),
|
|
275
263
|
],
|
|
276
264
|
},
|
|
277
|
-
|
|
278
|
-
name: "Vector Cortex",
|
|
279
|
-
settings: [
|
|
280
|
-
boolDirect(
|
|
281
|
-
"MEGACOMPACT_VC0A",
|
|
282
|
-
"VC0A Baseline Observability",
|
|
283
|
-
"Structured evaluation observer (MetricEventV1 + latency histogram). OFF = mode C, byte-identical to predecessor.",
|
|
284
|
-
true,
|
|
285
|
-
),
|
|
286
|
-
boolDirect(
|
|
287
|
-
"MEGACOMPACT_VC0B",
|
|
288
|
-
"VC0B Replay Correctness",
|
|
289
|
-
"ReplayCutV2 effective-cut (min of boundary-safe/commit/capture high-water + pair retreat + anchor floor) and M3 effective-cut-v2 migration. OFF = legacy capped replay, byte-identical.",
|
|
290
|
-
true,
|
|
291
|
-
),
|
|
292
|
-
boolDirect(
|
|
293
|
-
"MEGACOMPACT_VC1A",
|
|
294
|
-
"VC1A Canonical Byte Events",
|
|
295
|
-
"EventV2 byte-authority ledger codec (original bytes + SHA-256, strict UTF-8, derived NFC) and canonical validator (EVT_DIGEST_MISMATCH / EVT_UTF8_TAG_INVALID / EVT_DUPLICATE_ID). OFF = mode C, transcript codec unchanged, byte-identical.",
|
|
296
|
-
true,
|
|
297
|
-
),
|
|
298
|
-
boolDirect(
|
|
299
|
-
"MEGACOMPACT_VC1B",
|
|
300
|
-
"VC1B Occurrence Ledger + Tool Identity",
|
|
301
|
-
"Neutral occurrence ledger (LedgerReader/Writer/Admin + CompatJournalV1): per-session monotonic seq, tool result references one earlier call, uniqueness by (eventId,digest) only, and the M2 copy-validate-switch downgrade journal. OFF = mode C, ledger unwritten, byte-identical.",
|
|
302
|
-
true,
|
|
303
|
-
),
|
|
304
|
-
boolDirect(
|
|
305
|
-
"MEGACOMPACT_VC0C",
|
|
306
|
-
"VC0C Live Safety Envelope",
|
|
307
|
-
"TriadResult/Breaker live circuit breaker (60s window, 20 attempts, 30s cooldown, 3 probes, 5min healthy residence) + durable spool before provider invocation; manual reset clears cooldown but never evidence. OFF = mode C, unchanged transcript, byte-identical.",
|
|
308
|
-
true,
|
|
309
|
-
),
|
|
310
|
-
boolDirect(
|
|
311
|
-
"MEGACOMPACT_VC1C",
|
|
312
|
-
"VC1C Cross-Language Conformance v2",
|
|
313
|
-
"FixtureManifestV2 canonical manifest validator + DowngradeReport deterministic downgrade export + MinHashV2 exact big-integer signatures and the M4 copy/validate/switch minhash-v2 migration (seed table frozen, cross-language byte-exact). OFF = mode C, v1 sync dedup scan unchanged, byte-identical.",
|
|
314
|
-
true,
|
|
315
|
-
),
|
|
316
|
-
boolDirect(
|
|
317
|
-
"MEGACOMPACT_VC2A",
|
|
318
|
-
"VC2A Offline Model Runtime",
|
|
319
|
-
"ModelManifestV1 digest-before-load ONNX runtime (opset17/batch1/max512) + asset-free trigram demotion. Asset path assets/vector-cortex/encoder-v1 is immutable/digest-pinned. OFF = mode C, byte-identical to predecessor.",
|
|
320
|
-
true,
|
|
321
|
-
),
|
|
322
|
-
boolDirect(
|
|
323
|
-
"MEGACOMPACT_VC2B",
|
|
324
|
-
"VC2B Multi-Head Encoder",
|
|
325
|
-
"VectorSetV1 five L2-normalized heads (384/128/128/64/32) with head-calibration draft + asset-free trigram B (512d) and lexical C fallbacks, plus the per-head emit seam. OFF = mode C, no per-head vectors emitted, byte-identical predecessor.",
|
|
326
|
-
true,
|
|
327
|
-
),
|
|
328
|
-
boolDirect(
|
|
329
|
-
"MEGACOMPACT_VC2C",
|
|
330
|
-
"VC2C Encoder Qualification + Calibration",
|
|
331
|
-
"QualifiedEncoderV1/CalibrationV1: calibration fit on the calibration split only (held-out labels prohibited) + atomic selection across MODEL_ASSET and per-head EVALUATION thresholds (any field failure demotes all of A). OFF = mode C, no qualification/calibration selection, byte-identical predecessor.",
|
|
332
|
-
true,
|
|
333
|
-
),
|
|
334
|
-
boolDirect(
|
|
335
|
-
"MEGACOMPACT_VC3A",
|
|
336
|
-
"VC3A Cortex Store",
|
|
337
|
-
"Capability-gated derived cortex store (CortexReader/Writer/Admin + CortexRecordV1): additive, keyed (sourceHighWater, algorithmVersion, id), immutable records, deterministic generation rebuild + one root digest. OFF = mode C, no cortex records written, byte-identical predecessor.",
|
|
338
|
-
true,
|
|
339
|
-
),
|
|
340
|
-
boolDirect(
|
|
341
|
-
"MEGACOMPACT_VC3B",
|
|
342
|
-
"VC3B Deterministic Topology",
|
|
343
|
-
"Deterministic cortical topology (TopologyV1/EdgeV1): per-(source,head) top-k=16/head calibrated-threshold edges, stable score-desc/then-target-ID sort, dependency directed + contradiction symmetric paired records, one stable generation digest. OFF = mode C, no topology graph built/emitted, predecessor-precise topology view, byte-identical predecessor.",
|
|
344
|
-
true,
|
|
345
|
-
),
|
|
346
|
-
boolDirect(
|
|
347
|
-
"MEGACOMPACT_VC3C",
|
|
348
|
-
"VC3C Topology Query + Router Invalidation",
|
|
349
|
-
"TopologyQueryV1/RouterKeyV2 structured keys (length-delimited, unsigned-byte order, no prefix ambiguity), exact (session,generation) invalidation, stale-generation rejection (TOP_GENERATION_STALE), and the M6 router-generation-v2 copy/validate/switch migration. OFF = mode C, no structured router key / generation invalidation, byte-identical predecessor.",
|
|
350
|
-
true,
|
|
351
|
-
),
|
|
352
|
-
boolDirect(
|
|
353
|
-
"MEGACOMPACT_VC4A",
|
|
354
|
-
"VC4A Dual-Tier Shards",
|
|
355
|
-
"SemanticShardV1/ExactShardV1/ShardManifestV1: partition a session ONLY at complete EventV2 boundaries; exact shards preserve every tool call/result pair, anchor and invalid UTF-8 event as original bytes (pairs never split across exact shards); manifest enforces disjoint sorted ranges + complete protected-span coverage. OFF = mode C, exact anchors/current transcript only, byte-identical predecessor.",
|
|
356
|
-
true,
|
|
357
|
-
),
|
|
358
|
-
boolDirect(
|
|
359
|
-
"MEGACOMPACT_VC4B",
|
|
360
|
-
"VC4B Residual Basis Parity",
|
|
361
|
-
"Residual codec: orthonormal DCT-II basis + int16 block quantization + block-scoped exact correction stream + (9,6) Reed-Solomon parity shards with SHA-256 corruption detection; admission gates on encodedSize <= 95% of exact-compressed size. OFF = mode C, no residual artifact produced, byte-identical predecessor.",
|
|
362
|
-
true,
|
|
363
|
-
),
|
|
364
|
-
boolDirect(
|
|
365
|
-
"MEGACOMPACT_VC4C",
|
|
366
|
-
"VC4C Reconstruction Fidelity",
|
|
367
|
-
"Conservative closure + source-order assembly + reconstruction validator: recursively closes dependencies and whole tool pairs to a fixed point, resolves contradictions by retaining the later exact source resolution, assembles spans solely by source range, and rejects missing anchors / split pairs / digest mismatch / unresolved contradiction. Mandatory token estimate is content-only and handed unchanged to VC5A. OFF = mode C, no closure/validator, byte-identical predecessor (VC4B).",
|
|
368
|
-
true,
|
|
369
|
-
),
|
|
370
|
-
boolDirect(
|
|
371
|
-
"MEGACOMPACT_VC5A",
|
|
372
|
-
"VC5A PromptDagV1 + Budgeted Planner",
|
|
373
|
-
"Single-session DAG (PromptDagV1) + budgeted 0/1 portfolio planner: builds a stable Kahn-ordered DAG, computes the mandatory dependency/tool/anchor closure before optional selection, returns MANDATORY_CLOSURE_OVER_BUDGET with evidence preserved on overflow, and runs a utility-per-token portfolio that never exceeds the remaining budget. Framing is owned here, not in VC4C. OFF = byte-identical predecessor (VC4C).",
|
|
374
|
-
true,
|
|
375
|
-
),
|
|
376
|
-
boolDirect(
|
|
377
|
-
"MEGACOMPACT_VC5B",
|
|
378
|
-
"VC5B Validated Renderer + Provider Profiles",
|
|
379
|
-
"Validated prompt renderer: replays VC5A's stable Kahn order verbatim, preserves exact tool bytes (PREVENT-PI-002), places compacted context via the host before_agent_start prepend seam — never role:system (PREVENT-PI-003) — and SHA-256 hashes the entire canonical outbound request before provider invocation. Unknown provider/model cleanly bypasses to the predecessor prompt path. OFF = byte-identical predecessor (VC5A).",
|
|
380
|
-
true,
|
|
381
|
-
),
|
|
382
|
-
boolDirect(
|
|
383
|
-
"MEGACOMPACT_VC5C",
|
|
384
|
-
"VC5C Live Graduated Rollout",
|
|
385
|
-
"Live graduated rollout: deterministically hashes each session into a stable 10,000-bucket cohort and advances the exposure gate (1/5/25/50/100%) only after a 72h monotonic residency, a powered sample, >=10,000 events, and >=200 sessions — advancing ONE gate at a time. A hard causal/tool/anchor/exact failure freezes promotion and selects the pre-VC path. OFF = byte-identical predecessor (VC5B).",
|
|
386
|
-
true,
|
|
387
|
-
),
|
|
388
|
-
],
|
|
389
|
-
},
|
|
265
|
+
VECTOR_CORTEX_SETTINGS,
|
|
390
266
|
{
|
|
391
267
|
name: "Cost API",
|
|
392
268
|
settings: [
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dashboard-server/routes-rag-settings-types.ts — SETTINGS inventory contract.
|
|
3
|
+
*
|
|
4
|
+
* The shared shapes the settings inventory is built from. Extracted so the
|
|
5
|
+
* inventory can be split across sibling files (helpers.ts + the per-area groups)
|
|
6
|
+
* without either side importing the other's data — contract-first, per
|
|
7
|
+
* docs/ENGINEERING_PRACTICES.md.
|
|
8
|
+
*
|
|
9
|
+
* PREVENT-011: no `any` type.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Base metadata for a single setting entry before its live `value` is resolved.
|
|
14
|
+
* `category` and `value` are filled in at read time by the handler.
|
|
15
|
+
*/
|
|
16
|
+
export interface SettingSpec {
|
|
17
|
+
key: string;
|
|
18
|
+
label: string;
|
|
19
|
+
description: string;
|
|
20
|
+
type: "boolean" | "number" | "string";
|
|
21
|
+
default: string | number | boolean;
|
|
22
|
+
/** True when this is a `_DISABLED`-convention opt-out flag. */
|
|
23
|
+
disabledConvention: boolean;
|
|
24
|
+
requiresLlm: boolean;
|
|
25
|
+
unit?: string;
|
|
26
|
+
min?: number;
|
|
27
|
+
max?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One named category of settings as rendered by the Setup panel. */
|
|
31
|
+
export interface SettingGroup {
|
|
32
|
+
name: string;
|
|
33
|
+
settings: SettingSpec[];
|
|
34
|
+
}
|