@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,1192 @@
1
+ #!/usr/bin/env node
2
+ // Semantic + keyword retrieval over the vault — CLI entry.
3
+ //
4
+ // Thin-ish on purpose: this half owns argv, the SQLite handle and the embedding pipeline. The model
5
+ // profiles, chunking and all the scoring maths live in lib/memory-semantic.mjs with their tests
6
+ // beside them, so a ranking change can be exercised without a database.
7
+ //
8
+ // Usage:
9
+ // node memory-semantic.mjs --index [dir] [--rebuild]
10
+ // node memory-semantic.mjs --query "question" [-k 5] [--json | --tsv]
11
+ // node memory-semantic.mjs --serve | --coverage | --dupes | --clusters | --check-embedding
12
+ // node memory-semantic.mjs --propose [--top 8] # stage promotion candidates (#96)
13
+ // node memory-semantic.mjs --cross-dupes # same lesson, different folder, within a cluster
14
+ // node memory-semantic.mjs --dupe-eval --truth <file.jsonl> [--bars 0.75,0.70]
15
+ // node --test scripts/lib/memory-semantic.test.mjs
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { DatabaseSync } from 'node:sqlite';
19
+ import * as paths from '../hooks/lib/paths.mjs';
20
+ import { logHook } from '../hooks/lib/hook-io.mjs';
21
+ import { CARD } from './lib/lexical.mjs';
22
+ import {
23
+ MODEL_KEY,
24
+ PROFILE,
25
+ MODEL,
26
+ DIM,
27
+ MAX_CHARS,
28
+ QUERY_PREFIX,
29
+ DOC_PREFIX,
30
+ DEFAULT_FUSE_LEX,
31
+ chunkNote,
32
+ contentHash,
33
+ cosine,
34
+ assertVectorWidth,
35
+ clusterNotes,
36
+ consolidationGaps,
37
+ mistakesFirst,
38
+ crossFolderPairs,
39
+ samefolderPairs,
40
+ reportPairs,
41
+ bestDupe,
42
+ dupeScore,
43
+ pairKey,
44
+ sweepDupes,
45
+ socketIsLive,
46
+ singleFlight,
47
+ mtimeCache,
48
+ evictableSockets,
49
+ buildBundle,
50
+ searchIn,
51
+ QUIT,
52
+ vaultSources,
53
+ indexInput,
54
+ isIndexedSlug,
55
+ tsvLines,
56
+ parseArgs,
57
+ projectSlugs,
58
+ mergeProjectRows,
59
+ } from './lib/memory-semantic.mjs';
60
+ import { proposeStagingNotes } from './lib/memory-promote.mjs';
61
+ import { linkTargets } from '../hooks/lib/memory-link-lint.mjs';
62
+ import { isManual } from './lib/memory-mark.mjs';
63
+
64
+ /** @typedef {import('./lib/memory-semantic.mjs').ChunkRow} ChunkRow */
65
+ /** @typedef {{ note: string, layer: string, text: string, vec: Uint8Array }} CardRow */
66
+ /** @typedef {{ note: string, layer: string, text: string, vec: Float32Array }} Card */
67
+ /** @typedef {{ file: string, mtime: number, hash: string | null }} IndexedFile */
68
+
69
+ // ---------------------------------------------------------------- setup
70
+
71
+ const argv = process.argv.slice(2);
72
+ const parsed = parseArgs(argv, (a) => fs.existsSync(a) && fs.statSync(a).isDirectory());
73
+ if ('error' in parsed) {
74
+ console.error(parsed.error);
75
+ process.exit(1);
76
+ }
77
+ const { flags, values, queries, repo } = parsed;
78
+ const flag = (/** @type {string} */ n) => flags.has(n);
79
+ const val = (/** @type {string} */ n) => values.get(n);
80
+ // --vault/--slug point this at a generated benchmark vault instead of the real one, which is how
81
+ // a retrieval change gets scored against a FIXED note set. Explicit flags, not CLAUDE_VAULT: an
82
+ // env override once sent a relocating hook at a throwaway path and cost 24 notes.
83
+ const VAULT = val('--vault') || paths.vault();
84
+ const SLUG = val('--slug') || paths.projectKey(repo || process.cwd());
85
+ const tsvDupes = flag('--tsv') && (flag('--dupes') || flag('--cross-dupes'));
86
+ const readOnly = tsvDupes && !flag('--index');
87
+ const DB_DIR = readOnly ? path.join(paths.memoryHome(), 'db') : paths.stateDir('db');
88
+ const DB_PATH = path.join(DB_DIR, `semantic-${SLUG}-${MODEL_KEY}.db`);
89
+
90
+ // Keyed by MODEL, not by slug+model: one server answers for every project, because the model is
91
+ // what is expensive to hold and it is identical across them. Refuse to become a second one — see
92
+ // socketIsLive(). This sits above the DB open on purpose: everything below it (index rows, then the
93
+ // model) is what a duplicate must not pay for.
94
+ const SERVE_SOCK = path.join(paths.memoryHome(), 'run', `search-${MODEL_KEY}.sock`);
95
+ if (flag('--serve')) {
96
+ paths.stateDir('run');
97
+ // --serve opens no project DB (see below), so every other mode would dereference a null handle
98
+ // and crash where it used to print usage. Unreachable from any hook — nothing passes both — but a
99
+ // crash is the wrong answer to a typo.
100
+ const alsoAsked = [
101
+ '--index',
102
+ '--coverage',
103
+ '--dupes',
104
+ '--clusters',
105
+ '--check-embedding',
106
+ '--dupe-eval',
107
+ '--propose',
108
+ '--cross-dupes',
109
+ ].filter(flag);
110
+ if (alsoAsked.length) {
111
+ console.log(`--serve cannot be combined with ${alsoAsked.join(' ')} — run them separately.`);
112
+ process.exit(1);
113
+ }
114
+ if (await socketIsLive(SERVE_SOCK)) {
115
+ console.log(`already serving ${MODEL_KEY} on ${SERVE_SOCK}`);
116
+ process.exit(0);
117
+ }
118
+ try {
119
+ fs.unlinkSync(SERVE_SOCK); // stale file from a server that died without its SIGTERM handler
120
+ } catch {}
121
+ }
122
+
123
+ // NOT opened for --serve. Every query goes through loadIndex(), which opens and closes its own
124
+ // per-slug handle, so this one would be an unread fd held for the life of a 30-minute process — and
125
+ // worse, the CREATE TABLE below would CREATE an empty index file for whichever project happened to
126
+ // spawn the server, which doctor.sh then reports as "index is empty" for a project that simply has
127
+ // none. The server has no special relationship with its spawning project; that is the whole point.
128
+ if (flag('--all-projects') && !argv.some((a) => a === '--query' || a === '-q')) {
129
+ console.log('--all-projects works only with --query');
130
+ process.exit(1);
131
+ }
132
+ const readsNoDb = flag('--serve') || flag('--check-embedding') || flag('--all-projects');
133
+ if (!readsNoDb && !flag('--index') && !fs.existsSync(DB_PATH)) {
134
+ console.error(`no index for ${SLUG} — run --index first`);
135
+ process.exit(1);
136
+ }
137
+ if (readOnly) {
138
+ // SQLite can create WAL sidecars even on a read-only connection.
139
+ const header = Buffer.alloc(20);
140
+ const fd = fs.openSync(DB_PATH, 'r');
141
+ try {
142
+ fs.readSync(fd, header, 0, header.length, 0);
143
+ } finally {
144
+ fs.closeSync(fd);
145
+ }
146
+ if (header[18] === 2 || header[19] === 2) {
147
+ console.error('cannot scan a WAL-mode index without creating sidecars');
148
+ process.exit(1);
149
+ }
150
+ }
151
+ const db = readsNoDb ? null : new DatabaseSync(DB_PATH, { readOnly });
152
+ // `hash` repeats the SAME value on every row of a file. The staleness decision is per file, so a
153
+ // files table would be the normalised home for it — and would be a second write path that can
154
+ // disagree with the first. Here the hash is written and deleted by the statements that already
155
+ // write and delete a file's chunks (`DELETE FROM chunks WHERE file = ?` then re-INSERT), so a hash
156
+ // with no chunks cannot occur and, within one version, neither can chunks with no hash.
157
+ //
158
+ // A NULL hash is still reachable and is treated as a repairable state, not an impossible one: an
159
+ // index built before this column existed, or one written afterwards by an OLDER installed version
160
+ // — Claude Code keeps every version it has ever installed and they all share
161
+ // `$CLAUDE_MEMORY_HOME/db`. `--index` fills those in without embedding anything; see the backfill.
162
+ // Costs 64 bytes per chunk against ~4 KB of vector — 0.2 MB on a 3400-chunk index.
163
+ let schemaStale = false;
164
+ if (db && !readOnly) {
165
+ db.exec(`CREATE TABLE IF NOT EXISTS chunks (
166
+ id INTEGER PRIMARY KEY, note TEXT, layer TEXT, file TEXT, mtime INTEGER,
167
+ heading TEXT, text TEXT, vec BLOB, hash TEXT)`);
168
+ // A missing `hash` column is what identifies an index built before this shipped. Detect only —
169
+ // the ALTER lives in --index, next to the backfill that gives the column its values. Altering
170
+ // here destroys the evidence: the first run of ANY mode would add the column, and the --index
171
+ // that followed would see a current schema, keep every NULL-hash row and report "index already
172
+ // current" — silently re-embedding on every mtime bump forever (2026-08-19).
173
+ schemaStale = !db
174
+ .prepare('PRAGMA table_info(chunks)')
175
+ .all()
176
+ .some((c) => c.name === 'hash');
177
+ db.exec('CREATE INDEX IF NOT EXISTS chunks_file ON chunks(file)');
178
+ db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)');
179
+ }
180
+
181
+ // Vectors from two different models are not comparable — cosine between them is noise that looks
182
+ // like a score. Record which model built the index; --index rebuilds on a change, everything else
183
+ // refuses to run against a stale one rather than returning quiet nonsense.
184
+ const hasChunks = db
185
+ ? /** @type {{ c: number }} */ (db.prepare('SELECT COUNT(*) c FROM chunks').get()).c > 0
186
+ : false;
187
+ // An index written before this table existed records no model. Treat unknown as MISMATCHED, not as
188
+ // "probably fine" — the first version of this guard did the latter and quietly kept serving stale
189
+ // vectors from the previous model while reporting the index as current.
190
+ const storedModel = hasChunks
191
+ ? db?.prepare("SELECT value FROM meta WHERE key = 'model'").get()?.value
192
+ : undefined;
193
+ const modelChanged = hasChunks && storedModel !== MODEL;
194
+ // An index that predates the `hash` column is NOT treated like a model change, and that asymmetry
195
+ // is the whole migration. Its vectors were built by THIS model and answer exactly as well as they
196
+ // did yesterday; only --index needs the column, and it can fill it by reading each note once
197
+ // instead of re-embedding it. So there is deliberately no refusal for a missing hash and no forced
198
+ // rebuild (2026-08-19).
199
+ //
200
+ // A forced rebuild instead would fire unattended on every existing install — semantic-index-refresh
201
+ // launches --index detached with rows written outside a transaction, so an interrupted rebuild
202
+ // leaves a PARTIAL index indistinguishable from a current one. See
203
+ // docs/decisions/2026-08-19-hash-column-migration.md.
204
+
205
+ // `pipeline.dispose()` -> `InferenceSession.release()` returns the onnxruntime session's native
206
+ // memory; dropping the JS reference alone would not. Socket, indexes and BM25 tokens survive an
207
+ // unload — see CLAUDE.md ("modelIdleMs"/"serveIdleMs") and docs/architecture.md "Flow 3 — the
208
+ // search daemon" for the measured numbers (~1.4GB idle vs ~150MB unloaded).
209
+ async function unloadEmbedder() {
210
+ // take() returns null while a request is mid-inference; the next idle tick retries.
211
+ const e = embedderCell.take(); // out of the cell FIRST: a request arriving mid-dispose must
212
+ if (!e) return false; // rebuild, not reuse a corpse
213
+ try {
214
+ await e.dispose();
215
+ } catch {
216
+ /* best effort — a failed release must not take the server down */
217
+ }
218
+ return true;
219
+ }
220
+
221
+ async function loadEmbedder() {
222
+ const transformers = await import('@huggingface/transformers');
223
+ // Redirect the weights to $CLAUDE_MEMORY_HOME/models BEFORE the first pipeline() call.
224
+ // The default caches ~722 MB inside node_modules/@huggingface/transformers/.cache, which is
225
+ // the plugin's version-pinned dir and is discarded on every /plugin update.
226
+ paths.useModelCache(transformers);
227
+ return transformers.pipeline('feature-extraction', MODEL, {
228
+ dtype: 'q8',
229
+ // onnxruntime's BFCArena grows to the largest shapes it has seen and never returns them — the
230
+ // only bound that survives an input the clamp below fails to anticipate; see CLAUDE.md
231
+ // (enableCpuMemArena) and docs/architecture.md "THREE memory bounds". A single long query left a
232
+ // resident server holding 8.8G of dirty MALLOC_LARGE (2026-08-17); arena numbers in CHANGELOG.
233
+ session_options: { enableCpuMemArena: false },
234
+ });
235
+ }
236
+
237
+ // The check-then-act guard lives in lib/ with its tests — see singleFlight(). A regression in it
238
+ // is silent: it costs a leaked ~1.3GB session, not a wrong answer, so nothing here would fail.
239
+ const embedderCell = singleFlight(loadEmbedder);
240
+
241
+ /**
242
+ * @param {readonly string[]} texts
243
+ * @returns {Promise<Float32Array[]>}
244
+ */
245
+ async function embed(texts) {
246
+ // borrow(), not get(): holds the session for the whole inference so the idle timer cannot
247
+ // dispose() it out from under native code. See singleFlight().
248
+ return embedderCell.borrow(async (model) => {
249
+ // Pooling is per-model and silent when wrong, exactly like the query/passage prefixes above.
250
+ // The BGE family trains its dense vector on the CLS token; E5 trains on the mean. Feeding a
251
+ // BGE model mean-pooled vectors still returns plausible cosines, so the loss never surfaces
252
+ // as an error — only as rankings that are quietly worse than the model can do.
253
+ // Slice HERE, not in the callers, so the index path and the query path embed identically. They
254
+ // did not: indexing batched 8 while a query batched however many questions were asked at once —
255
+ // so the eval harness (28 questions in one padded batch) computed different vectors than a live
256
+ // session (one question). With batch 1 the padding is gone and both sides agree by construction.
257
+ const B = PROFILE.batch ?? 1; // 1 = no padding. See --check-embedding; every model tested fails at >1.
258
+ // Clamp HERE for the same reason the batch is pinned here: both sides must embed identically.
259
+ // Queries were capped only by bge-m3's own 8192-token limit — ~18x the index's per-chunk cap —
260
+ // which is the source of the 8.8G MALLOC_LARGE arena growth (2026-08-17). This clamp bounds what
261
+ // is ASKED FOR; `enableCpuMemArena: false` in loadEmbedder() bounds the allocator — belt and
262
+ // braces, since only the allocator bound survives an input this clamp fails to anticipate. Full
263
+ // sweep: CLAUDE.md ("embed() clamps to MAX_CHARS") and docs/architecture.md "THREE memory bounds".
264
+ const clamped = texts.map((t) => (t.length > MAX_CHARS ? t.slice(0, MAX_CHARS) : t));
265
+ const vecs = [];
266
+ for (let i = 0; i < clamped.length; i += B) {
267
+ const out = await model(clamped.slice(i, i + B), {
268
+ pooling: PROFILE.pool ?? 'mean',
269
+ normalize: true,
270
+ });
271
+ for (const v of out.tolist()) vecs.push(Float32Array.from(v));
272
+ }
273
+ return vecs;
274
+ });
275
+ }
276
+
277
+ // Every mode except --index reads vectors it did not build; refuse if they came from another model
278
+ // rather than returning scores that look plausible and mean nothing.
279
+ //
280
+ // --serve must never reach this, and today it cannot twice over: `modelChanged` is false for it
281
+ // because no DB is opened at all. The explicit `!flag('--serve')` stays as the one that states the
282
+ // INTENT, since the other is a side effect of an unrelated decision and would evaporate the moment
283
+ // anyone reopens that handle.
284
+ //
285
+ // The intent: this gate reads ONE index — the spawning project's, since memory-recall.mjs spawns
286
+ // with a cwd and no --slug. Right when a server served exactly that project; wrong now that it
287
+ // serves all of them, where a single stale index would exit(1) the shared server and silently kill
288
+ // recall for every OTHER project (the spawn is detached with stdio ignored, so nothing surfaces).
289
+ // loadIndex() applies the same check per slug at request time and throws, keeping one stale index
290
+ // to one failed request.
291
+ if (modelChanged && !flag('--index') && !flag('--serve')) {
292
+ console.error(
293
+ `index was built with ${storedModel}, but ${MODEL} is configured — run --index to rebuild.`,
294
+ );
295
+ process.exit(1);
296
+ }
297
+
298
+ // ---------------------------------------------------------------- coverage
299
+
300
+ // Is every note actually IN the index? Nobody had ever asked. A note missing from the index is
301
+ // indistinguishable from a note that ranks badly — both just fail to appear — so the whole class
302
+ // hides behind "retrieval is imperfect". obsidian-second-brain lists 100% index coverage as one of
303
+ // its measured gains, which is what prompted checking ours: it was 1047 of 1048.
304
+ if (flag('--coverage')) {
305
+ const onDisk = new Map(); // stem -> [paths]
306
+ for (const { dir } of vaultSources(VAULT, SLUG)) {
307
+ if (!fs.existsSync(dir)) continue;
308
+ for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.md')))
309
+ onDisk.set(f.slice(0, -3), [...(onDisk.get(f.slice(0, -3)) ?? []), path.join(dir, f)]);
310
+ }
311
+ const indexed = new Set(
312
+ /** @type {DatabaseSync} */ (db)
313
+ .prepare('SELECT DISTINCT note n FROM chunks')
314
+ .all()
315
+ .map((r) => r.n),
316
+ );
317
+ const missing = [...onDisk.keys()].filter((n) => !indexed.has(n));
318
+ // A stem that exists twice is worse than a missing note: the index keys by stem, so two files
319
+ // MERGE into one entry, best-chunk scoring mixes their content, and an Obsidian [[wikilink]] to
320
+ // that name is ambiguous too. It reads as full coverage while silently holding one note fewer.
321
+ const collisions = [...onDisk.entries()].filter(([, paths]) => paths.length > 1);
322
+ console.log(`project ${SLUG}`);
323
+ console.log(
324
+ ` on disk ${onDisk.size} distinct names (${[...onDisk.values()].flat().length} files) · indexed ${indexed.size}`,
325
+ );
326
+ if (missing.length)
327
+ console.log(` MISSING from the index (${missing.length}):\n ${missing.join('\n ')}`);
328
+ for (const [stem, paths] of collisions)
329
+ console.log(
330
+ ` NAME COLLISION "${stem}" — the index merges these into one entry:\n ${paths.join('\n ')}`,
331
+ );
332
+ if (!missing.length && !collisions.length)
333
+ console.log(' OK — every note is indexed exactly once.');
334
+ process.exit(missing.length || collisions.length ? 1 : 0);
335
+ }
336
+
337
+ // ---------------------------------------------------------------- embedding property check
338
+
339
+ // Batching pads every text to the longest in its group, and the padding CHANGES the output — the
340
+ // same string scored cosine 0.986 against itself on 2026-08-15, while competing notes here sit
341
+ // ~0.001 apart. No model card mentions it. Ten seconds, and it re-checks the property for whatever
342
+ // model is configured, instead of trusting that this one behaves like the last one.
343
+ if (flag('--check-embedding')) {
344
+ const t =
345
+ 'a representative note section about alarm thresholds, WAF rules and deployment controllers';
346
+ const [alone] = await embed([t]);
347
+ const [again] = await embed([t]);
348
+ const batched = (await embed([t, 'short', 'x'.repeat(1500)]))[0];
349
+ const self = cosine(alone, again),
350
+ mixed = cosine(alone, batched);
351
+ console.log(`model ${MODEL} batch=${PROFILE.batch ?? 1}`); // must mirror embed(); a stale default here reports a batch size the code does not use
352
+ console.log(` same text twice cosine ${self.toFixed(6)}`);
353
+ console.log(` alone vs in a batch cosine ${mixed.toFixed(6)}`);
354
+ const ok = self > 0.99999 && mixed > 0.99999;
355
+ console.log(
356
+ ok
357
+ ? ' OK — embedding is stable; batch company does not change the vector.'
358
+ : ` FAIL — batch company shifts the vector by ${(1 - mixed).toFixed(4)}. Set batch: 1 for this model.`,
359
+ );
360
+ process.exit(ok ? 0 : 1);
361
+ }
362
+
363
+ // ---------------------------------------------------------------- index
364
+
365
+ if (flag('--index')) {
366
+ const indexDb = /** @type {DatabaseSync} */ (db);
367
+ // The hook log's WORKER line, written only when the SessionStart gate started THIS run — see
368
+ // CLAUDE.md ("The indexer's line is guarded by MEMORY_INDEX_HOOK, not by the session id") for why
369
+ // a manual `/memory:prune` and the distiller's own end-of-distillation re-index must not be filed
370
+ // under this one.
371
+ //
372
+ // Registered ABOVE the lock, because the lock has its own `process.exit(0)`: below it, a run
373
+ // that stood down for a lock held elsewhere wrote no worker line at all, and a gate line saying
374
+ // `spawned` with no worker after it is exactly what the report teaches a reader to read as a
375
+ // run killed at its timeout.
376
+ /** @type {import('../hooks/lib/hook-io.mjs').HookOutcome} */
377
+ let workerOutcome = 'ran';
378
+ /** @type {string | undefined} */
379
+ let workerReason;
380
+ if (process.env.MEMORY_INDEX_HOOK)
381
+ process.on('exit', (code) =>
382
+ logHook({
383
+ hook: 'semantic-index-refresh',
384
+ event: 'worker',
385
+ cwd: process.cwd(),
386
+ session: process.env.MEMORY_HOOK_SESSION,
387
+ outcome: code === 0 ? workerOutcome : 'error',
388
+ reason: code === 0 ? workerReason : `exit ${code}`,
389
+ }),
390
+ );
391
+
392
+ // Cross-process write lock, PER MODEL — same scope as the DB it guards. A long background
393
+ // bge-m3 build must not stall the default profile's incremental refresh. (The cross-model
394
+ // corruption this lock was born from — a table holding 384-dim and 1024-dim vectors at once —
395
+ // is now structurally impossible: the two models no longer share a file.)
396
+ const lockDir = path.join(DB_DIR, `.index-${MODEL_KEY}.lock`);
397
+ let locked = false;
398
+ try {
399
+ fs.mkdirSync(lockDir);
400
+ locked = true;
401
+ } catch {
402
+ const age = Date.now() - (fs.statSync(lockDir).mtimeMs || 0);
403
+ if (age < 30 * 60 * 1000) {
404
+ console.log('another --index is running (lock held); skipping');
405
+ // A stand-down, not a re-index. Exiting 0 with the default outcome would report it as work
406
+ // that happened.
407
+ workerOutcome = 'debounced';
408
+ workerReason = 'another --index holds the lock';
409
+ process.exit(0);
410
+ }
411
+ fs.rmSync(lockDir, { recursive: true, force: true });
412
+ fs.mkdirSync(lockDir);
413
+ locked = true; // reclaim a lock left by a killed run
414
+ }
415
+ const releaseLock = () => {
416
+ if (locked) {
417
+ try {
418
+ fs.rmSync(lockDir, { recursive: true, force: true });
419
+ } catch {}
420
+ locked = false;
421
+ }
422
+ };
423
+ process.on('exit', releaseLock);
424
+ for (const sig of ['SIGINT', 'SIGTERM'])
425
+ process.on(sig, () => {
426
+ releaseLock();
427
+ process.exit(1);
428
+ });
429
+
430
+ const files = indexInput(VAULT, SLUG);
431
+
432
+ // --rebuild forces a full re-embed. Needed when the metadata cannot be trusted: a run that
433
+ // recorded the model without re-embedding leaves the DB claiming one model while holding another
434
+ // model's vectors, and no automatic check can see that.
435
+ if (schemaStale) {
436
+ indexDb.exec('ALTER TABLE chunks ADD COLUMN hash TEXT');
437
+ console.log('index predates the content-hash column; hashing existing notes in place');
438
+ }
439
+ if (modelChanged || flag('--rebuild')) {
440
+ console.log(
441
+ modelChanged
442
+ ? `model changed ${storedModel ?? '(unrecorded)'} → ${MODEL}; rebuilding the whole index (vectors are not comparable across models)`
443
+ : 'rebuilding the whole index',
444
+ );
445
+ indexDb.exec('DELETE FROM chunks');
446
+ }
447
+ indexDb
448
+ .prepare(
449
+ 'INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
450
+ )
451
+ .run('model', MODEL);
452
+
453
+ // Incremental, in two levels; drop rows for deleted notes.
454
+ // MAX(mtime)/MIN(hash) can in principle come from different rows — they cannot here, since every
455
+ // row of a file is written in one pass with the same pair.
456
+ const known = new Map(
457
+ /** @type {IndexedFile[]} */ (
458
+ indexDb
459
+ .prepare('SELECT file, MAX(mtime) AS mtime, MIN(hash) AS hash FROM chunks GROUP BY file')
460
+ .all()
461
+ ).map((r) => /** @type {[string, IndexedFile]} */ ([r.file, r])),
462
+ );
463
+ const live = new Set(files.map((f) => f.full));
464
+ let dropped = 0;
465
+ for (const f of known.keys())
466
+ if (!live.has(f)) {
467
+ indexDb.prepare('DELETE FROM chunks WHERE file = ?').run(f);
468
+ dropped++;
469
+ }
470
+ // Level 1 — mtime matches: skip WITHOUT reading the file. Unchanged, and it must stay that way;
471
+ // it is the only path a steady-state refresh takes for the whole vault.
472
+ // Level 2 — mtime moved: read, hash, and skip the embedding when the content is byte-identical.
473
+ // The read is not extra work for a note that really changed (the chunker needs the text anyway),
474
+ // so the added cost falls only on notes that merely LOOK stale — which on a synced vault is where
475
+ // the whole 20-40 min re-embed storm was coming from.
476
+ const stale = [];
477
+ const touched = []; // content identical, mtime moved: nothing to embed, but see the UPDATE below
478
+ const backfill = []; // rows written before the hash column existed: fill it, do not re-embed
479
+ for (const f of files) {
480
+ const prev = known.get(f.full);
481
+ if (prev && prev.mtime === f.mtime) {
482
+ // The one exception to "level 1 never reads", and it fires once per note in the life of an
483
+ // index. mtime equality is already what this code trusts to mean "the bytes the index
484
+ // embedded", so hashing them now only writes that same judgement down — no embedding is
485
+ // recomputed and no answer changes. This is the migration off a hash-less index, in place.
486
+ if (prev.hash == null) backfill.push({ ...f, hash: contentHash(fs.readFileSync(f.full)) });
487
+ continue;
488
+ }
489
+ const buf = fs.readFileSync(f.full);
490
+ const hash = contentHash(buf);
491
+ if (prev && prev.hash === hash) touched.push({ ...f, hash });
492
+ else stale.push({ ...f, raw: buf.toString('utf8'), hash });
493
+ }
494
+
495
+ // Write the new mtime for the notes sync only touched, and the hash for the ones migrating.
496
+ // Without the mtime write every later run re-reads and re-hashes them forever — cheap next to
497
+ // embedding, but it turns the fast path into the slow one for the entire vault, permanently.
498
+ //
499
+ // ONE transaction, not one per note. node:sqlite autocommits every statement, and this is the
500
+ // path the change exists to make fast — the storm case is "the whole vault's mtimes moved", so
501
+ // the loop runs once per note with nothing else in the run to hide an fsync behind. Measured
502
+ // 2026-08-19, 1000 files x 4 chunks: 667 ms un-transactioned against 31 ms wrapped. It is also
503
+ // all-or-nothing rather than a half-written mtime set.
504
+ if (touched.length || backfill.length) {
505
+ const bump = indexDb.prepare('UPDATE chunks SET mtime = ?, hash = ? WHERE file = ?');
506
+ indexDb.exec('BEGIN');
507
+ try {
508
+ for (const f of [...touched, ...backfill]) bump.run(f.mtime, f.hash, f.full);
509
+ indexDb.exec('COMMIT');
510
+ } catch (e) {
511
+ indexDb.exec('ROLLBACK');
512
+ throw e;
513
+ }
514
+ }
515
+
516
+ console.log(
517
+ `${files.length} notes · ${stale.length} to (re)embed · ${touched.length} mtime-only (content unchanged) · ${backfill.length} hashed in place · ${dropped} removed`,
518
+ );
519
+ if (!stale.length) {
520
+ console.log('index already current');
521
+ process.exit(0);
522
+ }
523
+
524
+ const del = indexDb.prepare('DELETE FROM chunks WHERE file = ?');
525
+ const ins = indexDb.prepare(
526
+ 'INSERT INTO chunks (note, layer, file, mtime, heading, text, vec, hash) VALUES (?,?,?,?,?,?,?,?)',
527
+ );
528
+ const pending = [];
529
+ for (const f of stale) {
530
+ del.run(f.full);
531
+ for (const c of chunkNote(f.note, f.raw))
532
+ pending.push({
533
+ ...c,
534
+ note: f.note,
535
+ layer: f.layer,
536
+ file: f.full,
537
+ mtime: f.mtime,
538
+ hash: f.hash,
539
+ });
540
+ }
541
+
542
+ const BATCH = PROFILE.batch ?? 1; // embed() slices to the same size; keep them equal
543
+ const t0 = Date.now();
544
+ for (let i = 0; i < pending.length; i += BATCH) {
545
+ const batch = pending.slice(i, i + BATCH);
546
+ const vecs = await embed(batch.map((b) => DOC_PREFIX + b.text));
547
+ batch.forEach((b, j) =>
548
+ // mtime 0 / hash NULL on the way in, and the real pair only once the file is FINISHED, a
549
+ // few lines down. Rows are autocommitted per batch and the SIGINT handler exits without a
550
+ // rollback, so a run killed part way through a file used to leave that file carrying its
551
+ // current mtime and hash over only the chunks that had landed — after which level 1 skipped
552
+ // it on every later run and the missing chunks were never searchable again, invisibly
553
+ // (--coverage passes on one surviving chunk). With the sentinel a half-written file fails
554
+ // both levels next run and is simply re-embedded (2026-08-19).
555
+ ins.run(b.note, b.layer, b.file, 0, b.heading, b.text, new Uint8Array(vecs[j].buffer), null),
556
+ );
557
+ try {
558
+ fs.utimesSync(lockDir, new Date(), new Date());
559
+ } catch {} // heartbeat: a slow model's build outlives the 30-min stale window
560
+ if ((i / BATCH) % 10 === 0)
561
+ console.log(` ${Math.min(i + BATCH, pending.length)}/${pending.length} chunks`);
562
+ }
563
+ // Commit the identity of every file whose chunks all landed. One transaction: this is what makes
564
+ // the run's result visible as a whole rather than as a half-finished state that looks finished.
565
+ const seal = indexDb.prepare('UPDATE chunks SET mtime = ?, hash = ? WHERE file = ?');
566
+ indexDb.exec('BEGIN');
567
+ try {
568
+ for (const f of stale) seal.run(f.mtime, f.hash, f.full);
569
+ indexDb.exec('COMMIT');
570
+ } catch (e) {
571
+ indexDb.exec('ROLLBACK');
572
+ throw e;
573
+ }
574
+
575
+ console.log(
576
+ `indexed ${pending.length} chunks from ${stale.length} notes in ${((Date.now() - t0) / 1000).toFixed(1)}s → ${DB_PATH}`,
577
+ );
578
+ process.exit(0);
579
+ }
580
+
581
+ // ---------------------------------------------------------------- consolidation gaps
582
+
583
+ if (flag('--clusters') || flag('--propose')) {
584
+ const min = Number(val('--min') || PROFILE.clusterMin);
585
+ // --size revives the flag deleted 2026-08-19 (no caller had ever set it) — --propose (#96) needs
586
+ // its candidate rule to be configuration, not a literal, so the default it inherits must be one.
587
+ const minSize = Number(val('--size') || 4);
588
+ const cards = /** @type {(CardRow & { mtime: number, file: string })[]} */ (
589
+ /** @type {DatabaseSync} */ (db)
590
+ .prepare('SELECT note, layer, text, vec, mtime, file FROM chunks WHERE heading = ?')
591
+ .all(CARD)
592
+ ).map((r) => ({
593
+ note: r.note,
594
+ layer: r.layer,
595
+ text: r.text,
596
+ vec: new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM),
597
+ mtime: r.mtime,
598
+ file: r.file,
599
+ }));
600
+ if (!cards.length) {
601
+ console.log('empty index — run --index first');
602
+ process.exit(1);
603
+ }
604
+
605
+ const permanent = cards
606
+ .filter((c) => c.layer === 'permanent')
607
+ .map((c) => {
608
+ try {
609
+ return { ...c, links: linkTargets(fs.readFileSync(c.file, 'utf8')) };
610
+ } catch {
611
+ return c;
612
+ }
613
+ });
614
+ const working = cards.filter((c) => c.layer !== 'permanent');
615
+ const { gaps, covered } = consolidationGaps(working, permanent, min, minSize);
616
+ const gapList = mistakesFirst(gaps);
617
+
618
+ if (flag('--propose')) {
619
+ const top = Number(val('--top') || 8);
620
+ const written = proposeStagingNotes(VAULT, SLUG, gapList.slice(0, top));
621
+ for (const r of written)
622
+ console.log(
623
+ `${r.status === 'written' ? 'proposed' : r.status}: Staging/${SLUG}/${r.file} (${r.members} members, best permanent/ ${r.bestScore})`,
624
+ );
625
+ console.log(
626
+ `\n${written.length} candidate(s). Draft each with /memory:synthesize, then /memory:adopt to promote.`,
627
+ );
628
+ process.exit(0);
629
+ }
630
+
631
+ console.log(
632
+ `${working.length} notes · ${permanent.length} permanent/ notes · clusters ≥${minSize} at ≥${min}: ${gapList.length}\n`,
633
+ );
634
+ for (const c of covered)
635
+ console.log(`covered by ${c.by} (links ${c.linked}/${c.members.length})`);
636
+ if (covered.length) console.log('');
637
+ const top = Number(val('--top') || 8);
638
+ const shown = gapList.slice(0, top);
639
+ for (const { members: g, best, typical, borderline } of shown) {
640
+ const mix = g.reduce(
641
+ (m, x) => ((m[x.layer] = (m[x.layer] || 0) + 1), m),
642
+ /** @type {Record<string, number>} */ ({}),
643
+ );
644
+ console.log(
645
+ `${g.length} notes — ${Object.entries(mix)
646
+ .map(([k, v]) => `${v} ${k}`)
647
+ .join(', ')}`,
648
+ );
649
+ console.log(
650
+ borderline
651
+ ? ` nearest permanent/: ${best.note} ${best.s.toFixed(3)} vs typical member ${typical.toFixed(3)} — borderline; check whether it should absorb this`
652
+ : ` no permanent/ note covers this (best ${best.note ?? 'n/a'} ${best.s.toFixed(3)} vs typical member ${typical.toFixed(3)})`,
653
+ );
654
+ // Every member, never a preview: /memory:synthesize step 2 must read every note in the cluster,
655
+ // and a truncated list is how a synthesis silently gets built from part of one. The 6-member
656
+ // cap and its `--members` escape hatch were deleted 2026-08-19 — nothing ever passed the flag,
657
+ // and clusters are a handful of notes each.
658
+ for (const x of g) console.log(` · [${x.layer}] ${x.note}`);
659
+ console.log('');
660
+ }
661
+ console.log(
662
+ gapList.length
663
+ ? `${gapList.length} topic(s) with no consolidated note${gapList.length > shown.length ? ` (showing the first ${shown.length}: Mistakes first, then largest)` : ''}. Writing one is a judgement call — this only finds where it is missing.`
664
+ : 'every cluster is covered by a permanent/ note.',
665
+ );
666
+ process.exit(0);
667
+ }
668
+
669
+ // ---------------------------------------------------------------- cross-folder duplicates (#96)
670
+
671
+ if (flag('--cross-dupes')) {
672
+ const linkMin = Number(val('--min') || PROFILE.clusterMin);
673
+ const dupeMin = Number(val('--dupe-min') || PROFILE.dupeMin);
674
+ const minSize = Number(val('--size') || 4); // same clustering step as --clusters/--propose
675
+ const cards = /** @type {CardRow[]} */ (
676
+ /** @type {DatabaseSync} */ (db)
677
+ .prepare('SELECT note, layer, text, vec FROM chunks WHERE heading = ?')
678
+ .all(CARD)
679
+ ).map((r) => ({
680
+ note: r.note,
681
+ layer: r.layer,
682
+ text: r.text,
683
+ vec: new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM),
684
+ }));
685
+ const working = cards.filter((c) => c.layer !== 'permanent');
686
+ const clusters = clusterNotes(working, linkMin).filter((g) => g.length >= minSize);
687
+ let found = 0;
688
+ for (const g of clusters) {
689
+ const pairs = crossFolderPairs(g, dupeMin);
690
+ for (const p of pairs) {
691
+ found++;
692
+ console.log(
693
+ flag('--tsv')
694
+ ? ['cross-dupe', p.s.toFixed(3), p.a.layer, p.a.note, p.b.layer, p.b.note].join('\t')
695
+ : `${p.s.toFixed(3)} — [${p.a.layer}] ${p.a.note} ⟷ [${p.b.layer}] ${p.b.note}`,
696
+ );
697
+ }
698
+ }
699
+ if (flag('--tsv')) process.exit(0);
700
+ console.log(
701
+ found
702
+ ? `\n${found} cross-folder pair(s) at ≥${dupeMin} within a topic cluster — same lesson, different folder. Not auto-merged: judge each, then mark kept pairs with memory-mark.mjs.`
703
+ : 'no cross-folder near-duplicates within any cluster.',
704
+ );
705
+ process.exit(0);
706
+ }
707
+
708
+ // ---------------------------------------------------------------- dedup
709
+
710
+ if (flag('--dupes')) {
711
+ const min = Number(val('--min') || PROFILE.dupeMin);
712
+ // One vector per note: the '(card)' chunk carries title + description + the opening body, which
713
+ // for a short Insight note is effectively the whole note. Comparing cards keeps this O(notes²)
714
+ // (~165k pairs, well under a second) instead of O(chunks²).
715
+ const rawCards = /** @type {(CardRow & { file: string })[]} */ (
716
+ /** @type {DatabaseSync} */ (db)
717
+ .prepare('SELECT note, layer, file, text, vec FROM chunks WHERE heading = ?')
718
+ .all(CARD)
719
+ );
720
+ assertVectorWidth(rawCards, DIM, 'dupes');
721
+ const cards = rawCards.map((r) => ({
722
+ note: r.note,
723
+ layer: r.layer,
724
+ text: r.text,
725
+ vec: new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM),
726
+ }));
727
+ if (!cards.length && !tsvDupes) {
728
+ console.log('empty index — run --index first');
729
+ process.exit(1);
730
+ }
731
+ const fileOf = new Map(rawCards.map((r) => [r.note, r.file]));
732
+ const pairs = reportPairs(cards, min, (n) => isManual(fileOf.get(n) ?? ''));
733
+ if (flag('--tsv')) {
734
+ for (const p of pairs)
735
+ console.log(['dupe', p.s.toFixed(3), p.layer, p.a, p.layer, p.b].join('\t'));
736
+ process.exit(0);
737
+ }
738
+ const byNote = new Map(cards.map((c) => [c.note, c]));
739
+ console.log(`${cards.length} notes · same-folder pairs ≥ ${min}: ${pairs.length}`);
740
+ console.log('(pairs with either note marked reconcile: manual are not reported)');
741
+ console.log('(cross-folder pairs are complementary by design and are not reported)\n');
742
+ for (const p of pairs.slice(0, Number(val('--top') || 30))) {
743
+ console.log(`${p.s.toFixed(3)} [${p.layer}]`);
744
+ for (const n of [p.a, p.b])
745
+ console.log(
746
+ ` ${n}\n ${/** @type {Card} */ (byNote.get(n)).text.replace(/\s+/g, ' ').slice(0, 130)}…`,
747
+ );
748
+ }
749
+ console.log('\nJudge each pair: merge when it adds coverage, keep when it only removes a file.');
750
+ process.exit(0);
751
+ }
752
+
753
+ // ---------------------------------------------------------------- dedup eval
754
+
755
+ // The acceptance check for the write-time reconcile — the arm this replaced shipped on a measurement
756
+ // taken against the wrong distribution (11/16 on the pairs the slug arm had missed, 0/25 on the
757
+ // corpus) and reports CAUGHT/total with the FALSE count beside it, swept over every same-folder pair
758
+ // rather than only the truth set. See CLAUDE.md ("dupe-eval") and
759
+ // docs/decisions/2026-08-23-embedding-reconcile.md (the fires/caught/false sweep table).
760
+ //
761
+ // Truth file is JSONL, one record per judged pair: {"a": note, "b": note, "verdict": "dupe"|"keep"}.
762
+ // The KEEPS are part of the truth — cross-linking two distinct notes correctly RAISES their
763
+ // similarity and can push a keep pair over the bar; see
764
+ // docs/decisions/2026-08-23-embedding-reconcile.md ("An opt-out"). The truth file itself is
765
+ // gitignored, because it names a private vault's notes — see docs/architecture.md (the `eval/`
766
+ // row) and docs/plans/2026-08-23-embedding-reconcile.md.
767
+ if (flag('--dupe-eval')) {
768
+ const truthFile = val('--truth');
769
+ if (!truthFile) {
770
+ console.log('usage: --dupe-eval --truth <file.jsonl> [--bars 0.75,0.70]');
771
+ process.exit(1);
772
+ }
773
+ const rawCards = /** @type {CardRow[]} */ (
774
+ /** @type {DatabaseSync} */ (db)
775
+ .prepare('SELECT note, layer, text, vec FROM chunks WHERE heading = ?')
776
+ .all(CARD)
777
+ );
778
+ assertVectorWidth(rawCards, DIM, 'dupe-eval');
779
+ const cards = rawCards.map((r) => ({
780
+ note: r.note,
781
+ layer: r.layer,
782
+ vec: new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM),
783
+ }));
784
+ if (!cards.length) {
785
+ console.log('empty index, run --index first');
786
+ process.exit(1);
787
+ }
788
+ /** @type {Set<string>} */
789
+ const dupes = new Set();
790
+ /** @type {Set<string>} */
791
+ const keeps = new Set();
792
+ /** @type {{ a: string, b: string, verdict: string }[]} */
793
+ const truth = [];
794
+ for (const line of fs.readFileSync(truthFile, 'utf8').split('\n')) {
795
+ if (!line.trim()) continue;
796
+ const rec = JSON.parse(line);
797
+ truth.push(rec);
798
+ (rec.verdict === 'keep' ? keeps : dupes).add(pairKey(rec.a, rec.b));
799
+ }
800
+ // A truth record naming a note the index does not hold is a truth file that has drifted past the
801
+ // vault, usually a merged or renamed note. Silence here would deflate the caught column and read
802
+ // as a worse predicate.
803
+ const known = new Set(cards.map((c) => c.note));
804
+ const absent = truth.filter((r) => !known.has(r.a) || !known.has(r.b));
805
+ if (absent.length) {
806
+ console.log(`${absent.length} truth pair(s) name notes absent from the index:`);
807
+ for (const r of absent.slice(0, 10)) console.log(` ${r.a} / ${r.b}`);
808
+ console.log('');
809
+ }
810
+ const bars = (val('--bars') || String(PROFILE.dupeMin)).split(',').map(Number);
811
+ console.log(`${cards.length} notes, truth: ${dupes.size} dupe, ${keeps.size} keep\n`);
812
+ console.log('bar fires caught missed false keeps-proposed');
813
+ /** @type {{ s: number, a: string, b: string }[]} */
814
+ let missedAt = [];
815
+ const cell = (/** @type {number|string} */ v, /** @type {number} */ w) => String(v).padStart(w);
816
+ for (const bar of bars) {
817
+ const pairs = samefolderPairs(cards, bar);
818
+ const r = sweepDupes(pairs, dupes, keeps);
819
+ console.log(
820
+ `${bar.toFixed(2)} ${cell(r.fires, 6)} ${cell(r.caught, 4)}/${dupes.size} ` +
821
+ `${cell(r.missed, 6)} ${cell(r.falses, 5)} ${cell(r.keepsProposed, 14)}`,
822
+ );
823
+ if (bar === bars[0]) {
824
+ const fired = new Set(pairs.map((p) => pairKey(p.a, p.b)));
825
+ const byNote = new Map(cards.map((c) => [c.note, c]));
826
+ missedAt = truth
827
+ .filter((x) => x.verdict !== 'keep' && !fired.has(pairKey(x.a, x.b)))
828
+ .map((x) => {
829
+ const a = byNote.get(x.a);
830
+ const b = byNote.get(x.b);
831
+ return { s: a && b ? dupeScore(a, b) : NaN, a: x.a, b: x.b };
832
+ })
833
+ .sort((y, z) => z.s - y.s);
834
+ }
835
+ }
836
+ if (missedAt.length) {
837
+ console.log(`\nmissed at ${bars[0]}:`);
838
+ for (const m of missedAt) console.log(` ${m.s.toFixed(3)} ${m.a} / ${m.b}`);
839
+ }
840
+ console.log(
841
+ '\n"false" is every firing not in the truth set as a duplicate, including unjudged pairs.',
842
+ );
843
+ console.log('"keeps-proposed" is what the reconcile: manual mark exists to suppress.');
844
+ process.exit(0);
845
+ }
846
+
847
+ // ---------------------------------------------------------------- query
848
+
849
+ if (!queries.length && !flag('--serve')) {
850
+ console.log(
851
+ 'usage: --index | --query "question" [--query "..."] [-k 5] [--all-projects] | --serve | --coverage | --dupes | --clusters | --propose | --cross-dupes',
852
+ );
853
+ process.exit(1);
854
+ }
855
+ const K = Number(val('-k') || 5);
856
+ const LEX_MODE = process.env.MEMORY_FUSE_LEX ?? DEFAULT_FUSE_LEX;
857
+
858
+ /**
859
+ * Everything a query needs for ONE project, as a value rather than module state.
860
+ *
861
+ * It used to be module state, which is exactly why there had to be a server per project: the slug
862
+ * was fixed before the socket existed. As a value, one process serves every project — and since the
863
+ * model is ~1.3GB against ~15MB of vectors for a 3400-chunk index, the thing worth sharing is the
864
+ * model, not the process.
865
+ *
866
+ * Throws rather than exiting: for the CLI a bad index is fatal, but for the server it is one bad
867
+ * request among many, and a server that called process.exit() on a stale slug would take every other
868
+ * project down with it.
869
+ *
870
+ * @param {string} slug
871
+ * @returns {import('./lib/memory-semantic.mjs').Bundle}
872
+ */
873
+ function loadIndex(slug) {
874
+ if (!isIndexedSlug(DB_DIR, slug)) throw new Error(`no index for ${slug} — run --index first`);
875
+ const dbPath = path.join(DB_DIR, `semantic-${slug}-${MODEL_KEY}.db`);
876
+ // Closed in the finally: `.all()` materialises every row, so nothing below needs the handle, and
877
+ // node:sqlite does NOT free it on GC. Measured 2026-08-17 — 200 unclosed DatabaseSync opens held
878
+ // 201 fds, unchanged after an explicit global.gc(). In a 30-minute server that reopens on every
879
+ // mtime bump, for every project, that is an fd leak ending in EMFILE. The same reason
880
+ // unloadEmbedder() calls dispose() rather than trusting the garbage collector.
881
+ const idb = new DatabaseSync(dbPath);
882
+ try {
883
+ // Same guard the CLI applies, per index: vectors from another model are noise that looks like a
884
+ // score, and in a multi-project server one stale index must not be answered from.
885
+ //
886
+ const stored = idb.prepare("SELECT value FROM meta WHERE key = 'model'").get()?.value;
887
+ const total = /** @type {{ c: number }} */ (idb.prepare('SELECT COUNT(*) c FROM chunks').get())
888
+ .c;
889
+ if (total && stored !== MODEL)
890
+ throw new Error(`index for ${slug} was built with ${stored}, not ${MODEL} — run --index`);
891
+ const rows = /** @type {ChunkRow[]} */ (
892
+ idb.prepare('SELECT note, layer, heading, text, vec, file, mtime FROM chunks').all()
893
+ );
894
+ if (!rows.length) throw new Error('empty index — run --index first');
895
+ return buildBundle(slug, dbPath, rows, {
896
+ dropAliases: process.env.MEMORY_NO_ALIAS_CHUNKS === '1',
897
+ lexMode: LEX_MODE,
898
+ dim: DIM,
899
+ });
900
+ } finally {
901
+ try {
902
+ idb.close();
903
+ } catch {
904
+ /* already closed, or never opened cleanly — nothing left to release */
905
+ }
906
+ }
907
+ }
908
+
909
+ /** Each skip is logged once: `--serve` calls this on every `all` request. */
910
+ const skipped = new Set();
911
+
912
+ /**
913
+ * Every real project's index as ONE bundle (mergeProjectRows). A stale or empty index is skipped,
914
+ * not fatal: one bad project must not silence the others.
915
+ * @param {(slug: string) => import('./lib/memory-semantic.mjs').Bundle} load
916
+ */
917
+ function allProjects(load) {
918
+ /** @type {import('./lib/memory-semantic.mjs').Bundle[]} */
919
+ const parts = [];
920
+ for (const slug of projectSlugs(DB_DIR, VAULT)) {
921
+ try {
922
+ parts.push(load(slug));
923
+ } catch (e) {
924
+ const line = `skipped ${slug}: ${/** @type {Error} */ (e).message}`;
925
+ if (!skipped.has(line)) console.log(line);
926
+ skipped.add(line);
927
+ }
928
+ }
929
+ const sig = parts.map((b) => `${b.slug}@${b.loadedAt}`).join();
930
+ const merged = () =>
931
+ buildBundle('*', DB_DIR, mergeProjectRows(parts.map((b) => [b.slug, b.rowsUsed])), {
932
+ lexMode: LEX_MODE,
933
+ dim: DIM,
934
+ });
935
+ return { sig, merged };
936
+ }
937
+
938
+ // ---------------------------------------------------------------- serve
939
+ //
940
+ // Holds the model and index warm — a query becomes a socket round-trip instead of a ~1.5s/~3.1s
941
+ // load. Idle-exits so it cannot become a forgotten daemon; the hook respawns on demand. See
942
+ // docs/architecture.md "Flow 3 — the search daemon" for the MRR comparison that motivated it
943
+ // (0.158 keyword-only vs 0.547 this path).
944
+ if (flag('--serve')) {
945
+ const net = await import('node:net');
946
+ const sockPath = SERVE_SOCK; // probed and cleaned above; do NOT unlink again — by now another
947
+ // server may legitimately own the path, and stealing it is what made these multiply.
948
+ const IDLE_MS = paths.serveIdleMs();
949
+ const MODEL_IDLE_MS = paths.modelIdleMs();
950
+ const quit = () => {
951
+ try {
952
+ fs.unlinkSync(sockPath);
953
+ } catch {}
954
+ process.exit(0);
955
+ };
956
+
957
+ // Two timers, because the process and the model are two very different costs. The model is ~1.3G
958
+ // and goes first; the process is ~150M once it has, and can afford to linger holding its indexes.
959
+ let idle = setTimeout(quit, IDLE_MS);
960
+ /** @type {NodeJS.Timeout | null} */
961
+ let modelIdle = null;
962
+ const armModelIdle = () => {
963
+ if (modelIdle) clearTimeout(modelIdle);
964
+ modelIdle = setTimeout(async () => {
965
+ // A request still holding the session (see singleFlight.borrow) means the unload declines.
966
+ // Re-arm rather than give up: only a new connection calls bump(), so without this the model
967
+ // would sit loaded until the next request or the process exit — and the "retries on the next
968
+ // tick" this comment claims would simply not be true.
969
+ if (embedderCell.busy()) return armModelIdle();
970
+ if (await unloadEmbedder())
971
+ console.log(`unloaded model after ${MODEL_IDLE_MS / 60000}m idle`);
972
+ }, MODEL_IDLE_MS);
973
+ modelIdle.unref?.(); // must never be the reason the event loop stays alive
974
+ };
975
+ const bump = () => {
976
+ clearTimeout(idle);
977
+ idle = setTimeout(quit, IDLE_MS);
978
+ armModelIdle();
979
+ };
980
+
981
+ // Indexes are per project and loaded on demand — this is what lets ONE process serve every
982
+ // project instead of one process per project. They are cheap next to the model (~15M of vectors
983
+ // for 3400 chunks against ~1.3G of weights), so they are cached and never evicted; the process
984
+ // idle timer is the upper bound on how long they live. The staleness policy lives in mtimeCache():
985
+ // the index changes under us as notes are written, and a stale one is answered from silently.
986
+ const indexCache = mtimeCache((slug) => {
987
+ const fresh = loadIndex(slug);
988
+ console.log(`loaded index ${slug} (${fresh.rowsUsed.length} chunks)`);
989
+ return fresh;
990
+ });
991
+ function indexFor(/** @type {string} */ slug) {
992
+ if (!isIndexedSlug(DB_DIR, slug)) throw new Error(`no index for ${slug} — run --index first`);
993
+ let mtime = NaN; // a failed stat must RELOAD, not serve a cached index forever
994
+ try {
995
+ mtime = fs.statSync(path.join(DB_DIR, `semantic-${slug}-${MODEL_KEY}.db`)).mtimeMs;
996
+ } catch {
997
+ /* gone or unreadable — let loadIndex() report it properly */
998
+ }
999
+ return indexCache.get(slug, mtime);
1000
+ }
1001
+
1002
+ // Rebuilt only when a part reloads, from the per-project cache above — not by re-reading every DB,
1003
+ // which took 2.4 s and so missed the hook's 700 ms timeout after any index changed (2026-12-02).
1004
+ /** @type {{ sig: string, bundle: import('./lib/memory-semantic.mjs').Bundle } | null} */
1005
+ let allCache = null;
1006
+ function allIndex() {
1007
+ const { sig, merged } = allProjects(indexFor);
1008
+ if (allCache?.sig !== sig) allCache = { sig, bundle: merged() };
1009
+ return allCache.bundle;
1010
+ }
1011
+
1012
+ // Pay the model load now, not on the first real request. The hook only spawns this server because
1013
+ // it just had no answer, so the prompt after next is the one that benefits.
1014
+ await embed(['warm up so the first real request is not the one that pays for the model load']);
1015
+
1016
+ const server = net.createServer((sock) => {
1017
+ bump();
1018
+ let buf = '';
1019
+ sock.on('data', async (d) => {
1020
+ buf += d;
1021
+ if (!buf.includes('\n')) return;
1022
+ const line = buf.slice(0, buf.indexOf('\n'));
1023
+ buf = '';
1024
+ try {
1025
+ const msg = JSON.parse(line);
1026
+ // A newer server has taken over — see evictableSockets(). Acknowledge first so it is not
1027
+ // left waiting on a socket that vanishes mid-write.
1028
+ if (msg.quit) {
1029
+ sock.end(JSON.stringify({ quitting: MODEL_KEY }) + '\n', quit);
1030
+ return;
1031
+ }
1032
+ // The slug is now a REQUEST field, not process state. Falling back to the server's own slug
1033
+ // keeps an older hook working against a newer server rather than answering from the wrong
1034
+ // project — the one failure that would be invisible, since wrong notes still look like notes.
1035
+ // Dupe mode: raw cosine against CARD vectors, not the query path's fused score. Answered
1036
+ // here rather than by a second process because this server already holds the model and the
1037
+ // per-slug index; the distiller's alternative was a 1.3GB model load per SessionEnd.
1038
+ // `mode` in the reply is load-bearing — an older server does not error on a request missing
1039
+ // it, it embeds the literal string "undefined" and answers confidently. See
1040
+ // docs/plans/2026-08-23-embedding-reconcile.md ("Socket dupe mode").
1041
+ if (typeof msg.dupe === 'string') {
1042
+ const { slug = SLUG, layer = '', min = PROFILE.dupeMin } = msg;
1043
+ const index = indexFor(slug);
1044
+ const [cv] = await embed([DOC_PREFIX + msg.dupe]);
1045
+ const cards = index.rowsUsed
1046
+ .filter((r) => r.heading === CARD)
1047
+ .map((r) => ({
1048
+ note: r.note,
1049
+ layer: r.layer,
1050
+ vec: new Float32Array(r.vec.buffer, r.vec.byteOffset, DIM),
1051
+ }));
1052
+ sock.end(
1053
+ JSON.stringify({
1054
+ mode: 'dupe',
1055
+ slug,
1056
+ best: bestDupe(cards, { layer, vec: cv }, min),
1057
+ // Returned so the caller can compare notes written earlier in the SAME run, which no
1058
+ // index has seen yet. Batching them into this request instead would make the server
1059
+ // embed more than one text at a time, and batch size is pinned to 1 because padding
1060
+ // changes the embedding.
1061
+ vec: Array.from(cv),
1062
+ }) + '\n',
1063
+ );
1064
+ return;
1065
+ }
1066
+ // `all` is the cross-project read; the hook decides it from config, the server just obeys.
1067
+ const { q, k = 5, slug = SLUG, all = false } = msg;
1068
+ const index = all ? allIndex() : indexFor(slug);
1069
+ const [qv] = await embed([QUERY_PREFIX + q]);
1070
+ const top = searchIn(index, q, qv, k);
1071
+ sock.end(
1072
+ JSON.stringify({
1073
+ slug,
1074
+ results: top.map(({ r, s }) => ({
1075
+ note: r.name ?? r.note,
1076
+ project: r.project,
1077
+ layer: r.layer,
1078
+ heading: r.heading,
1079
+ text: index.cardByNote.get(r.note) ?? r.text,
1080
+ matched: r.heading,
1081
+ score: +s.toFixed(4),
1082
+ })),
1083
+ }) + '\n',
1084
+ );
1085
+ } catch (e) {
1086
+ sock.end(JSON.stringify({ error: String(/** @type {Error} */ (e).message ?? e) }) + '\n');
1087
+ }
1088
+ });
1089
+ sock.on('error', () => {});
1090
+ });
1091
+ // The probe above closes the window to ~1ms, not to zero: loading the index takes seconds, and
1092
+ // two hooks firing in that gap both get past it. Losing the bind race is not an error — the other
1093
+ // server is serving. Without this the loser died on an unhandled 'error' event, and since it is
1094
+ // spawned detached with stdio ignored, the stack trace went nowhere.
1095
+ server.on('error', (/** @type {NodeJS.ErrnoException} */ e) => {
1096
+ if (e.code === 'EADDRINUSE') {
1097
+ console.log(`already serving ${MODEL_KEY} (lost bind race)`);
1098
+ process.exit(0);
1099
+ }
1100
+ console.error(`serve failed: ${e.message}`);
1101
+ process.exit(1);
1102
+ });
1103
+ server.listen(sockPath, async () => {
1104
+ console.log(
1105
+ `serving ${MODEL_KEY} on ${sockPath} (all projects, model idle ${MODEL_IDLE_MS / 60000}m, exit ${IDLE_MS / 60000}m)`,
1106
+ );
1107
+ // The slug is a request field since 0.3.0, so one connection can read every indexed project.
1108
+ // macOS does not enforce unix-socket permissions uniformly, so this is defence in depth rather
1109
+ // than a guarantee — and never fatal: a server that cannot chmod must still serve (2026-08-18).
1110
+ try {
1111
+ fs.chmodSync(sockPath, 0o600);
1112
+ } catch {}
1113
+ armModelIdle(); // nothing has been served yet, so the model must already be on the clock
1114
+ // Take over from any leftover server. AFTER listen, so a failed bind never evicts the server
1115
+ // that beat us to it. Best-effort throughout: one that ignores us dies on its own idle timer,
1116
+ // which is the whole safety net here.
1117
+ const runDir = path.dirname(sockPath);
1118
+ const own = path.basename(sockPath);
1119
+ let evicted = 0;
1120
+ for (const name of evictableSockets(fs.readdirSync(runDir), own)) {
1121
+ const done = await new Promise((resolve) => {
1122
+ const c = net.createConnection(path.join(runDir, name));
1123
+ const fin = (/** @type {boolean} */ v) => {
1124
+ try {
1125
+ c.destroy();
1126
+ } catch {}
1127
+ resolve(v);
1128
+ };
1129
+ const t = setTimeout(() => fin(false), 1000);
1130
+ c.on('connect', () => c.write(JSON.stringify(QUIT) + '\n'));
1131
+ c.on('data', () => {
1132
+ clearTimeout(t);
1133
+ fin(true);
1134
+ });
1135
+ c.on('error', () => {
1136
+ clearTimeout(t);
1137
+ fin(false); // nobody home; its own startup probe unlinks the leftover
1138
+ });
1139
+ });
1140
+ if (done) evicted++;
1141
+ }
1142
+ if (evicted) console.log(`evicted ${evicted} stale server(s) — other model, or per-project`);
1143
+ });
1144
+ for (const sig of ['SIGINT', 'SIGTERM'])
1145
+ process.on(sig, () => {
1146
+ try {
1147
+ fs.unlinkSync(sockPath);
1148
+ } catch {}
1149
+ process.exit(0);
1150
+ });
1151
+ } else {
1152
+ // The CLI is single-project by nature — its slug comes from cwd or --slug. A bad index here IS
1153
+ // fatal, unlike in the server, so the throw becomes the usage message it always was.
1154
+ let selfIndex;
1155
+ try {
1156
+ selfIndex = flag('--all-projects') ? allProjects(loadIndex).merged() : loadIndex(SLUG);
1157
+ } catch (e) {
1158
+ console.error(/** @type {Error} */ (e).message);
1159
+ process.exit(1);
1160
+ }
1161
+ const qvecs = await embed(queries.map((q) => QUERY_PREFIX + q));
1162
+ queries.forEach((q, qi) => {
1163
+ const top = searchIn(selfIndex, q, qvecs[qi], K);
1164
+ // --json: one machine-readable line per query, so the eval harness can score a whole case set in
1165
+ // a single process (the model loads once, not once per question).
1166
+ if (flag('--json')) {
1167
+ console.log(
1168
+ JSON.stringify({
1169
+ q,
1170
+ // `text` as --serve sends it, so the eval's injectedNotes() meets the hook's char budget.
1171
+ results: top.map(({ r, s }) => ({
1172
+ note: r.name ?? r.note,
1173
+ project: r.project,
1174
+ layer: r.layer,
1175
+ score: +s.toFixed(4),
1176
+ text: selfIndex.cardByNote.get(r.note) ?? r.text,
1177
+ })),
1178
+ }),
1179
+ );
1180
+ return;
1181
+ }
1182
+ if (flag('--tsv')) {
1183
+ for (const line of tsvLines(top)) console.log(line);
1184
+ return;
1185
+ }
1186
+ console.log(`\n## ${q}`);
1187
+ for (const { r, s } of top)
1188
+ console.log(
1189
+ ` ${s.toFixed(3)} [${r.layer}${r.project ? ` · ${r.project}` : ''}] ${r.name ?? r.note} — ${r.heading}\n ${r.text.replace(/\s+/g, ' ').slice(0, 150)}…`,
1190
+ );
1191
+ });
1192
+ }