@spike1292/claude-memory 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/hooks/distill-session.mjs +74 -0
  4. package/hooks/graph-staleness-check.mjs +25 -0
  5. package/hooks/hooks.json +94 -0
  6. package/hooks/insights-surface.mjs +48 -0
  7. package/hooks/lib/distill-session.mjs +1560 -0
  8. package/hooks/lib/dupe-report.mjs +61 -0
  9. package/hooks/lib/env-shell.mjs +92 -0
  10. package/hooks/lib/graph-staleness-check.mjs +394 -0
  11. package/hooks/lib/hook-io.mjs +715 -0
  12. package/hooks/lib/insights-surface.mjs +165 -0
  13. package/hooks/lib/memory-link-lint.mjs +499 -0
  14. package/hooks/lib/memory-recall.mjs +219 -0
  15. package/hooks/lib/omp.mjs +103 -0
  16. package/hooks/lib/opencode.mjs +231 -0
  17. package/hooks/lib/paths.mjs +452 -0
  18. package/hooks/lib/semantic-index-refresh.mjs +155 -0
  19. package/hooks/lib/validate-note.mjs +218 -0
  20. package/hooks/lib/vault-env.sh +110 -0
  21. package/hooks/memory-link-lint.mjs +65 -0
  22. package/hooks/memory-recall.mjs +251 -0
  23. package/hooks/semantic-index-refresh.mjs +23 -0
  24. package/hooks/session-context.mjs +9 -0
  25. package/hooks/validate-note.mjs +52 -0
  26. package/hooks/vault-memory-sync.sh +154 -0
  27. package/omp/index.js +1 -0
  28. package/opencode/index.js +1 -0
  29. package/package.json +51 -4
  30. package/scripts/claude-memory.mjs +31 -0
  31. package/scripts/doctor-perf.mjs +121 -0
  32. package/scripts/doctor.sh +558 -0
  33. package/scripts/env.mjs +6 -0
  34. package/scripts/lib/claude-memory.mjs +168 -0
  35. package/scripts/lib/doctor-perf.mjs +434 -0
  36. package/scripts/lib/hook-stats.mjs +864 -0
  37. package/scripts/lib/lexical.mjs +85 -0
  38. package/scripts/lib/memory-adopt.mjs +69 -0
  39. package/scripts/lib/memory-audit-checks.mjs +344 -0
  40. package/scripts/lib/memory-eval.mjs +381 -0
  41. package/scripts/lib/memory-mark.mjs +135 -0
  42. package/scripts/lib/memory-mcp.mjs +142 -0
  43. package/scripts/lib/memory-merge.mjs +316 -0
  44. package/scripts/lib/memory-mine.mjs +108 -0
  45. package/scripts/lib/memory-promote.mjs +207 -0
  46. package/scripts/lib/memory-prune.mjs +84 -0
  47. package/scripts/lib/memory-semantic.mjs +999 -0
  48. package/scripts/lib/memory-setup.mjs +170 -0
  49. package/scripts/lib/memory-synth-vault.mjs +538 -0
  50. package/scripts/lib/model-default.mjs +7 -0
  51. package/scripts/lib/models.mjs +58 -0
  52. package/scripts/lib/prune-logs.mjs +130 -0
  53. package/scripts/lib/recall-stats.mjs +354 -0
  54. package/scripts/lib/share-modules.mjs +70 -0
  55. package/scripts/lib/slim-install.mjs +162 -0
  56. package/scripts/lib/vault-mcp.mjs +405 -0
  57. package/scripts/memory-adopt.mjs +160 -0
  58. package/scripts/memory-audit-checks.mjs +375 -0
  59. package/scripts/memory-eval.mjs +753 -0
  60. package/scripts/memory-mark.mjs +39 -0
  61. package/scripts/memory-mcp.mjs +35 -0
  62. package/scripts/memory-merge.mjs +55 -0
  63. package/scripts/memory-prune.mjs +44 -0
  64. package/scripts/memory-semantic.mjs +1192 -0
  65. package/scripts/memory-setup.mjs +33 -0
  66. package/scripts/memory-synth-vault.mjs +251 -0
  67. package/scripts/prune-logs.mjs +42 -0
  68. package/scripts/share-modules.mjs +79 -0
  69. package/scripts/slim-install.mjs +55 -0
  70. package/scripts/vault-mcp.mjs +50 -0
  71. package/stubs/onnxruntime-web/index.mjs +11 -0
  72. package/stubs/onnxruntime-web/package.json +12 -0
  73. package/stubs/sharp/index.mjs +11 -0
  74. package/stubs/sharp/package.json +12 -0
@@ -0,0 +1,999 @@
1
+ #!/usr/bin/env node
2
+ // Semantic (vector) search over the vault — the paraphrase bridge that FTS5 cannot be.
3
+ //
4
+ // Why: ctx_search is BM25 over FTS5, keyword-only, and misses paraphrases that share no
5
+ // distinctive term. Query expansion was tried and rejected — it depends on the agent remembering
6
+ // to expand. Full rationale and the rejected-alternative measurement:
7
+ // docs/decisions/2026-08-15-model-choice.md.
8
+ //
9
+ // Local by construction: the model runs on-machine via onnxruntime. The vault holds PRIVATE notes
10
+ // (roster, KIDs, PI priorities) — nothing leaves the machine after the one-time model fetch.
11
+ //
12
+ // Model choice: DEFAULT bge-m3 (cls pooling, batch 1, alias chunks) — see the export below for
13
+ // why it's the default, and docs/decisions/2026-08-15-model-choice.md for the full EN/NL
14
+ // comparison against bge-small-en and e5-multi. Wrong pooling is silent (CLAUDE.md "Model
15
+ // profiles are not interchangeable").
16
+ //
17
+ // Usage: CLAUDE.md's "Exercising the real pipeline" section (--index/--query/--dupes/--clusters).
18
+ //
19
+ // ponytail: linear cosine scan over a few thousand 384-d vectors is ~5ms. No ANN index, no server.
20
+
21
+ import crypto from 'node:crypto';
22
+ import fs from 'node:fs';
23
+ import net from 'node:net';
24
+ import path from 'node:path';
25
+ import { activeModel } from './model-default.mjs';
26
+ // The profiles moved out on 2026-08-20 so a caller wanting only the key list is not taken down by
27
+ // this module's exit-on-unknown-model. Their comments went with them — the batch-size-is-1 finding
28
+ // and the per-model pooling and dupeMin warnings are in models.mjs, not lost.
29
+ import { MODELS } from './models.mjs';
30
+ // The lexical vocabulary lives in its own import-free module because the recall hook needs it ABOVE
31
+ // its fail-open try, and this module's scope exits the process on an unknown model. Consumers
32
+ // import it from there directly — the re-export that used to sit here was deleted 2026-08-19: a
33
+ // second import path for one implementation is a second thing to keep in step.
34
+ import { CARD, lexTokens, bm25, SUPERSEDED_BY, SUPERSEDED_MARKER } from './lexical.mjs';
35
+
36
+ /** @typedef {{ note: string, layer: string, heading: string, text: string, file?: string, name?: string, project?: string, mtime?: number }} ResultRow */
37
+ /** @typedef {ResultRow & { vec: Uint8Array }} ChunkRow */
38
+ /** @typedef {ResultRow & { toks: string[] }} LexDoc */
39
+ /** @typedef {{ r: ResultRow, s: number }} Scored */
40
+ /**
41
+ * @template {ResultRow} [T=ChunkRow]
42
+ * @typedef {object} Bundle
43
+ * @property {string} slug
44
+ * @property {string} dbPath
45
+ * @property {readonly T[]} rowsUsed
46
+ * @property {LexDoc[]} lexDocs
47
+ * @property {Map<string, string>} cardByNote
48
+ * @property {Set<ResultRow>} [superseded] rows and lexDocs whose text carries the inline marker
49
+ * @property {number} loadedAt
50
+ */
51
+
52
+ // Which sibling servers should this one evict? Anything else under run/ is a leftover (CLAUDE.md's
53
+ // "One --serve for the whole machine, keyed by MODEL"). Sockets are the registry — no pidfile, no
54
+ // lock, nothing to leave stale.
55
+ // ponytail: last-writer-wins, no coordination. Two servers starting at once can evict each other and
56
+ // both die; the next prompt respawns one. Needs a lock only if that is ever observed.
57
+ /**
58
+ * @param {readonly string[]} names
59
+ * @param {string} ownName
60
+ * @returns {string[]}
61
+ */
62
+ export function evictableSockets(names, ownName) {
63
+ return names.filter((n) => n !== ownName && n.startsWith('search-') && n.endsWith('.sock'));
64
+ }
65
+
66
+ export const QUIT = { quit: 1 };
67
+
68
+ /**
69
+ * A lazily-loaded value that is loaded AT MOST ONCE at a time, and can be taken back out.
70
+ *
71
+ * `if (!x) x = await load()` is a check-then-act across an await: two requests arriving after an
72
+ * unload would both load, with the second silently dropping the first ~1.3GB onnxruntime session
73
+ * (no dispose() — the leak this exists to prevent). `get()` shares the in-flight promise so N
74
+ * concurrent callers cause ONE load; `take()` returns null while a load is in flight and lets that
75
+ * load land instead of racing it.
76
+ *
77
+ * @template T
78
+ * @param {() => Promise<T>} load
79
+ */
80
+ export function singleFlight(load) {
81
+ /** @type {T | null} */
82
+ let value = null;
83
+ /** @type {Promise<T> | null} */
84
+ let inFlight = null;
85
+ let borrowed = 0;
86
+ return {
87
+ get() {
88
+ if (value) return Promise.resolve(value);
89
+ if (!inFlight)
90
+ inFlight = load().then(
91
+ (v) => {
92
+ value = v;
93
+ inFlight = null;
94
+ return v;
95
+ },
96
+ (e) => {
97
+ inFlight = null;
98
+ throw e;
99
+ },
100
+ );
101
+ return inFlight;
102
+ },
103
+ /**
104
+ * Hold the value for the duration of `use`, so `take()` cannot pull it out mid-flight — an idle
105
+ * timer calling take() -> dispose() while inference still runs on that session would free it
106
+ * underneath native code (a crash, not a wrong answer).
107
+ *
108
+ * @template R
109
+ * @param {(v: T) => R | Promise<R>} use
110
+ * @returns {Promise<R>}
111
+ */
112
+ async borrow(use) {
113
+ const v = await this.get();
114
+ borrowed++;
115
+ try {
116
+ return await use(v);
117
+ } finally {
118
+ borrowed--;
119
+ }
120
+ },
121
+ /**
122
+ * In use right now? `take()` refuses while it is. Callers own the retry — the server re-arms
123
+ * its idle timer on a refusal, because nothing else would: only a new connection re-arms it.
124
+ */
125
+ busy() {
126
+ return borrowed > 0;
127
+ },
128
+ take() {
129
+ if (borrowed > 0) return null;
130
+ const v = value;
131
+ value = null;
132
+ return v;
133
+ },
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Per-key cache that reloads when the source has been written since it was loaded.
139
+ * `mtimeMs <= entry.loadedAt` must be written in that direction — a NaN (a failed stat) then falls
140
+ * through to a RELOAD rather than serving a cached index forever; the other order reads identically
141
+ * and is wrong. Entries are never evicted: an index is ~15MB against the ~1.3GB model, so the
142
+ * process idle timer already bounds how long they live.
143
+ *
144
+ * @template {{ loadedAt: number }} T
145
+ * @param {(key: string) => T} load
146
+ */
147
+ export function mtimeCache(load) {
148
+ /** @type {Map<string, T>} */
149
+ const entries = new Map();
150
+ return {
151
+ /**
152
+ * @param {string} key
153
+ * @param {number} mtimeMs
154
+ * @returns {T}
155
+ */
156
+ get(key, mtimeMs) {
157
+ const have = entries.get(key);
158
+ if (have && mtimeMs <= have.loadedAt) return have;
159
+ const fresh = load(key);
160
+ entries.set(key, fresh);
161
+ return fresh;
162
+ },
163
+ size: () => entries.size,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Documents for the keyword arm, tokenised once (df/idf doesn't change per question, so
169
+ * re-tokenising inside the query loop would cost every question the whole corpus).
170
+ * `chunk` keeps both arms scoring the same units; `note` concatenates a note's chunks first, which
171
+ * suits a long note whose matching terms are spread thin. MEMORY_FUSE_LEX=note|chunk.
172
+ *
173
+ * @param {readonly ResultRow[]} rowsUsed
174
+ * @param {string} [mode]
175
+ * @returns {LexDoc[]}
176
+ */
177
+ export function buildLexDocs(rowsUsed, mode) {
178
+ if (mode !== 'note')
179
+ return rowsUsed.map((r) => ({
180
+ note: r.note,
181
+ layer: r.layer,
182
+ heading: r.heading,
183
+ text: r.text,
184
+ file: r.file,
185
+ name: r.name,
186
+ project: r.project,
187
+ toks: lexTokens(r.text),
188
+ }));
189
+ /** @type {Map<string, LexDoc>} */
190
+ const byNote = new Map();
191
+ for (const r of rowsUsed) {
192
+ const cur = byNote.get(r.note) ?? {
193
+ note: r.note,
194
+ layer: r.layer,
195
+ file: r.file,
196
+ heading: '(note)',
197
+ text: '',
198
+ name: r.name,
199
+ project: r.project,
200
+ toks: [],
201
+ };
202
+ cur.text += ' ' + r.text;
203
+ byNote.set(r.note, cur);
204
+ }
205
+ return [...byNote.values()].map((d) => ({ ...d, toks: lexTokens(d.text) }));
206
+ }
207
+
208
+ // Is something already listening on this unix socket? Full history and the measured server pile-up
209
+ // this replaced: docs/decisions/2026-08-17-socket-unlink-race.md.
210
+ // Probing must happen BEFORE the index load and warm-up, or a duplicate has already paid for both
211
+ // by the time it discovers it is redundant. A connect that neither succeeds nor errors is treated
212
+ // as LIVE — not stealing from a server that might be there is the safe direction. Only
213
+ // ECONNREFUSED (nobody bound, the file is a leftover) earns an unlink.
214
+ /**
215
+ * @param {string} sockPath
216
+ * @param {number} [timeoutMs]
217
+ * @returns {Promise<boolean>}
218
+ */
219
+ export function socketIsLive(sockPath, timeoutMs = 1000) {
220
+ if (!fs.existsSync(sockPath)) return Promise.resolve(false);
221
+ return new Promise((resolve) => {
222
+ const c = net.createConnection(sockPath);
223
+ let settled = false;
224
+ const done = (/** @type {boolean} */ v) => {
225
+ if (settled) return;
226
+ settled = true;
227
+ clearTimeout(timer);
228
+ try {
229
+ c.destroy();
230
+ } catch {}
231
+ resolve(v);
232
+ };
233
+ const timer = setTimeout(() => done(true), timeoutMs);
234
+ c.on('connect', () => done(true));
235
+ c.on('error', () => done(false));
236
+ });
237
+ }
238
+
239
+ // DEFAULT = bge-m3 since 2026-08-15, by measurement on both case sets — the full comparison and
240
+ // the harness-bug history behind two earlier rejections: docs/decisions/2026-08-15-model-choice.md.
241
+ //
242
+ // e5-multi remains available for Dutch-heavy work (MEMORY_SEMANTIC_MODEL=e5-multi, then
243
+ // --index --rebuild), though bge-m3 now beats it on Dutch too.
244
+ export { MODELS };
245
+ export const MODEL_KEY = activeModel();
246
+ export const PROFILE = MODELS[MODEL_KEY];
247
+ if (!PROFILE) {
248
+ console.error(`unknown MEMORY_SEMANTIC_MODEL — known: ${Object.keys(MODELS).join(', ')}`);
249
+ process.exit(1);
250
+ }
251
+ export const MODEL = PROFILE.id;
252
+ export const DIM = PROFILE.dim;
253
+ export const MAX_CHARS = PROFILE.maxChars;
254
+ export const MIN_SECTION = 40; // a section body shorter than this carries no retrievable content
255
+ export const QUERY_PREFIX = PROFILE.q;
256
+ export const DOC_PREFIX = PROFILE.d;
257
+
258
+ // ---------------------------------------------------------------- pure helpers (self-tested)
259
+
260
+ /**
261
+ * @param {string} raw
262
+ * @returns {{ meta: string, body: string }}
263
+ */
264
+ export function stripFrontmatter(raw) {
265
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n?/);
266
+ if (!m) return { meta: '', body: raw };
267
+ const desc = (m[1].match(/^\s*description:\s*(.+)$/m) || [])[1] || '';
268
+ return { meta: desc.trim().replace(/^["']|["']$/g, ''), body: raw.slice(m[0].length) };
269
+ }
270
+
271
+ // Does this note still hash to what the index embedded? mtime is only a fast-path hint now, not
272
+ // the decision — docs/architecture.md's closed risk R1 has why (a 20-40 min re-embed storm for
273
+ // unchanged Synology-touched content, 2026-08-19).
274
+ //
275
+ // Hashes the RAW FILE BYTES, not the chunk text: chunkNote() is pure, so identical bytes give
276
+ // identical vectors, and a frontmatter-only edit costing one needless re-embed is the safe way to
277
+ // be wrong — same as mtime. A change to chunkNote() itself is invisible to this, same as to mtime;
278
+ // --rebuild is the escape hatch for both.
279
+ //
280
+ // sha256 via crypto.hash(): stdlib, hardware-accelerated, not a digest a FIPS build disables.
281
+ // Speed sweep vs sha1: docs/decisions/2026-08-19-content-hash.md.
282
+ /**
283
+ * @param {import('node:crypto').BinaryLike} raw
284
+ * @returns {string}
285
+ */
286
+ export function contentHash(raw) {
287
+ return crypto.hash('sha256', raw, 'hex');
288
+ }
289
+
290
+ // CARD, the card-chunk heading sentinel, is defined in ./lexical.mjs and re-exported above.
291
+
292
+ // ponytail: note-level superseded_by rides in the header line every chunk but the alias chunk
293
+ // starts with, so the index needs no column; a note indexed before this shipped needs --rebuild.
294
+ const DEAD = ' · superseded_by: ';
295
+ const isDead = (/** @type {string} */ text) => text.split('\n', 1)[0].includes(DEAD);
296
+
297
+ // Every chunk carries the note's identity. Without it a mid-note section embeds as anonymous prose
298
+ // and a whole-note question cannot reach it — the vector equivalent of the "### Untitled" chunks
299
+ // FTS5 was returning for L1 notes.
300
+ /**
301
+ * @param {string} name
302
+ * @param {string} raw
303
+ * @returns {{ heading: string, text: string }[]}
304
+ */
305
+ export function chunkNote(name, raw) {
306
+ const { meta, body } = stripFrontmatter(raw);
307
+ const by = raw
308
+ .match(/^---\n([\s\S]*?)\n---/)?.[1]
309
+ .match(SUPERSEDED_BY)?.[1]
310
+ .trim();
311
+ const head = (meta ? `${name}: ${meta}` : name) + (by ? `${DEAD}${by}` : '');
312
+ const out = [{ heading: CARD, text: `${head}\n${body.slice(0, 700)}`.slice(0, MAX_CHARS) }];
313
+ // `_Also asked as:` gets its OWN chunk — alone at the end of a note it dilutes into the last
314
+ // section's embedding and becomes unreachable by a near-identical query (2026-08-15 near-miss;
315
+ // full case: docs/decisions/2026-08-15-alias-chunk-regex.md). `$` under the /m flag means END OF
316
+ // LINE, not end of string, so a naive regex here truncates a wrapped alias block to its first
317
+ // line — `(?![\s\S])` is the actual end-of-input assertion /m cannot break.
318
+ const alias = body.match(/^_Also asked as:([\s\S]*?)(?:\n\s*\n|(?![\s\S]))/m);
319
+ // Led by the NAME only, not the description: the head line is ~260 chars of summary prose here and
320
+ // would outweigh the questions it is supposed to introduce — the same dilution being fixed.
321
+ if (alias)
322
+ out.push({
323
+ heading: '(aliases)',
324
+ text: `${name} — questions this note answers:\n${alias[1].replace(/_\s*$/, '').trim()}`.slice(
325
+ 0,
326
+ MAX_CHARS,
327
+ ),
328
+ });
329
+ for (const part of body.split(/^##\s+/m)) {
330
+ const nl = part.indexOf('\n');
331
+ if (nl === -1) continue; // no body under this heading
332
+ const heading = part.slice(0, nl).trim();
333
+ const text = part.slice(nl + 1).trim();
334
+ if (text.length < MIN_SECTION) continue;
335
+ for (let i = 0; i < text.length; i += MAX_CHARS) {
336
+ const slice = text.slice(i, i + MAX_CHARS);
337
+ if (slice.trim().length < MIN_SECTION) continue;
338
+ out.push({ heading: heading || '(body)', text: `${head} — ${heading}\n${slice}` });
339
+ }
340
+ }
341
+ return out;
342
+ }
343
+
344
+ // Corpus competition: a SEPARATE result window, not a replaced one — filtering the corpus instead
345
+ // regresses retrieval (commands/eval.md's "scoping by layer is REFUTED" warning). Reserving slots
346
+ // lets the ~47 L1 notes surface without evicting the ~990 Insights ones.
347
+ // `sorted` is descending by `.s`; returns at most K, still score-ordered.
348
+ /**
349
+ * @template {{ s: number }} T
350
+ * @param {readonly T[]} sorted
351
+ * @param {number} K
352
+ * @param {number} reserve
353
+ * @param {(x: T) => boolean} isReserved
354
+ * @returns {T[]}
355
+ */
356
+ export function fuseReserved(sorted, K, reserve, isReserved) {
357
+ const top = sorted.slice(0, K);
358
+ const need = reserve - top.filter(isReserved).length;
359
+ if (need <= 0) return top;
360
+ // Promote only as far as there is something to evict, or the window grows past K when the top is
361
+ // already all-reserved — caught by selftest, not by any query, since K/3 makes it rare in practice.
362
+ const evictable = top.filter((x) => !isReserved(x)).length;
363
+ const promote = sorted.slice(K).filter(isReserved).slice(0, Math.min(need, evictable));
364
+ if (!promote.length) return top;
365
+ // evict the weakest non-reserved entries — never a reserved one, or promotion eats itself
366
+ let drop = promote.length;
367
+ const kept = [];
368
+ for (let i = top.length - 1; i >= 0; i--) {
369
+ if (drop > 0 && !isReserved(top[i])) {
370
+ drop--;
371
+ continue;
372
+ }
373
+ kept.unshift(top[i]);
374
+ }
375
+ return [...kept, ...promote].sort((a, b) => b.s - a.s);
376
+ }
377
+
378
+ /**
379
+ * @param {ArrayLike<number>} a
380
+ * @param {ArrayLike<number>} b
381
+ * @returns {number}
382
+ */
383
+ export function cosine(a, b) {
384
+ let s = 0;
385
+ for (let i = 0; i < a.length; i++) s += a[i] * b[i];
386
+ return s; // vectors are L2-normalised at embed time, so the dot product IS cosine
387
+ }
388
+
389
+ // A stored vector whose byte length does not match the active model's dimension is from a DIFFERENT
390
+ // model. Reading it as `new Float32Array(buf, offset, DIM)` does not throw — it silently reinterprets
391
+ // the bytes and returns a plausible-looking score. That is how a mixed-dimension index (384 + 1024 in
392
+ // one table, 2026-08-15) can serve nonsense with no error anywhere.
393
+ /**
394
+ * @param {readonly Partial<ChunkRow>[]} rows
395
+ * @param {number} dim
396
+ * @param {string} [label]
397
+ */
398
+ export function assertVectorWidth(rows, dim, label = 'index') {
399
+ const want = dim * 4;
400
+ // `?.`, not `.`: a row reaching here without a vector at all is the same corruption this
401
+ // exists to catch, and it must produce the message below rather than a TypeError one line up.
402
+ const bad = rows.filter((r) => r.vec?.byteLength !== want);
403
+ if (!bad.length) return;
404
+ const widths = [...new Set(bad.map((r) => r.vec?.byteLength ?? 'missing'))].join(', ');
405
+ console.log(
406
+ `⚠ ${label}: ${bad.length}/${rows.length} vectors are ${widths} bytes, expected ${want} (${dim}-dim).`,
407
+ );
408
+ console.log(
409
+ ' The index mixes models — results would be silent nonsense. Run --index --rebuild.',
410
+ );
411
+ process.exit(1);
412
+ }
413
+
414
+ // Topic clusters, for finding CONSOLIDATION GAPS — many notes on one idea with no permanent/
415
+ // note covering them. Deliberately CROSS-folder, unlike dedup: a topic is normally a Pattern +
416
+ // a Mistake + a Decision about the same thing. Union-find over the similarity graph:
417
+ // single-linkage, so a chain of related notes forms one topic rather than requiring every pair
418
+ // to be similar. Exists because memory-audit-checks.mjs's keyword Jaccard scan missed 6 real
419
+ // merges across 987 notes it should have caught (2026-08-14) — full evidence and the
420
+ // cache-policy-quota/Cache-Control examples: docs/decisions/2026-08-14-topic-cluster-gaps.md.
421
+ /**
422
+ * @template {{ vec: ArrayLike<number> }} T
423
+ * @param {readonly T[]} items
424
+ * @param {number} minScore
425
+ * @returns {T[][]}
426
+ */
427
+ export function clusterNotes(items, minScore) {
428
+ const parent = items.map((_, i) => i);
429
+ const find = (/** @type {number} */ i) => {
430
+ while (parent[i] !== i) {
431
+ parent[i] = parent[parent[i]];
432
+ i = parent[i];
433
+ }
434
+ return i;
435
+ };
436
+ const union = (/** @type {number} */ a, /** @type {number} */ b) => {
437
+ const ra = find(a),
438
+ rb = find(b);
439
+ if (ra !== rb) parent[ra] = rb;
440
+ };
441
+ for (let i = 0; i < items.length; i++)
442
+ for (let j = i + 1; j < items.length; j++)
443
+ if (cosine(items[i].vec, items[j].vec) >= minScore) union(i, j);
444
+ /** @type {Map<number, T[]>} */
445
+ const groups = new Map();
446
+ items.forEach((it, i) => {
447
+ const r = find(i);
448
+ if (!groups.has(r)) groups.set(r, []);
449
+ /** @type {T[]} */ (groups.get(r)).push(it);
450
+ });
451
+ return [...groups.values()].filter((g) => g.length > 1).sort((a, b) => b.length - a.length);
452
+ }
453
+
454
+ // Mean of L2-normalised vectors, re-normalised — the cluster's "average meaning", used to ask
455
+ // whether any permanent/ note already covers it.
456
+ /**
457
+ * @param {readonly ArrayLike<number>[]} vecs
458
+ * @returns {Float32Array}
459
+ */
460
+ export function centroid(vecs) {
461
+ const out = new Float32Array(vecs[0].length);
462
+ for (const v of vecs) for (let i = 0; i < v.length; i++) out[i] += v[i];
463
+ let n = 0;
464
+ for (let i = 0; i < out.length; i++) n += out[i] * out[i];
465
+ n = Math.sqrt(n) || 1;
466
+ for (let i = 0; i < out.length; i++) out[i] /= n;
467
+ return out;
468
+ }
469
+
470
+ /** A permanent/ note that wikilinks this share of a cluster's members covers it, whatever its cosine (#188). */
471
+ export const LINK_COVERAGE = 0.6;
472
+
473
+ // The gap `--clusters` reports and the candidate rule for promotion (#96) both read: a cluster no
474
+ // permanent/ note links to LINK_COVERAGE, whose centroid sits further from its best permanent/
475
+ // match than a typical member does. Links come first because a broad note covering two topics sits
476
+ // far from each in embedding space. ONE computation for both callers — a second scoring path here
477
+ // is the same failure CLAUDE.md names for dupeScore() below. Bar = 25th percentile of member
478
+ // distances, not the median or an absolute threshold — a synthesis note only needs to be as
479
+ // central as a typical member; calibration in docs/decisions/2026-08-31-consolidation-gap-percentile.md.
480
+
481
+ /**
482
+ * @template {{ note: string, layer: string, vec: ArrayLike<number> }} T
483
+ * @param {readonly T[]} working
484
+ * @param {readonly (T & { links?: ReadonlySet<string> })[]} permanent
485
+ * @param {number} minScore cluster linkage threshold
486
+ * @param {number} minSize
487
+ */
488
+ export function consolidationGaps(working, permanent, minScore, minSize) {
489
+ const clusters = clusterNotes(working, minScore).filter((g) => g.length >= minSize);
490
+ /** @type {{ members: T[], best: { note: string | null, s: number }, typical: number, borderline: boolean }[]} */
491
+ const gaps = [];
492
+ /** @type {{ members: T[], by: string, linked: number }[]} */
493
+ const covered = [];
494
+ for (const g of clusters) {
495
+ /** @type {{ by: string, linked: number } | null} */
496
+ let byLinks = null;
497
+ for (const p of permanent) {
498
+ const linked = p.links ? g.filter((x) => p.links?.has(x.note)).length : 0;
499
+ if (linked >= LINK_COVERAGE * g.length && (!byLinks || linked > byLinks.linked))
500
+ byLinks = { by: p.note, linked };
501
+ }
502
+ if (byLinks) {
503
+ covered.push({ members: g, ...byLinks });
504
+ continue;
505
+ }
506
+ const c = centroid(g.map((x) => x.vec));
507
+ /** @type {{ note: string | null, s: number }} */
508
+ let best = { note: null, s: 0 };
509
+ for (const p of permanent) {
510
+ const s = cosine(c, p.vec);
511
+ if (s > best.s) best = { note: p.note, s };
512
+ }
513
+ const memberSims = g.map((x) => cosine(c, x.vec)).sort((a, b) => a - b);
514
+ const typical = memberSims[Math.floor(memberSims.length * 0.25)];
515
+ if (best.s >= typical) continue; // a permanent/ note sits inside the topic's own spread
516
+ gaps.push({ members: g, best, typical, borderline: best.s >= typical - 0.02 });
517
+ }
518
+ return { gaps, covered };
519
+ }
520
+
521
+ // A cluster that has cost something comes before a bigger one that has not. Stable, so size order
522
+ // holds inside each group; applied before `--top`, so a Mistakes cluster is not cut off.
523
+ /**
524
+ * @template {{ members: readonly { layer: string }[] }} G
525
+ * @param {readonly G[]} gaps
526
+ * @returns {G[]}
527
+ */
528
+ export function mistakesFirst(gaps) {
529
+ const hasMistake = (/** @type {G} */ g) => g.members.some((x) => x.layer === 'Mistakes');
530
+ return [...gaps].sort((a, b) => Number(hasMistake(b)) - Number(hasMistake(a)));
531
+ }
532
+
533
+ /**
534
+ * The index allow-list. A folder not named here is never indexed.
535
+ *
536
+ * @param {string} vault
537
+ * @param {string} slug
538
+ * @returns {{ dir: string, layer: string }[]}
539
+ */
540
+ export function vaultSources(vault, slug) {
541
+ const out = [{ dir: path.join(vault, 'Memory', slug), layer: 'Memory' }];
542
+ for (const f of ['Patterns', 'Mistakes', 'Decisions'])
543
+ out.push({ dir: path.join(vault, 'Insights', slug, f), layer: f });
544
+ // permanent/ is cross-project, not slug-scoped. Indexed here so --clusters can ask "is this topic
545
+ // already consolidated?", and so promoted knowledge is searchable at all.
546
+ out.push({ dir: path.join(vault, 'permanent'), layer: 'permanent' });
547
+ for (const sub of ['domain', 'tools'])
548
+ out.push({ dir: path.join(vault, 'permanent', sub), layer: 'permanent' });
549
+ // Personal/ is cross-project too, and searchable on purpose (docs/decisions/2026-11-25-index-personal.md).
550
+ for (const sub of ['Research', 'Wiki'])
551
+ out.push({ dir: path.join(vault, 'Personal', sub), layer: 'Personal' });
552
+ return out;
553
+ }
554
+
555
+ export const VALUE_FLAGS = new Set([
556
+ '--query',
557
+ '-q',
558
+ '--vault',
559
+ '--slug',
560
+ '-k',
561
+ '--min',
562
+ '--size',
563
+ '--top',
564
+ '--dupe-min',
565
+ '--truth',
566
+ '--bars',
567
+ ]);
568
+
569
+ /**
570
+ * A value flag takes the next arg verbatim, so a query may start with `-`. Every name the entry
571
+ * reads with val() must be in VALUE_FLAGS, or its value is dropped; a test scans the entry for that.
572
+ *
573
+ * @param {readonly string[]} argv
574
+ * @param {(arg: string) => boolean} isDir
575
+ */
576
+ export function parseArgs(argv, isDir) {
577
+ const flags = new Set();
578
+ /** @type {Map<string, string>} */
579
+ const values = new Map();
580
+ /** @type {string[]} */
581
+ const queries = [];
582
+ let repo = '';
583
+ for (let i = 0; i < argv.length; i++) {
584
+ const arg = argv[i];
585
+ if (VALUE_FLAGS.has(arg)) {
586
+ const value = argv[++i];
587
+ if (value === undefined) return { error: `${arg} needs a value` };
588
+ if (arg === '--query' || arg === '-q') queries.push(value);
589
+ if (!values.has(arg)) values.set(arg, value);
590
+ } else if (arg.startsWith('-')) flags.add(arg);
591
+ else if (!repo && isDir(arg)) repo = arg;
592
+ }
593
+ return { flags, values, queries, repo };
594
+ }
595
+
596
+ /** @param {Scored[]} hits */
597
+ export function tsvLines(hits) {
598
+ return hits.map(({ r, s }) => {
599
+ const file = (r.file ?? r.note)
600
+ .replace(/\\/g, '\\\\')
601
+ .replace(/\t/g, '\\t')
602
+ .replace(/\r/g, '\\r')
603
+ .replace(/\n/g, '\\n');
604
+ const snippet = r.text.replace(/\s+/g, ' ').trim().slice(0, 160);
605
+ return [s.toFixed(3), r.layer, file, snippet].join('\t');
606
+ });
607
+ }
608
+
609
+ // A slug or note name from a socket or HTTP client is a single path segment: no separator, no
610
+ // leading dot (a slug of `..` would make vaultSources() the vault root).
611
+ export const SAFE_NAME = /^[^./\\\0][^/\\\0]*$/;
612
+
613
+ /**
614
+ * @param {string} dbDir
615
+ * @returns {string[]}
616
+ */
617
+ export function indexedSlugs(dbDir) {
618
+ const suffix = `-${MODEL_KEY}.db`;
619
+ let names;
620
+ try {
621
+ names = fs.readdirSync(dbDir);
622
+ } catch {
623
+ return [];
624
+ }
625
+ return names
626
+ .filter((n) => n.startsWith('semantic-') && n.endsWith(suffix))
627
+ .map((n) => n.slice('semantic-'.length, -suffix.length))
628
+ .filter((s) => SAFE_NAME.test(s))
629
+ .sort();
630
+ }
631
+
632
+ /**
633
+ * @param {string} dbDir
634
+ * @param {unknown} slug
635
+ * @returns {slug is string}
636
+ */
637
+ export function isIndexedSlug(dbDir, slug) {
638
+ return typeof slug === 'string' && SAFE_NAME.test(slug) && indexedSlugs(dbDir).includes(slug);
639
+ }
640
+
641
+ /**
642
+ * Indexed slugs that are real projects in this vault. Drops the bench and synthetic indexes, which
643
+ * share DB_DIR but have no folder here.
644
+ * @param {string} dbDir
645
+ * @param {string} vault
646
+ */
647
+ export function projectSlugs(dbDir, vault) {
648
+ return indexedSlugs(dbDir).filter((s) =>
649
+ ['Memory', 'Insights'].some((l) => fs.existsSync(path.join(vault, l, s))),
650
+ );
651
+ }
652
+
653
+ const SHARED_LAYERS = new Set(['permanent', 'Personal']);
654
+
655
+ /**
656
+ * One corpus from several projects' rows, so a cross-project query is ONE ranking — one BM25 idf,
657
+ * one RRF — not N rankings whose first places look equal. Slug-scoped rows are re-keyed
658
+ * `slug/note`, because two projects can hold a note of the same name and searchIn() keys by note;
659
+ * `name` and `project` carry what the reader sees. Shared layers are in every index: kept once, from
660
+ * the index that holds the newest indexed `mtime`, because a stale index still has the old text.
661
+ *
662
+ * @template {ResultRow} T
663
+ * @param {readonly [string, readonly T[]][]} perSlug
664
+ * @returns {(T & { name?: string, project?: string })[]}
665
+ */
666
+ export function mergeProjectRows(perSlug) {
667
+ /** @type {Map<string, { slug: string, mtime: number }>} */
668
+ const newest = new Map();
669
+ for (const [slug, rows] of perSlug)
670
+ for (const r of rows) {
671
+ if (!SHARED_LAYERS.has(r.layer)) continue;
672
+ const cur = newest.get(r.note);
673
+ if (!cur || (r.mtime ?? 0) > cur.mtime) newest.set(r.note, { slug, mtime: r.mtime ?? 0 });
674
+ }
675
+ /** @type {(T & { name?: string, project?: string })[]} */
676
+ const out = [];
677
+ for (const [slug, rows] of perSlug)
678
+ for (const r of rows) {
679
+ if (!SHARED_LAYERS.has(r.layer))
680
+ out.push({ ...r, note: `${slug}/${r.note}`, name: r.note, project: slug });
681
+ else if (newest.get(r.note)?.slug === slug) out.push(r);
682
+ }
683
+ return out;
684
+ }
685
+
686
+ /**
687
+ * @param {string} vault
688
+ * @param {string} slug
689
+ * @returns {{ full: string, layer: string, note: string, mtime: number }[]}
690
+ */
691
+ export function indexInput(vault, slug) {
692
+ const files = [];
693
+ for (const { dir, layer } of vaultSources(vault, slug)) {
694
+ if (!fs.existsSync(dir)) continue;
695
+ for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.md'))) {
696
+ if (f === 'REFLECTIONS.md') continue; // an audit log, not a memory
697
+ const full = path.join(dir, f);
698
+ files.push({
699
+ full,
700
+ layer,
701
+ note: f.slice(0, -3),
702
+ mtime: Math.floor(fs.statSync(full).mtimeMs),
703
+ });
704
+ }
705
+ }
706
+ return files;
707
+ }
708
+
709
+ // Cross-layer pairs score 0 by construction: a Pattern and a Mistake on one topic are
710
+ // complementary by design. `layer` IS the folder — see vaultSources().
711
+ // The single shared duplicate predicate (write-time reconcile and --dupes both call this) and
712
+ // why searchIn()'s fused score is NOT this quantity: CLAUDE.md "Architecture" § Retrieval,
713
+ // docs/decisions/2026-08-23-embedding-reconcile.md.
714
+ /**
715
+ * @param {{ layer: string, vec: ArrayLike<number> }} a
716
+ * @param {{ layer: string, vec: ArrayLike<number> }} b
717
+ * @returns {number}
718
+ */
719
+ export function dupeScore(a, b) {
720
+ return a.layer === b.layer ? cosine(a.vec, b.vec) : 0;
721
+ }
722
+
723
+ // #96's "second finding": dupeScore()'s same-layer gate hides a genuine same-lesson note restated
724
+ // in a different folder. A different question from "is this a duplicate" — stays out of that
725
+ // predicate on purpose — so raw cosine, across layers, for a human to judge in /memory:prune.
726
+ /**
727
+ * @template {{ note: string, layer: string, vec: ArrayLike<number> }} T
728
+ * @param {readonly T[]} members one cluster from clusterNotes()
729
+ * @param {number} minScore
730
+ * @returns {{ s: number, a: T, b: T }[]}
731
+ */
732
+ export function crossFolderPairs(members, minScore) {
733
+ /** @type {{ s: number, a: T, b: T }[]} */
734
+ const out = [];
735
+ for (let i = 0; i < members.length; i++)
736
+ for (let j = i + 1; j < members.length; j++) {
737
+ if (members[i].layer === members[j].layer) continue; // same-folder is dupeScore()'s job
738
+ const s = cosine(members[i].vec, members[j].vec);
739
+ if (s >= minScore) out.push({ s, a: members[i], b: members[j] });
740
+ }
741
+ return out.sort((x, y) => y.s - x.s);
742
+ }
743
+
744
+ /**
745
+ * @template {{ note: string, layer: string, vec: ArrayLike<number> }} T
746
+ * @param {readonly T[]} items
747
+ * @param {number} minScore
748
+ * @returns {{ s: number, layer: string, a: string, b: string }[]}
749
+ */
750
+ export function samefolderPairs(items, minScore) {
751
+ /** @type {{ s: number, layer: string, a: string, b: string }[]} */
752
+ const out = [];
753
+ for (let i = 0; i < items.length; i++)
754
+ for (let j = i + 1; j < items.length; j++) {
755
+ const s = dupeScore(items[i], items[j]);
756
+ if (s >= minScore) out.push({ s, layer: items[i].layer, a: items[i].note, b: items[j].note });
757
+ }
758
+ return out.sort((x, y) => y.s - x.s);
759
+ }
760
+
761
+ /**
762
+ * `samefolderPairs()` minus settled pairs. `--dupe-eval` stays unfiltered: it measures the mark.
763
+ * @template {{ note: string, layer: string, vec: ArrayLike<number> }} T
764
+ * @param {readonly T[]} items
765
+ * @param {number} minScore
766
+ * @param {(note: string) => boolean} isManual
767
+ */
768
+ export function reportPairs(items, minScore, isManual) {
769
+ /** @type {Map<string, boolean>} */
770
+ const seen = new Map();
771
+ const manual = (/** @type {string} */ n) => {
772
+ if (!seen.has(n)) seen.set(n, isManual(n));
773
+ return seen.get(n);
774
+ };
775
+ return samefolderPairs(items, minScore).filter((p) => !manual(p.a) && !manual(p.b));
776
+ }
777
+
778
+ /**
779
+ * The pair key both halves of the dedup eval agree on. Order-independent, because a truth file is
780
+ * hand-written and nobody should have to guess which note the author put first.
781
+ *
782
+ * @param {string} a
783
+ * @param {string} b
784
+ * @returns {string}
785
+ */
786
+ export function pairKey(a, b) {
787
+ return [a, b].sort().join(' :: ');
788
+ }
789
+
790
+ /**
791
+ * Score one bar against a truth set.
792
+ *
793
+ * Extracted and tested because it produces the ONE number this predicate is judged by, and an
794
+ * off-by-one in a denominator here is invisible: every column would still look plausible. `false`
795
+ * counts every firing that is not a known duplicate, INCLUDING pairs nobody has judged — a bar that
796
+ * fires on 1322 pairs to catch 18 is not a better bar, and a caught column alone cannot see that.
797
+ *
798
+ * @param {readonly { a: string, b: string }[]} fired
799
+ * @param {ReadonlySet<string>} dupes
800
+ * @param {ReadonlySet<string>} keeps
801
+ * @returns {{ fires: number, caught: number, missed: number, falses: number, keepsProposed: number }}
802
+ */
803
+ export function sweepDupes(fired, dupes, keeps) {
804
+ const firedKeys = new Set(fired.map((p) => pairKey(p.a, p.b)));
805
+ const caught = [...dupes].filter((k) => firedKeys.has(k)).length;
806
+ return {
807
+ fires: firedKeys.size,
808
+ caught,
809
+ missed: dupes.size - caught,
810
+ falses: firedKeys.size - caught,
811
+ keepsProposed: [...keeps].filter((k) => firedKeys.has(k)).length,
812
+ };
813
+ }
814
+
815
+ /**
816
+ * Nearest same-layer note to a candidate card, or null when nothing reaches the bar.
817
+ *
818
+ * Top-1 by design: the runner-up is not a consolation prize. When the best match is marked
819
+ * `reconcile: manual` the caller writes a new note rather than folding into second place, because
820
+ * the mark says the human settled where this lesson's boundary sits.
821
+ *
822
+ * @template {{ note: string, layer: string, vec: ArrayLike<number> }} T
823
+ * @param {readonly T[]} items
824
+ * @param {{ layer: string, vec: ArrayLike<number> }} candidate
825
+ * @param {number} minScore
826
+ * @returns {{ note: string, s: number } | null}
827
+ */
828
+ export function bestDupe(items, candidate, minScore) {
829
+ /** @type {{ note: string, s: number } | null} */
830
+ let best = null;
831
+ for (const it of items) {
832
+ const s = dupeScore(it, candidate);
833
+ if (s >= minScore && (!best || s > best.s)) best = { note: it.note, s };
834
+ }
835
+ return best;
836
+ }
837
+
838
+ // ---------------------------------------------------------------- lexical arm + fusion
839
+ //
840
+ // Fusion exists because the two channels miss DIFFERENT notes: keyword search recovers
841
+ // identifier-shaped misses (CLI notes, ticket keys, dated commit-style titles) that the vector
842
+ // arm drops. Case counts and the sweep: docs/decisions/2026-08-15-fusion-tuning.md.
843
+ //
844
+ // RECIPROCAL RANK FUSION, not a weighted sum of scores. Cosine sits in a narrow ~0.4-0.7 band
845
+ // while BM25 is unbounded, so summing them needs a normaliser, and a normaliser is one more
846
+ // thing that is silently per-model. RRF consumes RANKS, so it cannot be broken by a model with a
847
+ // compressed similarity band, which is exactly how e5-multi failed. One knob: how much a vector
848
+ // rank outweighs a keyword rank.
849
+ // STOP, lexTokens and bm25 are defined in ./lexical.mjs; import them from there.
850
+
851
+ // `w` weights the vector rank against the keyword rank. w=0 is keyword-only, a large w is
852
+ // vector-only. RRF_K flattens the top of the curve so rank 1 vs 2 is not a landslide.
853
+ export const RRF_K = 60;
854
+ // w=2 chosen (2026-08-15 sweep, 28 EN + 15 NL cases): the only weight where neither language
855
+ // regresses. Re-sweep after any model change — a value swept on another vault/fusion formula
856
+ // does not transfer (obsidian-second-brain's w=20 is worse here on every EN column). Table:
857
+ // docs/decisions/2026-08-15-fusion-tuning.md.
858
+ // 0 disables fusion (vector only). Override per run with MEMORY_FUSE_W.
859
+ export const DEFAULT_FUSE_W = 2;
860
+ // Multiplies a superseded chunk's score in BOTH arms for ORDERING only; the returned `s` stays raw
861
+ // cosine so the recall gate never drops a claim on demotion alone.
862
+ // Sweep and why 0.9: docs/decisions/2026-10-10-superseded-demote.md.
863
+ export const SUPERSEDED_DEMOTE = 0.9;
864
+ // 'chunk' scoring (concatenate per-chunk, not per whole note) chosen by measurement — beats
865
+ // whole-note scoring at every weight and worst for Dutch (2026-08-15 sweep). MEMORY_FUSE_LEX=note
866
+ // kept as a reproducible negative result. Sweep: docs/decisions/2026-08-15-fusion-tuning.md.
867
+ export const DEFAULT_FUSE_LEX = 'chunk';
868
+ /**
869
+ * @param {readonly string[]} semRanked
870
+ * @param {readonly string[]} lexRanked
871
+ * @param {number} w
872
+ * @param {number} k
873
+ * @returns {string[]}
874
+ */
875
+ export function fuseRRF(semRanked, lexRanked, w, k) {
876
+ /** @type {Map<string, number>} */
877
+ const score = new Map();
878
+ const add = (/** @type {readonly string[]} */ list, /** @type {number} */ weight) =>
879
+ list.forEach((note, i) => score.set(note, (score.get(note) || 0) + weight / (RRF_K + i + 1)));
880
+ add(semRanked, w);
881
+ add(lexRanked, 1);
882
+ return [...score.entries()]
883
+ .sort((a, b) => b[1] - a[1])
884
+ .slice(0, k)
885
+ .map(([note]) => note);
886
+ }
887
+
888
+ /**
889
+ * A query-ready index bundle from raw chunk rows. No SQLite here — `lib/` must not import
890
+ * node:sqlite (CI enforces it), so the entry reads the rows and this owns everything after.
891
+ *
892
+ * @template {ResultRow} T
893
+ * @param {string} slug
894
+ * @param {string} dbPath
895
+ * @param {readonly T[]} rows
896
+ * @param {{ dropAliases?: boolean, lexMode?: string, dim?: number }} [opts]
897
+ * @returns {Bundle<T>}
898
+ */
899
+ export function buildBundle(slug, dbPath, rows, { dropAliases = false, lexMode, dim } = {}) {
900
+ // Ablation switch, so the alias-chunk change can be scored against its own absence on ONE index.
901
+ // Otherwise the A/B needs two full rebuilds, and the note set moves between them — which is
902
+ // exactly how the 2026-08-15 alias measurement was first taken (1034 notes before, 1047 after)
903
+ // and why it could not be trusted. Query-time exclusion holds the note set fixed by construction.
904
+ const rowsUsed = dropAliases ? rows.filter((r) => r.heading !== '(aliases)') : rows;
905
+ if (dim != null) assertVectorWidth(rowsUsed, dim, 'query');
906
+ const lexDocs = buildLexDocs(rowsUsed, lexMode);
907
+ const own = (/** @type {ResultRow} */ r) =>
908
+ isDead(r.text) || (r.heading !== '(note)' && SUPERSEDED_MARKER.test(r.text));
909
+ const marked = new Set(rowsUsed.filter(own).map((r) => r.note));
910
+ // Card and alias chunks speak for the whole note, so they carry any of its markers; a section
911
+ // carries only its own, because the rest of a multi-claim note is still true.
912
+ const isSuperseded = (/** @type {ResultRow} */ r) =>
913
+ own(r) || ((r.heading === CARD || r.heading === '(aliases)') && marked.has(r.note));
914
+ return {
915
+ slug,
916
+ dbPath,
917
+ rowsUsed,
918
+ lexDocs,
919
+ // Display text comes from the note's CARD, not from whichever chunk matched. Alias chunks win
920
+ // the match often (that is their job) but their text is a list of questions — as a one-line
921
+ // brief it reads as noise. Match on any chunk, describe with the card.
922
+ cardByNote: new Map(rowsUsed.filter((r) => r.heading === CARD).map((r) => [r.note, r.text])),
923
+ superseded: new Set([...rowsUsed, ...lexDocs].filter(isSuperseded)),
924
+ loadedAt: Date.now(),
925
+ };
926
+ }
927
+
928
+ // One query, factored out so the CLI and the socket server cannot drift apart — a server that
929
+ // re-implemented ranking would eventually answer differently from the eval harness, and the
930
+ // whole point of the harness is that it measures what a session actually gets.
931
+ //
932
+ // The `preFiltered`/`--layer` history and why this is byte-for-byte what ran in the entry:
933
+ // docs/architecture.md, "G1 — the entry/lib/ rule is inverted where it matters".
934
+ /**
935
+ * @param {Bundle<ChunkRow>} index
936
+ * @param {string} q
937
+ * @param {Float32Array} qvec
938
+ * @param {number} k
939
+ * @returns {Scored[]}
940
+ */
941
+ export function searchIn(index, q, qvec, k) {
942
+ const { rowsUsed, lexDocs } = index;
943
+ const demote = (/** @type {ResultRow} */ r) => (index.superseded?.has(r) ? SUPERSEDED_DEMOTE : 1);
944
+ // best chunk per note, so one long note cannot fill the whole result list
945
+ /** @type {Map<string, Scored>} */
946
+ const best = new Map();
947
+ /** @type {Map<string, number>} */
948
+ const rank = new Map();
949
+ for (const r of rowsUsed) {
950
+ const s = cosine(qvec, new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM));
951
+ if (!best.has(r.note) || /** @type {Scored} */ (best.get(r.note)).s < s)
952
+ best.set(r.note, { r, s });
953
+ const key = s * demote(r);
954
+ if (!rank.has(r.note) || /** @type {number} */ (rank.get(r.note)) < key) rank.set(r.note, key);
955
+ }
956
+ const at = (/** @type {Scored} */ x) => /** @type {number} */ (rank.get(x.r.note));
957
+ const sorted = [...best.values()].sort((a, b) => at(b) - at(a));
958
+
959
+ // Keyword arm over the SAME units, then rank-fuse.
960
+ const FUSE_W = Number(process.env.MEMORY_FUSE_W ?? DEFAULT_FUSE_W);
961
+ /** @type {Scored[] | null} */
962
+ let fused = null;
963
+ if (FUSE_W > 0 && FUSE_W < Infinity) {
964
+ const qt = lexTokens(q);
965
+ if (qt.length) {
966
+ const scores = bm25(lexDocs, qt);
967
+ /** @type {Map<string, number>} */
968
+ const bestLex = new Map();
969
+ lexDocs.forEach((d, i) => {
970
+ const v = scores[i] * demote(d);
971
+ if (!bestLex.has(d.note) || /** @type {number} */ (bestLex.get(d.note)) < v)
972
+ bestLex.set(d.note, v);
973
+ });
974
+ const lexRanked = [...bestLex.entries()]
975
+ .filter(([, v]) => v > 0)
976
+ .sort((a, b) => b[1] - a[1])
977
+ .map(([n]) => n);
978
+ const order = fuseRRF(
979
+ sorted.map((x) => x.r.note),
980
+ lexRanked,
981
+ FUSE_W,
982
+ k,
983
+ );
984
+ const byNote = new Map(sorted.map((x) => [x.r.note, x]));
985
+ // A note the keyword arm found but the vector arm ranked below the window still needs a row
986
+ // to display; pull it from the chunk table rather than dropping it.
987
+ fused = order.map(
988
+ (n) =>
989
+ byNote.get(n) ?? { r: /** @type {LexDoc} */ (lexDocs.find((d) => d.note === n)), s: 0 },
990
+ );
991
+ }
992
+ }
993
+ // Layer quota — OFF by default, refuted at k=5 on both case sets (see fuseReserved).
994
+ const reserve = Number(process.env.MEMORY_FUSE_RESERVE ?? 0);
995
+ const base = fused ?? sorted.slice(0, k);
996
+ return reserve > 0
997
+ ? fuseReserved(fused ? base.map((x) => x) : sorted, k, reserve, (x) => x.r.layer === 'Memory')
998
+ : base;
999
+ }