@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,753 @@
1
+ #!/usr/bin/env node
2
+ // Reproducible retrieval eval — CLI entry. Generates a versioned case set once, then scores any
3
+ // retrieval change against THE SAME cases.
4
+ //
5
+ // Thin on purpose: argv, files, stdout. The scoring helpers and their tests live in
6
+ // lib/memory-eval.mjs.
7
+ //
8
+ // Usage:
9
+ // node memory-eval.mjs --author < cases.jsonl the way to make a REAL paraphrase set
10
+ // node memory-eval.mjs --generate 40 [--style semantic|keyword] [--out <path>]
11
+ // node memory-eval.mjs --run [--cases <path>] [--mode semantic|lexical] [--json]
12
+ // Flags take a space, never `=`. `--cases`/`--out` both override the per-project default on --run;
13
+ // leave them off unless you mean to score a set that is not this project's.
14
+ //
15
+ // Cases live in $CLAUDE_MEMORY_HOME/eval/ and are GITIGNORED: they contain vault content.
16
+ // Regenerate only with --force; a changed case set invalidates every past number.
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { execFileSync } from 'node:child_process';
20
+ import { activeModel } from './lib/model-default.mjs';
21
+ import * as paths from '../hooks/lib/paths.mjs';
22
+ import {
23
+ evalBody,
24
+ pickSentence,
25
+ metrics,
26
+ lexicalRank,
27
+ goldCoverage,
28
+ defaultCasesPath,
29
+ unscorableReason,
30
+ pairwise,
31
+ abstains,
32
+ caseQuery,
33
+ injectedNotes,
34
+ injection,
35
+ TYPE,
36
+ gateFailures,
37
+ casesHash,
38
+ followCases,
39
+ kindOfPath,
40
+ KIND,
41
+ GOLD,
42
+ GOLD_FLOOR,
43
+ RECALL_KS,
44
+ } from './lib/memory-eval.mjs';
45
+ import { minePrompts } from './lib/memory-mine.mjs';
46
+ import { readRedirects } from './lib/memory-merge.mjs';
47
+
48
+ // ---------------------------------------------------------------- setup
49
+
50
+ const argv = process.argv.slice(2);
51
+ /** @param {string} n @returns {boolean} */
52
+ const flag = (n) => argv.includes(n);
53
+ // A flag whose value went missing used to score the DEFAULT case set and print a number the
54
+ // operator read as belonging to the file they had just named — #97's own failure, reached by a typo
55
+ // instead of by a doc. `--cases` last in argv yielded undefined; `--cases --mode lexical` yielded
56
+ // `--mode`. Checked HERE rather than against a list of value-taking flags, because every one of
57
+ // them already passes through this function and a list would silently miss the next one added.
58
+ /**
59
+ * @param {string} n
60
+ * @param {boolean} [bare] value optional — only `--generate`, whose bare form means 40
61
+ * @returns {string|null}
62
+ */
63
+ const val = (n, bare = false) => {
64
+ const i = argv.indexOf(n);
65
+ if (i < 0) return null;
66
+ const v = argv[i + 1];
67
+ if (!bare && (!v || v.startsWith('--'))) {
68
+ console.log(`${n} needs a value.`);
69
+ process.exit(1);
70
+ }
71
+ return v ?? null;
72
+ };
73
+ // The other shape of the same hole, and the one no `val()` call can see: `--cases=other.jsonl`
74
+ // matches no flag at all, so it was dropped in silence. Refuse it rather than guess.
75
+ const equalsArg = argv.find((a) => /^--[\w-]+=/.test(a));
76
+ if (equalsArg) {
77
+ const [name, ...rest] = equalsArg.split('=');
78
+ console.log(`${name} takes a space-separated value. Write: ${name} ${rest.join('=')}`);
79
+ process.exit(1);
80
+ }
81
+ // And the last shape: a misspelled flag NAME — `--casess other.jsonl` matched nothing and was
82
+ // dropped. A closed set is safe to keep by hand because it fails CLOSED: a name missing from it
83
+ // errors on first use instead of going quiet. A test ties it to the call sites.
84
+ const KNOWN_FLAGS = new Set([
85
+ '--run',
86
+ '--author',
87
+ '--generate',
88
+ '--force',
89
+ '--json',
90
+ '--cases',
91
+ '--out',
92
+ '--vault',
93
+ '--slug',
94
+ '--style',
95
+ '--mode',
96
+ '--fetch-k',
97
+ '--mine',
98
+ '--kind',
99
+ '--min-rank1',
100
+ '--freeze',
101
+ ]);
102
+ const unknownFlag = argv.find((a) => a.startsWith('--') && !KNOWN_FLAGS.has(a));
103
+ if (unknownFlag) {
104
+ console.log(`unknown flag ${unknownFlag}. Known: ${[...KNOWN_FLAGS].join(' ')}`);
105
+ process.exit(1);
106
+ }
107
+ const repo =
108
+ argv
109
+ .filter((a) => !a.startsWith('--'))
110
+ .find((a) => fs.existsSync(a) && fs.statSync(a).isDirectory()) || process.cwd();
111
+ // --vault/--slug point this at a generated benchmark vault instead of the real one, which is how
112
+ // a retrieval change gets scored against a FIXED note set. Explicit flags, not CLAUDE_VAULT: an
113
+ // env override once sent a relocating hook at a throwaway path and cost 24 notes.
114
+ const VAULT = val('--vault') || paths.vault();
115
+ const SLUG = val('--slug') || paths.projectKey(repo);
116
+ // Echo the resolved project. `repo` defaults to cwd, so running this from ~/.claude silently
117
+ // evaluates the CONFIG repo's near-empty vault — hit three separate times on 2026-08-14, once per
118
+ // script, always with a confident-looking wrong answer.
119
+ console.error(`project: ${SLUG} (from ${repo})`);
120
+ const STYLE = val('--style') || 'semantic';
121
+ // Default `tuning`, so every existing invocation resolves the file it always did. An unknown kind
122
+ // throws rather than falling through, which would print a tuning number under a held-out label.
123
+ const CASE_KIND = val('--kind') || KIND.tuning;
124
+ // Case sets are generated FROM a real vault and contain its content, so they live in
125
+ // machine-local state, never in the plugin (which is a public repo).
126
+ const DATA = paths.stateDir('eval');
127
+ let SCOPED_CASES;
128
+ try {
129
+ SCOPED_CASES = defaultCasesPath(DATA, SLUG, STYLE, CASE_KIND);
130
+ } catch (e) {
131
+ console.log(String(e instanceof Error ? e.message : e));
132
+ process.exit(1);
133
+ }
134
+ const CASES = val('--cases') || val('--out') || SCOPED_CASES;
135
+ // From the FILE, never the flag: `--kind` decides which file the DEFAULT resolves to, and does not
136
+ // get to assert what an explicit `--cases` path is. It warns rather than deferring silently,
137
+ // because the freeze banner is what gets pasted into an issue as provenance.
138
+ const REPORTED_KIND = kindOfPath(CASES);
139
+ if (val('--kind') && CASE_KIND !== REPORTED_KIND)
140
+ console.error(
141
+ `warning: --kind ${CASE_KIND} ignored — ${path.basename(CASES)} is a ${REPORTED_KIND} set, and the file decides.`,
142
+ );
143
+
144
+ /** @typedef {{ note: string, layer: string, file: string }} EvalNote */
145
+
146
+ // permanent/ is a retrieval target like any other — consolidated notes are often the BEST answer,
147
+ // so leaving them out both hides misses and rejects valid gold notes.
148
+ /** @type {[string, string][]} vault-relative dir, layer */
149
+ const NOTE_DIRS = [
150
+ [path.join('Memory', SLUG), 'Memory'],
151
+ ...['Patterns', 'Mistakes', 'Decisions'].map(
152
+ (l) => /** @type {[string, string]} */ ([path.join('Insights', SLUG, l), l]),
153
+ ),
154
+ ...['', 'domain', 'tools'].map(
155
+ (d) => /** @type {[string, string]} */ ([path.join('permanent', d), 'permanent']),
156
+ ),
157
+ ];
158
+
159
+ /** @returns {EvalNote[]} */
160
+ function allNotes() {
161
+ /** @type {EvalNote[]} */
162
+ const out = [];
163
+ /** @param {string} dir @param {string} layer */
164
+ const add = (dir, layer) => {
165
+ if (!fs.existsSync(dir)) return;
166
+ for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('.md'))) {
167
+ if (f === 'REFLECTIONS.md' || f === 'MEMORY.md') continue;
168
+ out.push({ note: f.slice(0, -3), layer, file: path.join(dir, f) });
169
+ }
170
+ };
171
+ for (const [d, layer] of NOTE_DIRS) add(path.join(VAULT, d), layer);
172
+ return out;
173
+ }
174
+
175
+ // A case set is JSONL, so a truncated write leaves one unparseable line. Bare `JSON.parse` threw a
176
+ // SyntaxError and a stack trace from inside a `.map()`, which reads as a crash rather than as the
177
+ // bad input it is — and it fired BEFORE the malformed-case guard written to report exactly this.
178
+ /**
179
+ * @param {string} text
180
+ * @param {string} src
181
+ * @returns {{ q: string, gold?: unknown, layer?: string, style?: string }[]}
182
+ */
183
+ const parseJsonl = (text, src) => {
184
+ const out = [];
185
+ for (const [i, l] of text.trim().split('\n').filter(Boolean).entries()) {
186
+ try {
187
+ out.push(JSON.parse(l));
188
+ } catch {
189
+ console.log(`${src}: line ${i + 1} is not valid JSON — truncated or malformed.`);
190
+ process.exit(1);
191
+ }
192
+ }
193
+ return out;
194
+ };
195
+
196
+ // A question has to contain something searchable (2026-08-23). Blank was the first version, but
197
+ // `"???"` is not blank and still tokenises to nothing: every BM25 score ties at 0, so the ranking
198
+ // is whatever order the documents arrived in. The reported figure is then not a measurement at all
199
+ // — 100% on the 3-note fixture where k exceeds the corpus, 0.0% on the 60-note bench vault. One
200
+ // letter or digit is the general form of "not empty to the retriever".
201
+ //
202
+ // `\p{L}\p{N}` with the `u` flag, never `\w`: JS's `\w` is ASCII-only where Python's is unicode-
203
+ // aware, so `\w` would reject 日本語 and every other non-Latin question in a vault that has them.
204
+ //
205
+ // `typeof` first and spelled out: `q` is JSON.parse output, so it can be a number, and
206
+ // `(42)?.trim()` throws where the type test refuses. The short form shipped for one commit.
207
+ /** @param {unknown} q @returns {boolean} */
208
+ const isQuestion = (q) => typeof q === 'string' && /[\p{L}\p{N}]/u.test(q);
209
+
210
+ // ---------------------------------------------------------------- mine
211
+
212
+ // --mine <dir>[,<dir>…]: emit candidate questions from Claude Code transcripts as {q} JSONL, with
213
+ // NO gold. It never writes a case set. Assigning gold is the human's half, and keeping the two
214
+ // halves in different hands is the whole point of a held-out set (#87) — a producer that wrote both
215
+ // would reproduce the failure that put inflated figures in five artefacts.
216
+ //
217
+ // A LIST of roots, because one project's history is spread over several cwd-slug folders and the
218
+ // deduplication has to span them: two folders holding 142 candidates each hold 142 between them
219
+ // (2026-09-05), so mining them separately would report the pool at exactly twice its size.
220
+ //
221
+ // Candidates go to stdout and the tally to stderr, so the output pipes into an editor or a
222
+ // labelling pass while the operator still sees what was dropped.
223
+ if (flag('--mine')) {
224
+ const roots = (val('--mine') || '').split(',').filter(Boolean);
225
+ const absent = roots.filter((r) => !fs.existsSync(r));
226
+ if (!roots.length || absent.length) {
227
+ console.log(
228
+ `--mine needs transcript directories. Not found: ${absent.join(', ') || '(none given)'}`,
229
+ );
230
+ process.exit(1);
231
+ }
232
+ // Recursive: Claude Code keeps one FOLDER per cwd-slug, so a useful root is the parent of many
233
+ // folders as often as it is one folder.
234
+ const notDir = roots.filter((r) => !fs.statSync(r).isDirectory());
235
+ if (notDir.length) {
236
+ console.log(`--mine takes transcript DIRECTORIES, not files: ${notDir.join(', ')}`);
237
+ process.exit(1);
238
+ }
239
+ const files = roots.flatMap((r) => {
240
+ try {
241
+ return fs
242
+ .readdirSync(r, { recursive: true })
243
+ .map(String)
244
+ .filter((f) => f.endsWith('.jsonl'))
245
+ .map((f) => path.join(r, f));
246
+ } catch (e) {
247
+ // Skip and continue, the same as the per-file read below: mining is best-effort.
248
+ console.error(`skipping ${r}: ${e instanceof Error ? e.message : e}`);
249
+ return [];
250
+ }
251
+ });
252
+ const seen = new Set();
253
+ let turns = 0;
254
+ for (const f of files) {
255
+ let text;
256
+ try {
257
+ text = fs.readFileSync(f, 'utf8');
258
+ } catch {
259
+ continue; // a transcript deleted mid-walk is not an error worth stopping a mining run for
260
+ }
261
+ turns += minePrompts(text.split('\n'), seen).turns;
262
+ }
263
+ for (const q of seen) console.log(JSON.stringify({ q }));
264
+ // Read, kept and dropped, all three: a candidate count alone cannot tell an operator whether the
265
+ // filters are too tight or the history is too thin, and those want opposite responses.
266
+ console.error(
267
+ `${files.length} transcripts under ${roots.length} root(s): ${turns} user turns → ${seen.size} candidates (${turns - seen.size} dropped as noise or duplicate)`,
268
+ );
269
+ console.error('No gold notes attached — assign them by hand, then pipe to --author.');
270
+ process.exit(0);
271
+ }
272
+
273
+ // ---------------------------------------------------------------- freeze
274
+
275
+ // --freeze: record a case set's identity as a sha256 sidecar. The set stays machine-local (vault
276
+ // content), so the hash is what gets quoted; `--run` verifies it whenever one exists.
277
+ if (flag('--freeze')) {
278
+ if (!fs.existsSync(CASES)) {
279
+ console.log(`no case set at ${CASES} to freeze.`);
280
+ process.exit(1);
281
+ }
282
+ const h = casesHash(fs.readFileSync(CASES, 'utf8'));
283
+ const side = `${CASES}.sha256`;
284
+ // Re-freezing is how a set gets edited unnoticed, so it takes --force.
285
+ if (fs.existsSync(side) && fs.readFileSync(side, 'utf8').trim() !== h && !flag('--force')) {
286
+ console.log(
287
+ `${side} records a DIFFERENT set. Re-freezing invalidates every number quoted against the old hash — pass --force if that is what you want.`,
288
+ );
289
+ process.exit(1);
290
+ }
291
+ fs.writeFileSync(side, `${h}\n`);
292
+ console.log(`${REPORTED_KIND} set frozen: ${CASES}\n sha256 ${h}`);
293
+ console.log(
294
+ 'Quote this hash wherever you quote a number from this set; the questions stay local.',
295
+ );
296
+ process.exit(0);
297
+ }
298
+
299
+ // ---------------------------------------------------------------- generate
300
+
301
+ // --author: read {q, gold} JSONL on stdin, validate every gold note exists, and save as the case
302
+ // set. This is how a REAL paraphrase set is made: the agent writes the questions once (it is the
303
+ // LLM the upstream harness calls out to), then scoring is reproducible forever after.
304
+ if (flag('--author')) {
305
+ const known = new Set(allNotes().map((n) => n.note));
306
+ const lines = parseJsonl(fs.readFileSync(0, 'utf8'), 'stdin');
307
+ const cases = [],
308
+ bad = [];
309
+ for (const c of lines) {
310
+ // Same trust boundary as --run: this is input someone wrote, not a shape we can assume. Both
311
+ // fields, because guarding `gold` and then dereferencing `c.q` two lines later just moves the
312
+ // TypeError down the function.
313
+ const q = caseQuery(c, repo);
314
+ if (!isQuestion(q) || !Array.isArray(c.gold)) {
315
+ console.log(
316
+ `every case needs a question and a gold array — got: ${JSON.stringify(c).slice(0, 80)}`,
317
+ );
318
+ process.exit(1);
319
+ }
320
+ const missing = c.gold.filter((g) => !known.has(g));
321
+ if (missing.length) {
322
+ bad.push(`${missing.join(', ')} (Q: ${String(q).slice(0, 60)})`);
323
+ continue;
324
+ }
325
+ cases.push({ ...c, style: c.style || 'semantic-authored' });
326
+ }
327
+ if (bad.length) {
328
+ console.log(`gold note(s) not found — fix these first:\n ${bad.join('\n ')}`);
329
+ process.exit(1);
330
+ }
331
+ // `--run` would refuse the hash mismatch afterwards, but by then the questions are gone.
332
+ if (fs.existsSync(`${CASES}.sha256`) && !flag('--force')) {
333
+ console.log(
334
+ `${CASES} is frozen. Re-authoring replaces the questions every number quoted against its hash was measured on — pass --force if that is what you want, then --freeze --force.`,
335
+ );
336
+ process.exit(1);
337
+ }
338
+ // Never write an empty set. `--author` has no --force gate, so an upstream producer that failed,
339
+ // a `< /dev/null`, or a filter that matched nothing would silently replace the authored baseline
340
+ // every past number was measured against — the same data loss `--generate` was just given a
341
+ // guard for, still live on the branch that shares its parser.
342
+ if (!cases.length) {
343
+ console.log(`no cases on stdin — refusing to overwrite ${CASES} with nothing.`);
344
+ process.exit(1);
345
+ }
346
+ fs.writeFileSync(CASES, cases.map((c) => JSON.stringify(c)).join('\n') + '\n');
347
+ console.log(`${cases.length} authored cases → ${CASES}`);
348
+ process.exit(0);
349
+ }
350
+
351
+ if (flag('--generate')) {
352
+ // `--generate` extracts sentences the note contains verbatim (its banner below: BM25 finds them
353
+ // trivially). Under the held-out name that is an inflated number with a publishable hash.
354
+ if (CASE_KIND === KIND.heldOut) {
355
+ console.log(
356
+ '--generate cannot make a held-out set: it extracts sentences the notes already contain.\n' +
357
+ 'Mine candidates with --mine, assign gold by hand, then --author --kind held-out.',
358
+ );
359
+ process.exit(1);
360
+ }
361
+ // `--generate` may be bare, so `val()` cannot refuse a missing value here — and what follows is
362
+ // then the NEXT FLAG. `Number('--force')` is NaN, the stride is NaN, the sample loop never runs,
363
+ // and `--generate --force` wrote an EMPTY case set over a real one and exited 0. A count is
364
+ // either a positive number or absent; anything else is a typo worth stopping for.
365
+ const count = val('--generate', true);
366
+ const n = !count || count.startsWith('--') ? 40 : Number(count);
367
+ if (!Number.isInteger(n) || n < 1) {
368
+ console.log(`--generate takes a positive count, got: ${count}`);
369
+ process.exit(1);
370
+ }
371
+ if (fs.existsSync(CASES) && !flag('--force')) {
372
+ console.log(
373
+ `${CASES} exists. Regenerating invalidates every past number — pass --force if that is what you want.`,
374
+ );
375
+ process.exit(1);
376
+ }
377
+ const notes = allNotes();
378
+ // Deterministic sample: sort by name and stride. Math.random would make the set unreproducible,
379
+ // which is the exact failure this harness exists to fix.
380
+ notes.sort((a, b) => (a.note < b.note ? -1 : 1));
381
+ const stride = Math.max(1, Math.floor(notes.length / n));
382
+ const cases = [];
383
+ for (let i = 0; i < notes.length && cases.length < n; i += stride) {
384
+ const nt = notes[i];
385
+ const q = pickSentence(evalBody(fs.readFileSync(nt.file, 'utf8')), nt.note, STYLE);
386
+ if (q) cases.push({ q, gold: [nt.note], layer: nt.layer, style: STYLE });
387
+ }
388
+ fs.writeFileSync(CASES, cases.map((c) => JSON.stringify(c)).join('\n') + '\n');
389
+ console.log(`${cases.length} cases (${STYLE}) → ${CASES}`);
390
+ console.log('Gitignored by the deny-by-default rule: these contain vault content.');
391
+ console.log(
392
+ '\n⚠ These are EXTRACTED SENTENCES, not paraphrases — the note contains them verbatim,',
393
+ );
394
+ console.log(
395
+ ' so BM25 finds them trivially (2026-08-15 real-vault set: lexical recall@1 97.5% vs semantic 62.5%;',
396
+ );
397
+ console.log(
398
+ ' the lexical arm has since moved to the shared tokeniser: -5 points recall@1 on',
399
+ ' cases-paraphrase, 55.0% -> 50.0%, seed-7 bench vault; cases-keyword unchanged).',
400
+ );
401
+ console.log(
402
+ ' Useful as a lexical-recall floor and an index-coverage check; NOT a paraphrase test.',
403
+ );
404
+ console.log(' For that, author real questions and pipe them to --author.');
405
+ process.exit(0);
406
+ }
407
+
408
+ // ---------------------------------------------------------------- run
409
+
410
+ if (!flag('--run')) {
411
+ console.log('usage: --generate N [--style semantic|keyword] | --run [--mode semantic|lexical]');
412
+ process.exit(1);
413
+ }
414
+ if (!fs.existsSync(CASES)) {
415
+ // --author, not --generate: `--generate` emits extracted sentences, which commands/eval.md calls
416
+ // useless as a paraphrase test. Pointing the two branches at different tools taught half the
417
+ // callers the wrong one.
418
+ console.log(`no case set at ${CASES}. Author one first: --author (see /memory:eval)`);
419
+ process.exit(1);
420
+ }
421
+ // existsSync is true for a directory, and readFileSync then threw EISDIR with a stack. A mistyped
422
+ // --cases is bad input, not a crash. Testing for a DIRECTORY rather than for a regular file, so
423
+ // `--cases <(jq …)` and `--cases /dev/stdin` — a pipe and a character device — still work.
424
+ if (fs.statSync(CASES).isDirectory()) {
425
+ console.log(`${CASES} is a directory. --cases takes a .jsonl case set.`);
426
+ process.exit(1);
427
+ }
428
+ const casesText = fs.readFileSync(CASES, 'utf8');
429
+ // A set that no longer hashes to its sidecar is not this set.
430
+ const sidecar = `${CASES}.sha256`;
431
+ let frozen = null;
432
+ if (fs.existsSync(sidecar)) {
433
+ // Unreadable or a directory is bad input, the way a mistyped --cases is.
434
+ let want;
435
+ try {
436
+ want = fs.readFileSync(sidecar, 'utf8').trim();
437
+ } catch (e) {
438
+ console.log(`${sidecar} exists but cannot be read: ${e instanceof Error ? e.message : e}`);
439
+ process.exit(1);
440
+ }
441
+ const got = casesHash(casesText);
442
+ frozen = got;
443
+ if (want !== got) {
444
+ console.log(
445
+ `${CASES} has changed since it was frozen.\n frozen ${want}\n now ${got}\n` +
446
+ `Every number quoted against the frozen hash was measured on different questions. Re-freeze with --freeze --force if the edit was intended.`,
447
+ );
448
+ process.exit(1);
449
+ }
450
+ }
451
+ const cases =
452
+ /** @type {{ q: string, gold: string[], owner?: string, layer?: string, style?: string, type?: string }[]} */ (
453
+ parseJsonl(casesText, CASES)
454
+ );
455
+ for (const c of cases) c.q = /** @type {string} */ (caseQuery(c, repo));
456
+
457
+ // A line with no gold array is not a case. goldCoverage skips them, so a file of three good cases
458
+ // and one truncated line passed coverage as `ok` and then killed the scorer on `c.gold.includes`.
459
+ // Refuse the file: half a case set cannot produce a number anyone should read.
460
+ // Both fields, matching --author. Guarding `gold` alone left a line with gold and no question
461
+ // reaching the scorer, which then threw on `c.q` — the same crash one field over. What counts as a
462
+ // question is `isQuestion()` above; a number from no question is the thing this guard refuses,
463
+ // whether it arrives by a wrong corpus or by a blank line.
464
+ const malformed = cases.filter((c) => !isQuestion(c.q) || !Array.isArray(c.gold)).length;
465
+ if (malformed) {
466
+ console.log(
467
+ `${malformed} of ${cases.length} case lines are missing a question or a gold array — truncated or malformed. Refusing to report a number.\n` +
468
+ ` case set: ${CASES}`,
469
+ );
470
+ process.exit(1);
471
+ }
472
+
473
+ // Without its owner a supersede case would score as recall, where its gold is the loser by design.
474
+ const ownerless = cases.filter((c) => c.type === TYPE.supersede && !c.owner).length;
475
+ if (ownerless) {
476
+ console.log(
477
+ `${ownerless} supersede case(s) name no owner, the newer note. Refusing to report a number.\n case set: ${CASES}`,
478
+ );
479
+ process.exit(1);
480
+ }
481
+
482
+ // Refuse a case set that is not about this vault — why, and the measurement, in `goldCoverage`.
483
+ const known = new Set(allNotes().map((n) => n.note));
484
+ // Nothing to score against at all. Diagnosed before coverage, because zero resolvable gold is a
485
+ // property of the VAULT here, and the mismatch branch below would blame the case set for it.
486
+ if (!known.size) {
487
+ console.log(
488
+ `no notes for ${SLUG} in ${VAULT} — nothing to score against.\n` +
489
+ `Check --vault/--slug, or sync the vault before scoring.`,
490
+ );
491
+ process.exit(1);
492
+ }
493
+ // Followed in memory, never written back, so a frozen set's hash still holds: a merged gold is the
494
+ // same lesson, now in the survivor.
495
+ const followed = followCases(
496
+ cases,
497
+ known,
498
+ readRedirects(VAULT, new Set(NOTE_DIRS.map(([d]) => d))),
499
+ );
500
+ if (followed)
501
+ console.error(`followed ${followed} gold/owner name(s) to the note it was merged into.`);
502
+ const cov = goldCoverage(cases, known);
503
+ // An abstention case names no gold by design, so a set of nothing else has no coverage to check.
504
+ const allAbstain = cases.length > 0 && cases.every((c) => c.type === TYPE.abstain);
505
+ if (cov.verdict === GOLD.mismatch && !allAbstain) {
506
+ // Both tests, because either alone reintroduces the other's bug. The path says WHETHER an
507
+ // override matters — `--cases <the scoped path>` is not one, and "drop it" hands back the same
508
+ // file. The flag says WHICH to name — `--out` overrides too.
509
+ const override =
510
+ CASES === SCOPED_CASES ? null : (['--cases', '--out'].find((f) => val(f)) ?? null);
511
+ const fix = !override
512
+ ? `This IS ${SLUG}'s own set, so the vault has moved out from under it. Re-author it with --author.`
513
+ : `Drop ${override} to use this project's own set: ${SCOPED_CASES}\nAuthor one with --author if it does not exist yet.`;
514
+ // An empty or gold-less file is a mismatch by the same arithmetic, but calling it another vault's
515
+ // case set would be a false diagnosis of a truncated or half-written one.
516
+ const why = cov.total
517
+ ? `${cov.resolved}/${cov.total} gold notes in this case set exist in ${SLUG}'s vault — under the ${Math.round(GOLD_FLOOR * 100)}% floor.\n` +
518
+ `That is a case set built from a DIFFERENT vault, not a bad score. Refusing to report a number.`
519
+ : `This case set names no gold notes at all — it is empty, truncated, or malformed. Refusing to report a number.`;
520
+ console.log(`${why}\n case set: ${CASES}\n${fix}`);
521
+ process.exit(1);
522
+ }
523
+ if (cov.verdict === GOLD.churn)
524
+ console.error(
525
+ `warning: ${cov.total - cov.resolved}/${cov.total} gold notes no longer exist (pruned?). Scoring the rest; every missing one counts as a miss.`,
526
+ );
527
+
528
+ const mode = val('--mode') || 'semantic';
529
+ // A rank-window intervention (reserved slots, re-ranking) is invisible when the harness fetches a
530
+ // wider window than a session does: promoted items sort to the bottom by score, so scoring @5 from
531
+ // a k=10 fetch shows nothing at @5. --fetch-k measures what the caller actually sees; only ks up to
532
+ // it are reported, since a k=5 fetch cannot answer @10.
533
+ // Validated like --generate, and for the same reason: `--fetch-k abc` made K NaN, which emptied KS,
534
+ // which printed no recall bars at all while `--json` still reported every k as 0 and exited 0. An
535
+ // all-zero number attributed to a named case set is the failure this whole guard exists to stop.
536
+ const K = Number(val('--fetch-k') || Math.max(...RECALL_KS));
537
+ if (!Number.isInteger(K) || K < 1) {
538
+ console.log(`--fetch-k takes a positive whole number, got: ${val('--fetch-k')}`);
539
+ process.exit(1);
540
+ }
541
+ const KS = RECALL_KS.filter((k) => k <= K);
542
+
543
+ // --min-rank1 turns a report into a GATE: below the floor the process exits non-zero. A percentage,
544
+ // to match how the numbers are quoted. Validated like --fetch-k: NaN would compare false and pass
545
+ // every run silently, which is the failure the flag exists to prevent.
546
+ const minRaw = flag('--min-rank1') ? Number(val('--min-rank1')) : null;
547
+ if (minRaw !== null && (!Number.isFinite(minRaw) || minRaw < 0 || minRaw > 100)) {
548
+ console.log(`--min-rank1 takes a percentage between 0 and 100, got: ${val('--min-rank1')}`);
549
+ process.exit(1);
550
+ }
551
+ const MIN_RANK1 = minRaw === null ? null : minRaw / 100;
552
+
553
+ /** @type {{ q: string, results: { note: string }[] }[]} */
554
+ let ranked; // [{q, results:[{note}]}]
555
+ if (mode === 'semantic') {
556
+ const args = ['--json', '-k', String(K), repo];
557
+ // Forward the vault override, or the child searches the REAL vault while this process scores
558
+ // against the benchmark one — two different note sets, one silent mismatch.
559
+ if (val('--vault')) args.push('--vault', /** @type {string} */ (val('--vault')));
560
+ if (val('--slug')) args.push('--slug', /** @type {string} */ (val('--slug')));
561
+ for (const c of cases) args.push('--query', c.q);
562
+ const out = execFileSync('node', [path.join(paths.scriptsDir, 'memory-semantic.mjs'), ...args], {
563
+ encoding: 'utf8',
564
+ maxBuffer: 64 * 1024 * 1024,
565
+ });
566
+ ranked = out
567
+ .trim()
568
+ .split('\n')
569
+ .filter((l) => l.startsWith('{'))
570
+ .map((l) => JSON.parse(l));
571
+ } else {
572
+ // Lexical arm: a local BM25 stand-in, NOT ctx_search. It exists so a retrieval change can be
573
+ // compared against a keyword baseline on the same cases inside one process. It does not reproduce
574
+ // context-mode's ranking, and a number from it is not a claim about ctx_search — nor about the
575
+ // recall hook, which scores a different document unit. See lexicalRank's comment.
576
+ ranked = lexicalRank(
577
+ allNotes().map((n) => ({ note: n.note, text: evalBody(fs.readFileSync(n.file, 'utf8')) })),
578
+ cases.map((c) => c.q),
579
+ K,
580
+ );
581
+ }
582
+
583
+ // BM25 is not cosine, so the hook's gate cannot judge a lexical run. Skipped, not unscorable:
584
+ // unscorable gates under --min-rank1, and these cases never gate.
585
+ const skipped = mode === 'semantic' ? [] : cases.filter((c) => c.type === TYPE.abstain);
586
+ const scored = cases.map((c, i) => {
587
+ const res = ranked[i]?.results || [];
588
+ const abstain = c.type === TYPE.abstain;
589
+ return {
590
+ q: c.q,
591
+ gold: c.gold[0],
592
+ layer: c.layer,
593
+ type: c.type,
594
+ rank: res.findIndex((r) => c.gold.includes(r.note)) + 1,
595
+ // A pairwise case inverts what `gold` means — it names the note that must LOSE — so it is
596
+ // scored by pairwise() and kept out of recall@k, where it would count as a miss by design.
597
+ pair: c.owner ? pairwise(/** @type {{gold: string[], owner: string}} */ (c), res) : null,
598
+ abstained: abstain ? abstains(res) : null,
599
+ relevant: c.gold,
600
+ injected: mode === 'semantic' ? injectedNotes(res) : [],
601
+ unscorable: unscorableReason(c, res, known),
602
+ top1: res[0]?.note ?? null,
603
+ };
604
+ });
605
+ const perCase = scored.filter((c) => !c.pair && c.type !== TYPE.abstain);
606
+ // Unscorable pairwise cases leave BOTH sides of the tally, or `gold: []` counts as a pass in the
607
+ // line people paste (`named` is Infinity, so `owner < named` is vacuously true).
608
+ const owned = scored.filter((c) => c.pair && !c.unscorable);
609
+ const pairs = owned.filter((c) => c.type !== TYPE.supersede);
610
+ const supersede = owned.filter((c) => c.type === TYPE.supersede);
611
+ const supersedeFails = supersede.filter((c) => !c.pair?.pass);
612
+ const abstain = skipped.length
613
+ ? []
614
+ : scored.filter((c) => c.type === TYPE.abstain && !c.unscorable);
615
+ const spoke = abstain.filter((c) => !c.abstained);
616
+ // Semantic only, like abstention: the hook gates on cosine. Pairwise gold is a loser, not relevant.
617
+ const inj = mode === 'semantic' ? injection(scored.filter((c) => !c.pair && !c.unscorable)) : null;
618
+ const { recall, mrr } = metrics(perCase);
619
+ const misses = perCase.filter((c) => !c.rank);
620
+ const buried = perCase.filter((c) => c.rank > 3);
621
+ const unscorable = scored.filter((c) => c.unscorable);
622
+ const pairFails = pairs.filter((c) => !c.pair?.pass);
623
+ // Before either report branch: --json exits on its own, and an automated caller is the only caller
624
+ // a gate is for.
625
+ const failures = gateFailures({
626
+ recall1: recall[1],
627
+ minRank1: MIN_RANK1,
628
+ unscorable: unscorable.length,
629
+ pairFails: pairFails.length,
630
+ recallCases: perCase.length,
631
+ });
632
+
633
+ // Every semantic number is model-dependent, so the model IS part of the measurement. Reporting a
634
+ // recall figure without it is the provenance gap CLAIM-1 exists to catch.
635
+ const model = mode === 'semantic' ? activeModel() : 'bm25';
636
+ if (flag('--json')) {
637
+ console.log(
638
+ JSON.stringify(
639
+ // goldResolved/goldTotal: the churn warning is stderr prose, so a machine reading this
640
+ // envelope could not tell a full case set from one a prune had eaten a quarter of.
641
+ {
642
+ cases: CASES,
643
+ kind: REPORTED_KIND,
644
+ mode,
645
+ model,
646
+ fetchK: K,
647
+ n: perCase.length,
648
+ goldResolved: cov.resolved,
649
+ goldTotal: cov.total,
650
+ // KS, not every k. The comment on KS says a k=5 fetch cannot answer @10 — and the human
651
+ // path honours that while this one printed the lot, so `--fetch-k 3 --json` reported an
652
+ // @5 and an @10 that were @3 censored to the window. Indistinguishable from a measurement
653
+ // to whatever reads this, which is the whole failure #97 is about.
654
+ // Omitted, never zero: metrics() divides by `|| 1`, so an all-pairwise set shipped
655
+ // `recall: {1:0,…}` to a consumer that could not tell it from a measurement.
656
+ ...(perCase.length
657
+ ? { recall: Object.fromEntries(KS.map((k) => [k, recall[k]])), mrr: +mrr.toFixed(3) }
658
+ : {}),
659
+ // Its own key: a consumer must be able to tell a case that scored zero from one never
660
+ // scored at all.
661
+ unscorable: unscorable.length,
662
+ // Null when no sidecar exists — deleting one un-freezes a set silently.
663
+ frozen,
664
+ pairwise: { total: pairs.length, failed: pairFails.length },
665
+ supersede: { total: supersede.length, passed: supersede.length - supersedeFails.length },
666
+ abstain: {
667
+ total: abstain.length,
668
+ passed: abstain.length - spoke.length,
669
+ ...(skipped.length ? { skipped: skipped.length } : {}),
670
+ },
671
+ ...(inj ? { injection: inj } : {}),
672
+ gate: failures,
673
+ },
674
+ null,
675
+ 2,
676
+ ),
677
+ );
678
+ process.exit(failures.length ? 1 : 0);
679
+ }
680
+ // A number whose set kind is unknown is not printable (#87).
681
+ console.log(
682
+ `${perCase.length} cases · ${REPORTED_KIND} · style ${cases[0]?.style ?? '?'} · mode ${mode} · model ${model}`,
683
+ );
684
+ // Name the file the number came from, the way the `project:` echo names the vault. Every failure
685
+ // in #97 is a figure attributed to a case set nobody checked; a number printed beside its source
686
+ // cannot be silently misread, whatever routed us to the wrong one.
687
+ console.log(` cases: ${CASES}`);
688
+ console.log(frozen ? ` frozen: ${frozen}` : ' frozen: no (this set is not pinned)');
689
+ // metrics() divides by `|| 1`, so an all-pairwise set rendered a bar chart no case contributed to.
690
+ if (!perCase.length) console.log(' no recall cases in this set — typed or pairwise cases only');
691
+ else {
692
+ for (const k of KS)
693
+ console.log(
694
+ ` recall@${String(k).padEnd(2)} ${(recall[k] * 100).toFixed(1).padStart(5)}% ${'#'.repeat(Math.round(recall[k] * 40))}`,
695
+ );
696
+ console.log(` MRR ${mrr.toFixed(3)}`);
697
+ console.log(
698
+ ` misses (gold absent from top ${K}): ${misses.length} buried (rank>3): ${buried.length}`,
699
+ );
700
+ }
701
+ // What beat the gold note is the diagnosis: a keyword magnet, a near-duplicate, or a better answer.
702
+ if (misses.length) {
703
+ console.log('\nMisses — and what ranked #1 instead:');
704
+ for (const m of misses.slice(0, 10))
705
+ console.log(` want ${m.gold}\n got ${m.top1}\n Q: ${m.q.slice(0, 90)}`);
706
+ }
707
+ if (buried.length) {
708
+ console.log('\nBuried (found, but below rank 3):');
709
+ for (const b of buried.slice(0, 8))
710
+ console.log(` rank ${b.rank} ${b.gold} (beaten by ${b.top1})`);
711
+ }
712
+ if (pairs.length)
713
+ console.log(
714
+ `\nPairwise (owner must outrank the named note): ${pairs.length - pairFails.length}/${pairs.length} passed`,
715
+ );
716
+ // `absent` rather than `Infinity`: an owner that never appeared is a vocabulary gap, one that came
717
+ // second is a ranking gap, and they want opposite fixes.
718
+ const rankLabel = (/** @type {number} */ r) => (Number.isFinite(r) ? String(r) : 'absent');
719
+ for (const f of pairFails.slice(0, 8))
720
+ console.log(
721
+ ` owner ${rankLabel(f.pair?.owner ?? Infinity)} named ${rankLabel(f.pair?.named ?? Infinity)} Q: ${f.q.slice(0, 70)}`,
722
+ );
723
+ if (supersede.length)
724
+ console.log(
725
+ `\nSupersession (the newer note must outrank the one it replaced): ${supersede.length - supersedeFails.length}/${supersede.length} passed`,
726
+ );
727
+ for (const f of supersedeFails.slice(0, 8))
728
+ console.log(
729
+ ` newer ${rankLabel(f.pair?.owner ?? Infinity)} older ${rankLabel(f.pair?.named ?? Infinity)} Q: ${f.q.slice(0, 70)}`,
730
+ );
731
+ if (abstain.length)
732
+ console.log(
733
+ `\nAbstention (the recall hook must inject nothing): ${abstain.length - spoke.length}/${abstain.length} passed`,
734
+ );
735
+ for (const f of spoke.slice(0, 8)) console.log(` injected ${f.top1} Q: ${f.q.slice(0, 70)}`);
736
+ if (inj)
737
+ console.log(
738
+ `\nInjection (the recall hook's server path): precision ${inj.precision == null ? 'n/a' : `${(inj.precision * 100).toFixed(1)}%`} over ${inj.injecting} injecting case(s), ${inj.relevantInjected}/${inj.injected} notes relevant · false injection ${inj.falseInjections}/${inj.noRelevant}`,
739
+ );
740
+ if (skipped.length)
741
+ console.log(
742
+ `\n${skipped.length} abstention case(s) skipped: scored in semantic mode only, the hook gates on cosine`,
743
+ );
744
+ // Named, not counted: a tally cannot be gone and looked at.
745
+ if (unscorable.length) {
746
+ console.log(`\n${unscorable.length} case(s) could not be scored at all:`);
747
+ for (const u of unscorable.slice(0, 10))
748
+ console.log(` ${u.unscorable}\n Q: ${u.q.slice(0, 80)}`);
749
+ }
750
+ if (failures.length) {
751
+ console.log(`\nGATE FAILED:\n ${failures.join('\n ')}`);
752
+ process.exit(1);
753
+ }