pi-mega-compact 0.20.5 → 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.
Files changed (116) hide show
  1. package/dist/config/vector-cortex.js +12 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +3 -31
  4. package/dist/extensions/dashboard-server/routes-rag-settings-types.js +11 -0
  5. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +43 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-rollout.js +43 -0
  7. package/dist/extensions/dashboard-server/routes-vector-cortex.js +1 -0
  8. package/dist/extensions/dashboard-server/routes.js +1 -1
  9. package/dist/extensions/dashboard-server/server.js +3 -1
  10. package/dist/extensions/mega-runtime/vector-cortex-live.js +105 -0
  11. package/dist/src/config/dedup.js +1 -0
  12. package/dist/src/config/vector-cortex.js +12 -0
  13. package/dist/src/config.js +1 -1
  14. package/dist/src/dedup-audit.test-helpers.js +43 -0
  15. package/dist/src/monitoring.js +9 -0
  16. package/dist/src/vector-cortex/rollout/_acceptance-fixture.js +55 -0
  17. package/dist/src/vector-cortex/rollout/_acceptance-helpers.js +8 -0
  18. package/dist/src/vector-cortex/rollout/_acceptance-scenario.js +70 -0
  19. package/dist/src/vector-cortex/rollout/assign.js +56 -0
  20. package/dist/src/vector-cortex/rollout/emit.js +50 -0
  21. package/dist/src/vector-cortex/rollout/gate.js +75 -0
  22. package/dist/src/vector-cortex/rollout/types.js +39 -0
  23. package/dist/src/vectorStore/add-l0.js +108 -0
  24. package/dist/src/vectorStore/add-l1.js +35 -0
  25. package/dist/src/vectorStore/add.js +229 -0
  26. package/dist/src/vectorStore/class.js +15 -291
  27. package/dist/src/vectorStore/dedup-audit.js +104 -0
  28. package/dist/src/vectorStore.js +1 -0
  29. package/dist/vector-cortex/rollout/_acceptance-fixture.js +55 -0
  30. package/dist/vector-cortex/rollout/_acceptance-helpers.js +8 -0
  31. package/dist/vector-cortex/rollout/_acceptance-scenario.js +70 -0
  32. package/dist/vector-cortex/rollout/assign.js +56 -0
  33. package/dist/vector-cortex/rollout/emit.js +50 -0
  34. package/dist/vector-cortex/rollout/gate.js +75 -0
  35. package/dist/vector-cortex/rollout/types.js +39 -0
  36. package/extensions/dashboard-client/dist/assets/{AreaChart-CGL29Tcl.js → AreaChart-DqTbaSRA.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{AreaChart-CGL29Tcl.js.map → AreaChart-DqTbaSRA.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{BarChart-OxhalIZa.js → BarChart-BfNBeOvF.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{BarChart-OxhalIZa.js.map → BarChart-BfNBeOvF.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{CacheTab-VcMFwL-6.js → CacheTab-C9SOMYB5.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{CacheTab-VcMFwL-6.js.map → CacheTab-C9SOMYB5.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{EventsTab-DePofXDM.js → EventsTab-GsMKP10_.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{EventsTab-DePofXDM.js.map → EventsTab-GsMKP10_.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{HealthTab-nQd1tjSF.js → HealthTab-DAOCXwRP.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{HealthTab-nQd1tjSF.js.map → HealthTab-DAOCXwRP.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CzvA8-F6.js → MaintenanceTab-BtBeMkB5.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CzvA8-F6.js.map → MaintenanceTab-BtBeMkB5.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-3lxgWBvU.js → MemoryMapTab-DzndtgkZ.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-3lxgWBvU.js.map → MemoryMapTab-DzndtgkZ.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{MetricsTab-D_FcA6kN.js → MetricsTab-DyxJ4eb8.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{MetricsTab-D_FcA6kN.js.map → MetricsTab-DyxJ4eb8.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{OverviewTab-BU6R4aEs.js → OverviewTab-DCiEdVWR.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{OverviewTab-BU6R4aEs.js.map → OverviewTab-DCiEdVWR.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{ReposTab-DFjy1isz.js → ReposTab-B5SIqVHA.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{ReposTab-DFjy1isz.js.map → ReposTab-B5SIqVHA.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{SessionsTab-UGIzIH25.js → SessionsTab-DLWFJ9xI.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{SessionsTab-UGIzIH25.js.map → SessionsTab-DLWFJ9xI.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{SetupTab-CECrgMKI.js → SetupTab-CvGXZyej.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{SetupTab-CECrgMKI.js.map → SetupTab-CvGXZyej.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dyy4SCDk.js → TimeSavedCard-wZuQGxLS.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dyy4SCDk.js.map → TimeSavedCard-wZuQGxLS.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{TurnsTab-B0LPcVs1.js → TurnsTab-B7aOejch.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{TurnsTab-B0LPcVs1.js.map → TurnsTab-B7aOejch.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/VectorCortexTab-eHVt9yDx.js +2 -0
  65. package/extensions/dashboard-client/dist/assets/VectorCortexTab-eHVt9yDx.js.map +1 -0
  66. package/extensions/dashboard-client/dist/assets/{WikiTab-DWk9Qvut.js → WikiTab-DhWHjAtt.js} +2 -2
  67. package/extensions/dashboard-client/dist/assets/{WikiTab-DWk9Qvut.js.map → WikiTab-DhWHjAtt.js.map} +1 -1
  68. package/extensions/dashboard-client/dist/assets/{button-O59wPr5H.js → button-BrC-W87h.js} +2 -2
  69. package/extensions/dashboard-client/dist/assets/{button-O59wPr5H.js.map → button-BrC-W87h.js.map} +1 -1
  70. package/extensions/dashboard-client/dist/assets/{card-C-DxXv1-.js → card-0rgfRgr3.js} +2 -2
  71. package/extensions/dashboard-client/dist/assets/{card-C-DxXv1-.js.map → card-0rgfRgr3.js.map} +1 -1
  72. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Dw5YnE5s.js → generateCategoricalChart-DRresOQF.js} +2 -2
  73. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Dw5YnE5s.js.map → generateCategoricalChart-DRresOQF.js.map} +1 -1
  74. package/extensions/dashboard-client/dist/assets/{index-i9oaPE0a.js → index-DohmtZWL.js} +3 -3
  75. package/extensions/dashboard-client/dist/assets/{index-i9oaPE0a.js.map → index-DohmtZWL.js.map} +1 -1
  76. package/extensions/dashboard-client/dist/assets/{switch-B69QY3IM.js → switch-Bs8g_zB5.js} +2 -2
  77. package/extensions/dashboard-client/dist/assets/{switch-B69QY3IM.js.map → switch-Bs8g_zB5.js.map} +1 -1
  78. package/extensions/dashboard-client/dist/assets/{toggle-BJ4Kwggu.js → toggle-DVVauIo8.js} +2 -2
  79. package/extensions/dashboard-client/dist/assets/{toggle-BJ4Kwggu.js.map → toggle-DVVauIo8.js.map} +1 -1
  80. package/extensions/dashboard-client/dist/assets/{useSSE-BpuA8sPd.js → useSSE-DxH1PTAR.js} +2 -2
  81. package/extensions/dashboard-client/dist/assets/{useSSE-BpuA8sPd.js.map → useSSE-DxH1PTAR.js.map} +1 -1
  82. package/extensions/dashboard-client/dist/index.html +1 -1
  83. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  84. package/extensions/dashboard-client/src/tabs/VectorCortexRolloutCard.tsx +44 -0
  85. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +8 -0
  86. package/extensions/dashboard-client/src/types/vector-cortex.ts +17 -0
  87. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +32 -1
  88. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +11 -129
  89. package/extensions/dashboard-server/routes-rag-settings-types.ts +34 -0
  90. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +142 -0
  91. package/extensions/dashboard-server/routes-vector-cortex-rollout.ts +52 -0
  92. package/extensions/dashboard-server/routes-vector-cortex.ts +1 -0
  93. package/extensions/dashboard-server/routes.ts +1 -0
  94. package/extensions/dashboard-server/server.ts +2 -0
  95. package/extensions/mega-runtime/vector-cortex-live.ts +165 -0
  96. package/package.json +1 -1
  97. package/src/config/dedup.ts +9 -0
  98. package/src/config/vector-cortex.ts +13 -0
  99. package/src/config.ts +1 -0
  100. package/src/dedup-audit.test-helpers.ts +49 -0
  101. package/src/monitoring.ts +10 -0
  102. package/src/vector-cortex/rollout/_acceptance-fixture.ts +94 -0
  103. package/src/vector-cortex/rollout/_acceptance-helpers.ts +24 -0
  104. package/src/vector-cortex/rollout/_acceptance-scenario.ts +96 -0
  105. package/src/vector-cortex/rollout/assign.ts +67 -0
  106. package/src/vector-cortex/rollout/emit.ts +81 -0
  107. package/src/vector-cortex/rollout/gate.ts +119 -0
  108. package/src/vector-cortex/rollout/types.ts +111 -0
  109. package/src/vectorStore/add-l0.ts +152 -0
  110. package/src/vectorStore/add-l1.ts +57 -0
  111. package/src/vectorStore/add.ts +269 -0
  112. package/src/vectorStore/class.ts +17 -327
  113. package/src/vectorStore/dedup-audit.ts +199 -0
  114. package/src/vectorStore.ts +1 -0
  115. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BWi3u_gp.js +0 -2
  116. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BWi3u_gp.js.map +0 -1
@@ -0,0 +1,152 @@
1
+ /**
2
+ * add-l0.ts — the L0 exact-match tier of the dedup cascade.
3
+ *
4
+ * L0 is three exact-hash probes sharing one enable flag and one MARK_ONLY flag:
5
+ * 1. contentHash — normalized dual-hash, bloom-accelerated (Sprint 9/10)
6
+ * 2. regionHash — the legacy pre-normalization hash (backward-compat)
7
+ * 3. summaryHash — same-topic incremental compactions
8
+ *
9
+ * Split out of add.ts so both files stay under the 300-line src/ soft limit.
10
+ * The tier is a pure decision: it either produces a collapse (returning the
11
+ * matched result) or reports the fall-through, and it never writes a new
12
+ * checkpoint — that stays in add.ts.
13
+ *
14
+ * All three probes are hash comparisons, so none of them computes a similarity
15
+ * score and none is invented for the audit trail.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import type { StoredCheckpoint } from "../store.js";
19
+ import type { ContentDigest } from "../dedup/digest.js";
20
+ import { upsertCheckpoint, addTokensSaved, bumpDedupStats } from "../store/sqlite.js";
21
+ import type { BloomFilter } from "../store/bloom.js";
22
+ import type { DedupAuditRecorder } from "./dedup-audit.js";
23
+ import type { AddInput, AddResult } from "./types.js";
24
+ import type { VectorStore } from "./class.js";
25
+
26
+ /** Everything the L0 tier needs from the enclosing add() cascade. */
27
+ export interface L0Context {
28
+ store: VectorStore;
29
+ input: AddInput;
30
+ /** Checkpoints already stored for this session. */
31
+ all: StoredCheckpoint[];
32
+ /** Normalized content digest of the incoming region. */
33
+ digest: ContentDigest;
34
+ /** Legacy region hash of the incoming region. */
35
+ regionHash: string;
36
+ /** SHA-256 of the topic summary, when one was supplied. */
37
+ summaryHash?: string;
38
+ /** Tokens the original region occupied (the dedup "saved" base). */
39
+ origTokens: number;
40
+ /** Warm bloom accelerator for the content-hash probe. */
41
+ bloom: BloomFilter;
42
+ /** Cascade start time, for the monitoring latency figure. */
43
+ t0: number;
44
+ audit: DedupAuditRecorder;
45
+ }
46
+
47
+ /**
48
+ * Outcome of the L0 tier.
49
+ *
50
+ * `result` set → the tier collapsed the region and add() returns immediately.
51
+ * `markOnly` set → a probe matched but MARK_ONLY policy said store anyway, so
52
+ * the cascade continues and records the mark at the end.
53
+ */
54
+ export interface L0Outcome {
55
+ result?: AddResult;
56
+ markOnly: "L0" | null;
57
+ }
58
+
59
+ /** Run the L0 exact-match tier. */
60
+ export function runL0Tier(ctx: L0Context): L0Outcome {
61
+ const { store, input, all, digest, regionHash, origTokens, bloom, t0, audit } = ctx;
62
+ const cfg = store.cfg;
63
+ const onTier = input.onTier;
64
+ let markOnly: "L0" | null = null;
65
+
66
+ // 0. Content-hash dedup (Sprint 9) — catches identical content arriving under
67
+ // different regionText. Normalization handles case/whitespace/ANSI so
68
+ // variants collapse to one row. Dual-hash guards a single-hash collision.
69
+ // Sprint 10: bloom is the accelerator — a miss means "definitely new" and
70
+ // skips the scan; a hit is only a candidate, confirmed against `all` here.
71
+ // MARK_ONLY_L0 records the decision but does not collapse.
72
+ onTier?.({ tier: "L0", status: "scanning" });
73
+ if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
74
+ const contentMatch = all.find(
75
+ (cp) =>
76
+ cp.contentHash === digest.contentHash &&
77
+ cp.contentHash2 === digest.contentHash2,
78
+ );
79
+ if (contentMatch) {
80
+ if (cfg.MARK_ONLY_L0) {
81
+ markOnly = "L0"; // Record-but-don't-collapse: fall through.
82
+ } else {
83
+ contentMatch.timestamp = input.timestamp;
84
+ upsertCheckpoint(contentMatch, store.stateDir);
85
+ bumpDedupStats(true, store.stateDir);
86
+ // Deduped: whole original region discarded, nothing new stored.
87
+ addTokensSaved(origTokens, store.stateDir);
88
+ store.record("L0", "deduped", "contentHash", Date.now() - t0, 1, contentMatch.checkpointId);
89
+ audit.deduped("L0", contentMatch.checkpointId, "contentHash");
90
+ onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
91
+ return {
92
+ result: { checkpoint: contentMatch, deduped: true, reason: "contentHash" },
93
+ markOnly,
94
+ };
95
+ }
96
+ }
97
+ }
98
+
99
+ // 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
100
+ if (cfg.L0_ENABLED) {
101
+ const regionMatch = all.find((cp) => cp.regionHash === regionHash);
102
+ if (regionMatch) {
103
+ if (cfg.MARK_ONLY_L0) {
104
+ markOnly = "L0"; // fall through
105
+ } else {
106
+ bumpDedupStats(true, store.stateDir);
107
+ // Deduped: whole original region discarded, nothing new stored.
108
+ addTokensSaved(origTokens, store.stateDir);
109
+ store.record("L0", "deduped", "regionHash", Date.now() - t0, 1, regionMatch.checkpointId);
110
+ audit.deduped("L0", regionMatch.checkpointId, "regionHash");
111
+ onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
112
+ return {
113
+ result: { checkpoint: regionMatch, deduped: true, reason: "regionHash" },
114
+ markOnly,
115
+ };
116
+ }
117
+ }
118
+ }
119
+
120
+ // 2. SummaryHash dedup — catches same-topic incremental compactions.
121
+ if (ctx.summaryHash && cfg.L0_ENABLED) {
122
+ const summaryMatch = all.find((cp) => cp.summaryHash === ctx.summaryHash);
123
+ if (summaryMatch) {
124
+ if (cfg.MARK_ONLY_L0) {
125
+ markOnly = "L0"; // fall through
126
+ } else {
127
+ summaryMatch.timestamp = input.timestamp;
128
+ upsertCheckpoint(summaryMatch, store.stateDir);
129
+ bumpDedupStats(true, store.stateDir);
130
+ // Deduped: whole original region discarded, nothing new stored.
131
+ addTokensSaved(origTokens, store.stateDir);
132
+ store.record("L0", "deduped", "summaryHash", Date.now() - t0, 1, summaryMatch.checkpointId);
133
+ audit.deduped("L0", summaryMatch.checkpointId, "summaryHash");
134
+ onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
135
+ return {
136
+ result: { checkpoint: summaryMatch, deduped: true, reason: "summaryHash" },
137
+ markOnly,
138
+ };
139
+ }
140
+ }
141
+ }
142
+ // L0 did not collapse this region.
143
+ onTier?.({ tier: "L0", status: "passed" });
144
+ return { markOnly };
145
+ }
146
+
147
+ /** SHA-256 of the topic summary (full 64-hex; 16-hex was collision-prone). */
148
+ export function computeSummaryHash(topicSummary?: string): string | undefined {
149
+ return topicSummary
150
+ ? createHash("sha256").update(topicSummary).digest("hex")
151
+ : undefined;
152
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * add-l1.ts — the L1 MinHash/LSH near-duplicate lookup.
3
+ *
4
+ * Split out of add.ts to keep both files under the 300-line src/ soft limit.
5
+ * L1 catches the one-word edits and rewordings L0's exact hashes miss: a cheap
6
+ * LSH bucket retrieval narrows the field, then a trigram verification
7
+ * (pg_trgm-equivalent) is the final gate. The verify is boolean, so the tier
8
+ * produces no similarity score.
9
+ */
10
+ import type { StoredCheckpoint } from "../store.js";
11
+ import {
12
+ minhashSignature,
13
+ SIGNATURE_VERSION,
14
+ NUM_HASHES,
15
+ } from "../dedup/l1-minhash.js";
16
+ import { lshBands } from "../dedup/l1-lsh.js";
17
+ import { isNearDuplicate } from "../dedup/l1-verify.js";
18
+ import { lshCandidateChunks } from "../store/sqlite.js";
19
+ import type { VectorStore } from "./class.js";
20
+
21
+ export /**
22
+ * L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
23
+ * Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
24
+ * and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
25
+ */
26
+ function findL1Duplicate(
27
+ store: VectorStore,
28
+ sessionId: string,
29
+ regionText: string,
30
+ all: StoredCheckpoint[],
31
+ ): StoredCheckpoint | undefined {
32
+ if (all.length === 0) return undefined;
33
+ const sig = minhashSignature(regionText);
34
+ if (sig.length !== NUM_HASHES) return undefined;
35
+ const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
36
+ // Cheap candidate retrieval (single query, capped). Exclude nothing yet —
37
+ // the new checkpoint has no id, so pass a sentinel that never matches.
38
+ const candidateIds = lshCandidateChunks(
39
+ bands,
40
+ sessionId,
41
+ "__new__",
42
+ store.stateDir,
43
+ 100,
44
+ );
45
+ if (candidateIds.length === 0) return undefined;
46
+ const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
47
+ const VERIFY_BUDGET_MS = 20;
48
+ const start = Date.now();
49
+ for (const id of candidateIds) {
50
+ if (Date.now() - start > VERIFY_BUDGET_MS) break; // QA #15: abort → "not dup"
51
+ const cand = byId.get(id);
52
+ if (!cand) continue;
53
+ const candText = cand.normalizedText ?? cand.summary ?? "";
54
+ if (isNearDuplicate(regionText, candText)) return cand;
55
+ }
56
+ return undefined;
57
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * add.ts — the dedup cascade behind VectorStore.add() (extracted from class.ts).
3
+ *
4
+ * Free function taking the store as its first argument, matching the sibling
5
+ * pattern used by vector-read.ts / vector-search.ts / vector-dedup.ts: the
6
+ * store's fields are package-public by design (see the comment in class.ts) so
7
+ * the helpers can read them without casts, and class.ts stays a thin shell.
8
+ *
9
+ * Cascade order (unchanged by the extraction):
10
+ * 1. L0 contentHash exact match (bloom-accelerated)
11
+ * 2. L0 legacy regionHash exact match (backward-compat)
12
+ * 3. L0 summaryHash exact match (same-topic incremental compactions)
13
+ * 4. L1 MinHash/LSH near-duplicate
14
+ * 5. L2 cosine similarity >= threshold
15
+ * 6. None matched → create a new checkpoint
16
+ *
17
+ * Sprint-14 monitoring (`store.record`) and the live `onTier` UI hook are
18
+ * untouched. The dedup audit trail (external-audit item #2) is layered on top as
19
+ * PURE instrumentation: every emit is best-effort and flag-gated, so a flag-off
20
+ * or a failing write leaves the dedup outcome byte-identical.
21
+ */
22
+ import { cosineSimilarity } from "../embedder.js";
23
+ import type { StoredCheckpoint } from "../store.js";
24
+ import { normalizeSessionId, compressSmart } from "../store.js";
25
+ import { computeContentDigest } from "../dedup/digest.js";
26
+ import { minhashSignature, SIGNATURE_VERSION } from "../dedup/l1-minhash.js";
27
+ import { lshBands } from "../dedup/l1-lsh.js";
28
+ import { openBloom, saveBloom } from "../store/bloom.js";
29
+ import {
30
+ listCheckpoints,
31
+ nextCheckpointId,
32
+ upsertCheckpoint,
33
+ loadSessionState,
34
+ saveSessionState,
35
+ upsertMinhashSignature,
36
+ insertLshBuckets,
37
+ addTokensSaved,
38
+ bumpDedupStats,
39
+ } from "../store/sqlite.js";
40
+ import { computeRegionHash } from "./hash.js";
41
+ import { runL0Tier, computeSummaryHash } from "./add-l0.js";
42
+ import { findL1Duplicate } from "./add-l1.js";
43
+ import { dedupAuditRecorder } from "./dedup-audit.js";
44
+ import type { VectorStore } from "./class.js";
45
+ import type { AddInput, AddResult } from "./types.js";
46
+
47
+ /**
48
+ * Add a checkpoint, running the full dedup cascade.
49
+ *
50
+ * Returns the matched checkpoint with `deduped: true` when a tier collapsed the
51
+ * region, otherwise the newly created checkpoint with `deduped: false`.
52
+ */
53
+ export function addCheckpoint(store: VectorStore, input: AddInput): AddResult {
54
+ const t0 = Date.now();
55
+ const sessionId = normalizeSessionId(input.sessionId);
56
+ const regionHash = computeRegionHash(input.regionText);
57
+ const all = listCheckpoints(sessionId, store.stateDir);
58
+ // Honest "tokens saved" base for this region. For a deduped add the whole
59
+ // original region is discarded (nothing new stored); for a new checkpoint
60
+ // we persist (orig − stored). Falls back to stored when orig is unknown.
61
+ const origTokens = input.originalTokenEstimate ?? input.tokenEstimate ?? 0;
62
+ const cfg = store.cfg;
63
+ // Live per-tier progress hook (Phase 1). Sync + optional; fired at each tier
64
+ // so the UI can paint "L0 ✓ → L1 ✓ → L2 0.91 → stored" during a compaction.
65
+ const onTier = input.onTier;
66
+ // Durable decision trail (external-audit item #2). Bound to this one cascade
67
+ // so each call site is a single line; a no-op when cfg.DEDUP_AUDIT is off.
68
+ const audit = dedupAuditRecorder(
69
+ {
70
+ stateDir: store.stateDir,
71
+ eventsPath: store.eventsPath,
72
+ auditEnabled: cfg.DEDUP_AUDIT,
73
+ },
74
+ {
75
+ sessionId,
76
+ originalTokenEstimate: input.originalTokenEstimate,
77
+ tokenEstimate: input.tokenEstimate,
78
+ },
79
+ );
80
+ // Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
81
+ // and which tier.
82
+ let markOnly: "L0" | "L1" | "L2" | null = null;
83
+
84
+ // L0 exact-match tier (contentHash / regionHash / summaryHash) — see add-l0.ts.
85
+ const digest = computeContentDigest(input.regionText);
86
+ const bloom = openBloom(store.stateDir);
87
+ const summaryHash = computeSummaryHash(input.topicSummary);
88
+ const l0 = runL0Tier({
89
+ store,
90
+ input,
91
+ all,
92
+ digest,
93
+ regionHash,
94
+ summaryHash,
95
+ origTokens,
96
+ bloom,
97
+ t0,
98
+ audit,
99
+ });
100
+ if (l0.result) return l0.result;
101
+ if (l0.markOnly) markOnly = l0.markOnly;
102
+
103
+ // 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
104
+ // edits / rewordings that L0's exact hash misses. Cheap LSH bucket
105
+ // retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
106
+ // Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
107
+ onTier?.({ tier: "L1", status: "scanning" });
108
+ if (cfg.L1_ENABLED) {
109
+ const l1 = findL1Duplicate(store, sessionId, input.regionText, all);
110
+ if (l1 && !cfg.MARK_ONLY_L1) {
111
+ l1.timestamp = input.timestamp;
112
+ upsertCheckpoint(l1, store.stateDir);
113
+ bumpDedupStats(true, store.stateDir);
114
+ const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
115
+ store.record("L1", "deduped", "l1MinHash", Date.now() - t0, 1, l1.checkpointId);
116
+ // Verify tier: the trigram gate is a boolean, so no score is invented.
117
+ audit.deduped("L1", l1.checkpointId, "l1MinHash");
118
+ onTier?.({ tier: "L1", status: "deduped", detail: "l1MinHash" });
119
+ return r;
120
+ }
121
+ if (l1 && cfg.MARK_ONLY_L1) markOnly = "L1";
122
+ }
123
+ onTier?.({ tier: "L1", status: "passed" });
124
+
125
+ // 3. L2 semantic dedup — catches near-identical / semantically-similar regions
126
+ // via cosine over the embedding. topicSummary is used for summaryHash dedup
127
+ // (tier 2); the vector index is keyed on the original region for backward-
128
+ // compat search semantics. Threshold from cfg (L2_COSINE trigram honest
129
+ // firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
130
+ // degrade to "store without dedup this pass" so we never lose a checkpoint.
131
+ // Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
132
+ const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
133
+ const simThreshold = store.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
134
+ const embedding = store.embedder.embed(input.regionText);
135
+ onTier?.({ tier: "L2", status: "scanning" });
136
+ if (cfg.L2_ENABLED && all.length > 0) {
137
+ const start = Date.now();
138
+ let timedOut = false;
139
+ const nearest = all.reduce(
140
+ (best, cp) => {
141
+ if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS)
142
+ timedOut = true;
143
+ if (timedOut) return best;
144
+ const sim = cosineSimilarity(embedding, cp.embedding);
145
+ return sim > best.sim ? { checkpoint: cp, sim } : best;
146
+ },
147
+ { checkpoint: all[0], sim: -1 },
148
+ );
149
+ if (!timedOut && nearest.sim >= simThreshold) {
150
+ if (!cfg.MARK_ONLY_L2) {
151
+ // Near-identical — update timestamp on existing checkpoint
152
+ nearest.checkpoint.timestamp = input.timestamp;
153
+ upsertCheckpoint(nearest.checkpoint, store.stateDir);
154
+ bumpDedupStats(true, store.stateDir);
155
+ // Deduped: whole original region discarded, nothing new stored.
156
+ addTokensSaved(origTokens, store.stateDir);
157
+ const r = {
158
+ checkpoint: nearest.checkpoint,
159
+ deduped: true,
160
+ reason: "contentSimilarity",
161
+ };
162
+ store.record("L2", "deduped", "contentSimilarity", Date.now() - t0, nearest.sim, nearest.checkpoint.checkpointId);
163
+ // The real cosine that cleared the threshold — the tuning datum.
164
+ audit.deduped(
165
+ "L2",
166
+ nearest.checkpoint.checkpointId,
167
+ "contentSimilarity",
168
+ nearest.sim,
169
+ );
170
+ onTier?.({
171
+ tier: "L2",
172
+ status: "deduped",
173
+ detail: nearest.sim.toFixed(2),
174
+ });
175
+ return r;
176
+ }
177
+ markOnly = "L2";
178
+ }
179
+ onTier?.({
180
+ tier: "L2",
181
+ status: "passed",
182
+ detail: `best ${nearest.sim.toFixed(2)}`,
183
+ });
184
+ // Near-miss: how close did we come to collapsing? Only emitted when the
185
+ // scan actually completed and scored a candidate — a timed-out scan has no
186
+ // honest best to report.
187
+ if (!timedOut && nearest.sim >= 0) {
188
+ audit.passed("L2", nearest.checkpoint.checkpointId, nearest.sim);
189
+ }
190
+ }
191
+
192
+ // 4. Genuinely new — create checkpoint
193
+ const checkpointId = nextCheckpointId(sessionId, store.stateDir);
194
+ const checkpoint: StoredCheckpoint = {
195
+ checkpointId,
196
+ sessionId,
197
+ repoId: store.repoId,
198
+ summary: input.summary,
199
+ topicSummary: input.topicSummary,
200
+ summaryHash,
201
+ keyDecisions: input.keyDecisions ?? [],
202
+ nextSteps: input.nextSteps ?? [],
203
+ filesModified: input.filesModified ?? [],
204
+ tokenEstimate: input.tokenEstimate ?? 0,
205
+ originalTokenEstimate: input.originalTokenEstimate,
206
+ regionHash,
207
+ contentHash: digest.contentHash,
208
+ contentHash2: digest.contentHash2,
209
+ contentHashVersion: digest.contentHashVersion,
210
+ normalizedText: digest.normalizedText,
211
+ compressedOriginal: compressSmart(
212
+ Buffer.from(input.regionText, "utf-8"),
213
+ input.compressionPressure,
214
+ ),
215
+ embedding,
216
+ timestamp: input.timestamp,
217
+ };
218
+ // Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
219
+ // idempotent-by-id semantics the old JSON append implied.
220
+ upsertCheckpoint(checkpoint, store.stateDir);
221
+ // Cumulative "tokens saved" counter (per-repo SQLite meta). For a NEW
222
+ // checkpoint the saved amount is (original − stored); for a deduped add the
223
+ // whole original region is discarded (handled in the deduped return paths
224
+ // above). Survives sessions and travels with the repo.
225
+ const stored = input.tokenEstimate ?? 0;
226
+ addTokensSaved(Math.max(0, origTokens - stored), store.stateDir);
227
+ // L1: persist this checkpoint's MinHash signature + LSH buckets so future
228
+ // near-duplicate inserts can find it. Deterministic given the seed.
229
+ const sig = minhashSignature(input.regionText);
230
+ upsertMinhashSignature(
231
+ checkpointId,
232
+ sessionId,
233
+ SIGNATURE_VERSION,
234
+ sig,
235
+ store.stateDir,
236
+ );
237
+ insertLshBuckets(
238
+ checkpointId,
239
+ sessionId,
240
+ SIGNATURE_VERSION,
241
+ lshBands(sig, sessionId, SIGNATURE_VERSION),
242
+ store.stateDir,
243
+ );
244
+ // Bloom accelerator: record the new content_hash so a future add() can short-
245
+ // circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
246
+ bloom.add(digest.contentHash);
247
+ saveBloom(store.stateDir);
248
+
249
+ // Track the region hash in session state for fast sentinel checks.
250
+ const state = loadSessionState(sessionId, store.stateDir);
251
+ if (!state.storedRegionHashes.includes(regionHash)) {
252
+ state.storedRegionHashes.push(regionHash);
253
+ saveSessionState(sessionId, state, store.stateDir);
254
+ }
255
+ // A new checkpoint. If a tier matched while MARK_ONLY, record that (the
256
+ // decision fired but we intentionally did not collapse).
257
+ if (markOnly) {
258
+ store.record(markOnly, "mark_only", "mark_only", Date.now() - t0);
259
+ } else {
260
+ store.record("L0", "new", undefined, Date.now() - t0);
261
+ }
262
+ // Final outcome. `mark_only` distinguishes "a tier matched but policy said
263
+ // store anyway" from a genuinely novel region.
264
+ audit.stored(checkpointId, markOnly ? "mark_only" : "new", stored);
265
+ // Cumulative store-wide dedup accounting (attempt, not collapsed).
266
+ bumpDedupStats(false, store.stateDir);
267
+ onTier?.({ tier: "new", status: "stored" });
268
+ return { checkpoint, deduped: false };
269
+ }