@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,130 @@
1
+ // Archive session logs older than N days into <logs-dir>/Archive/. Ported from prune-logs.sh
2
+ // (backlog #9); the port rationale and the five review-found defects fixed in it are in
3
+ // CHANGELOG.md's 0.4.0 entry.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ /**
8
+ * @typedef {{ moved: string[], skipped: string[], collisions: string[] }} PruneResult
9
+ * @typedef {Error & { partial?: PruneResult }} PrunePartialError
10
+ */
11
+
12
+ /**
13
+ * The date encoded in a log filename, as `YYYY-MM-DD`, or null when there is none.
14
+ * The round-trip is the validation: `2026-02-31` matches the pattern but is not a real date.
15
+ * @param {string} basename
16
+ * @returns {string | null}
17
+ */
18
+ export function logDate(basename) {
19
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(basename);
20
+ if (!m) return null;
21
+ const [, y, mo, d] = m;
22
+ // Local, not UTC — toISOString() would shift the day; these filenames are local-dated
23
+ // (CLAUDE.md's Conventions: "toISOString() is UTC where date.today() is local").
24
+ const dt = new Date(Number(y), Number(mo) - 1, Number(d));
25
+ return dt.getFullYear() === Number(y) &&
26
+ dt.getMonth() === Number(mo) - 1 &&
27
+ dt.getDate() === Number(d)
28
+ ? m[0]
29
+ : null;
30
+ }
31
+
32
+ // Year padded to 4 digits — unpadded, the lexical YYYY-MM-DD compare breaks past a three-digit
33
+ // PRUNE_DAYS (CHANGELOG.md 0.4.0).
34
+ /** @type {(dt: Date) => string} */
35
+ const iso = (dt) =>
36
+ `${String(dt.getFullYear()).padStart(4, '0')}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
37
+
38
+ /**
39
+ * `PRUNE_DAYS` as a whole number of days, or NaN when it is not one (empty/unset defaults to 90).
40
+ * Digits only — `Number()` accepts far too much for a human-typed value (CHANGELOG.md 0.4.0).
41
+ * @param {unknown} raw
42
+ * @returns {number}
43
+ */
44
+ export function parseDays(raw) {
45
+ const s = String(raw ?? '').trim();
46
+ if (s === '') return 90;
47
+ return /^\d+$/.test(s) ? Number(s) : NaN;
48
+ }
49
+
50
+ /**
51
+ * The oldest date that is kept, as `YYYY-MM-DD`. Strictly older is archived.
52
+ * Date arithmetic, not `now - days * 86400`, so a DST change cannot move the boundary a day.
53
+ * @param {Date} now
54
+ * @param {number} days
55
+ * @returns {string}
56
+ */
57
+ export function cutoffDate(now, days) {
58
+ // Re-checked here, not only by the caller — every path to a deletion-shaped move goes through
59
+ // this (CHANGELOG.md 0.4.0).
60
+ if (!Number.isInteger(days) || days < 0)
61
+ throw new RangeError(`days must be a non-negative whole number of days, got: ${days}`);
62
+ const c = new Date(now.getFullYear(), now.getMonth(), now.getDate() - days);
63
+ if (Number.isNaN(c.getTime())) throw new RangeError(`days is too large to be a date: ${days}`);
64
+ return iso(c);
65
+ }
66
+
67
+ /**
68
+ * Move every `YYYY-MM-DD-*.md` older than the cutoff into `<dir>/Archive/`.
69
+ * Returns { moved, skipped, collisions }: `skipped` are names with no parseable date,
70
+ * `collisions` are files whose archive destination already exists.
71
+ * @param {string} dir
72
+ * @param {{ days?: number, now?: Date, dryRun?: boolean }} [options]
73
+ * @returns {PruneResult}
74
+ */
75
+ export function pruneLogs(dir, { days = 90, now = new Date(), dryRun = false } = {}) {
76
+ const cutoff = cutoffDate(now, days);
77
+ const archive = path.join(dir, 'Archive');
78
+ /** @type {PruneResult} */
79
+ const result = { moved: [], skipped: [], collisions: [] };
80
+
81
+ // !isDirectory(), not isFile() — isFile() is lstat-based and drops a symlinked log silently
82
+ // (CHANGELOG.md 0.4.0).
83
+ const entries = fs
84
+ .readdirSync(dir, { withFileTypes: true })
85
+ .filter((e) => !e.isDirectory() && e.name.endsWith('.md'))
86
+ .map((e) => e.name)
87
+ .sort();
88
+
89
+ try {
90
+ const archiveStat = fs.lstatSync(archive, { throwIfNoEntry: false });
91
+ if (archiveStat && !archiveStat.isDirectory())
92
+ throw new Error(`${archive} is not a real directory`);
93
+ for (const name of entries) {
94
+ const date = logDate(name);
95
+ if (!date) {
96
+ result.skipped.push(name);
97
+ continue;
98
+ }
99
+ if (date >= cutoff) continue; // lexical compare is chronological for YYYY-MM-DD
100
+ const dest = path.join(archive, name);
101
+ // lstat, not existsSync — existsSync follows a link, so a dangling one at dest read as free
102
+ // space (CHANGELOG.md 0.4.0). A collision leaves both copies alone and is reported.
103
+ if (fs.lstatSync(dest, { throwIfNoEntry: false })) {
104
+ result.collisions.push(name);
105
+ continue;
106
+ }
107
+ if (!dryRun) {
108
+ // Created lazily: a prune that moves nothing leaves no empty Archive/ behind.
109
+ fs.mkdirSync(archive, { recursive: true });
110
+ const src = path.join(dir, name);
111
+ try {
112
+ const stat = fs.lstatSync(src);
113
+ if (stat.isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(src), dest);
114
+ else fs.linkSync(src, dest);
115
+ } catch (e) {
116
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EEXIST') throw e;
117
+ result.collisions.push(name);
118
+ continue;
119
+ }
120
+ fs.unlinkSync(src);
121
+ }
122
+ result.moved.push(name);
123
+ }
124
+ } catch (err) {
125
+ // Partial result rides on the error, so a rename failing part-way still reports what moved.
126
+ /** @type {PrunePartialError} */ (err).partial = result;
127
+ throw err;
128
+ }
129
+ return result;
130
+ }
@@ -0,0 +1,354 @@
1
+ // The `--stats` half of /memory:doctor: what per-prompt recall actually did, from its own log.
2
+ // The CLI entry is scripts/doctor-perf.mjs.
3
+ //
4
+ // Two gates decide whether a prompt gets a brief — cosine 0.55 and BM25 6.0 — and both were tuned
5
+ // on small hand-made sets, one of which cannot ship. The comments beside them say to "read the
6
+ // abstain rate in the log" before moving them; until this existed, nothing could. This is the
7
+ // instrument, not a change to what it measures.
8
+ //
9
+ // Read-only, and the same hard rule as doctor-perf.mjs: no server, no model, no index write. It
10
+ // opens no database itself — the index note set arrives as a value, so this module stays testable
11
+ // on a runtime without `node:sqlite`, exactly as indexStats() takes its counts.
12
+ //
13
+ // It must also read log lines written before the fields it reports existed. Every metric below is
14
+ // therefore counted over the lines that HAVE the key, and reports how many did not, rather than
15
+ // treating a missing `ms` as a fast recall.
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { table } from './doctor-perf.mjs';
20
+ import { MAX_CHARS } from '../../hooks/lib/memory-recall.mjs';
21
+
22
+ /**
23
+ * @typedef {{
24
+ * t?: string, slug?: string, abstained?: boolean, reason?: string, top?: string | null,
25
+ * score?: number, injected?: number, chars?: number, via?: string,
26
+ * ms?: number, k?: number, notes?: string[],
27
+ * }} RecallLine
28
+ */
29
+ /** @typedef {{ decisions: number, injected: number, scores: number[], latencies: number[] }} ArmStats */
30
+
31
+ export const DEFAULT_DAYS = 7;
32
+ const TOP_N = 10;
33
+
34
+ /**
35
+ * The daily log files of one family, oldest first.
36
+ *
37
+ * The window is counted in FILES, not in days elapsed: names are dated and a family only gets a
38
+ * file on a day it ran, so "the last 7 files" is the last 7 days recall was armed. Nothing here
39
+ * reads the clock — a machine that has been off for a month still reports its last week of use.
40
+ *
41
+ * `family` is a parameter because the hook log (scripts/lib/hook-stats.mjs) is the same shape read
42
+ * the same way; a second copy of this and of readLines() below is how the two would drift.
43
+ *
44
+ * @param {string} dir
45
+ * @param {number} [days]
46
+ * @param {string} [family]
47
+ * @returns {string[]}
48
+ */
49
+ export function logFiles(dir, days = DEFAULT_DAYS, family = 'recall') {
50
+ let names;
51
+ try {
52
+ names = fs.readdirSync(dir);
53
+ } catch {
54
+ return [];
55
+ }
56
+ return names
57
+ .filter((f) => new RegExp(`^${family}-\\d{4}-\\d{2}-\\d{2}\\.jsonl$`).test(f))
58
+ .sort()
59
+ .slice(-Math.max(1, days))
60
+ .map((f) => path.join(dir, f));
61
+ }
62
+
63
+ /**
64
+ * Every parseable line from those files. An unparseable line is skipped, not thrown on: the file
65
+ * is append-only from a hook that can be killed mid-write, so a torn last line is expected.
66
+ *
67
+ * @param {readonly string[]} files
68
+ * @returns {RecallLine[]}
69
+ */
70
+ export function readLines(files) {
71
+ /** @type {RecallLine[]} */
72
+ const out = [];
73
+ for (const f of files) {
74
+ let raw;
75
+ try {
76
+ raw = fs.readFileSync(f, 'utf8');
77
+ } catch {
78
+ continue;
79
+ }
80
+ for (const line of raw.split('\n')) {
81
+ if (!line.trim()) continue;
82
+ try {
83
+ const v = JSON.parse(line);
84
+ if (v && typeof v === 'object') out.push(v);
85
+ } catch {
86
+ /* torn or hand-edited line */
87
+ }
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * Nearest-rank percentile over an unsorted list. Empty is null, never 0 — a missing measurement
95
+ * and a measured zero must not print the same.
96
+ *
97
+ * @param {readonly number[]} values
98
+ * @param {number} p
99
+ * @returns {number | null}
100
+ */
101
+ export function percentile(values, p) {
102
+ if (!values.length) return null;
103
+ const s = [...values].sort((a, b) => a - b);
104
+ return s[Math.min(s.length - 1, Math.ceil((p / 100) * s.length) - 1)];
105
+ }
106
+
107
+ // The absence of `via` is the BM25 fallback — a documented contract of the log format, not an
108
+ // oversight, so it is read here rather than repaired.
109
+ //
110
+ // The 'no index' abstain is the exception: the ENTRY writes it before either arm exists — no
111
+ // socket, no BM25 — and it carries no `via`, so it would land in the keyword bucket and make the
112
+ // fallback look fast and useless. On an install whose index moved, every keyword row would be that.
113
+ // Bucketed separately here rather than given a `via` at the hook, which would change the contract.
114
+ /** @param {RecallLine} l @returns {string} */
115
+ const armOf = (l) => (l.reason?.startsWith('no index') ? '(no index)' : (l.via ?? 'keyword'));
116
+
117
+ /**
118
+ * Which notes of a decision actually reached the prompt.
119
+ *
120
+ * `notes` is the candidate list in render order and `injected` is how many of them survived the
121
+ * character budget, so the injected set is a prefix. Lines written before those fields existed
122
+ * carry only `top`, which is the first of them — one note, correctly, rather than none.
123
+ *
124
+ * @param {RecallLine} l
125
+ * @returns {string[]}
126
+ */
127
+ export function injectedNotes(l) {
128
+ if (l.abstained) return [];
129
+ if (Array.isArray(l.notes)) return l.notes.slice(0, l.injected ?? l.notes.length);
130
+ return typeof l.top === 'string' ? [l.top] : [];
131
+ }
132
+
133
+ /**
134
+ * The log files are MACHINE-WIDE — one `logs/` directory, every project appending to the same daily
135
+ * file — and every line carries its `slug`. The never-injected list can only be resolved for one
136
+ * project (its index is per slug), so mixing projects would report one project's notes against
137
+ * every project's retrievals. Measured on this machine 2026-08-20: a 7-file window held 5 slugs at
138
+ * 791/186/20/8/1 decisions, so the headline rate was mostly another project's. Passing
139
+ * `slug: null` deliberately keeps every line; passing a slug drops the rest, and the report says
140
+ * how many it dropped rather than quietly narrowing.
141
+ *
142
+ * @param {readonly RecallLine[]} lines
143
+ * @param {readonly string[] | null} [indexNotes]
144
+ * @param {string | null} [slug]
145
+ */
146
+ export function summarize(lines, indexNotes = null, slug = null) {
147
+ const seen = lines.length;
148
+ lines = slug ? lines.filter((l) => l.slug === slug) : lines;
149
+ /** @type {Map<string, ArmStats>} */
150
+ const arms = new Map();
151
+ /** @type {Map<string, number>} */
152
+ const reasons = new Map();
153
+ /** @type {Map<string, number>} */
154
+ const injections = new Map();
155
+ let injected = 0;
156
+ let untimed = 0;
157
+ let unlisted = 0;
158
+ let trimmed = 0;
159
+
160
+ for (const l of lines) {
161
+ const arm = armOf(l);
162
+ const a = arms.get(arm) ?? { decisions: 0, injected: 0, scores: [], latencies: [] };
163
+ a.decisions++;
164
+ if (typeof l.score === 'number') a.scores.push(l.score);
165
+ if (typeof l.ms === 'number') a.latencies.push(l.ms);
166
+ else untimed++;
167
+ if (!l.abstained) {
168
+ a.injected++;
169
+ injected++;
170
+ // A line older than `notes` names only its top hit, so up to three notes it really did inject
171
+ // are invisible. That does not merely blur the most-injected table — it puts those notes in
172
+ // the NEVER-injected list, which is the one output the whole feature exists to produce.
173
+ if (!Array.isArray(l.notes)) unlisted++;
174
+ if (typeof l.k === 'number' && typeof l.injected === 'number' && l.k > l.injected) trimmed++;
175
+ } else {
176
+ const r = l.reason ?? '(no reason)';
177
+ reasons.set(r, (reasons.get(r) ?? 0) + 1);
178
+ }
179
+ arms.set(arm, a);
180
+ for (const n of injectedNotes(l)) injections.set(n, (injections.get(n) ?? 0) + 1);
181
+ }
182
+
183
+ // `indexNotes?.length`, not `indexNotes`: an index that opens but holds no rows comes back as an
184
+ // empty array, and `[]` would report "all 0 indexed notes have surfaced" — the opposite of true.
185
+ const never = indexNotes?.length ? indexNotes.filter((n) => !injections.has(n)) : null;
186
+ return {
187
+ decisions: lines.length,
188
+ injected,
189
+ abstained: lines.length - injected,
190
+ untimed,
191
+ unlisted,
192
+ trimmed,
193
+ first: lines.find((l) => l.t)?.t ?? null,
194
+ last: [...lines].reverse().find((l) => l.t)?.t ?? null,
195
+ arms: [...arms.entries()].sort((a, b) => b[1].decisions - a[1].decisions),
196
+ reasons: [...reasons.entries()].sort((a, b) => b[1] - a[1]),
197
+ top: [...injections.entries()].sort((a, b) => b[1] - a[1]),
198
+ never,
199
+ indexed: indexNotes?.length ? indexNotes.length : null,
200
+ emptyIndex: Array.isArray(indexNotes) && indexNotes.length === 0,
201
+ slug,
202
+ otherProjects: seen - lines.length,
203
+ };
204
+ }
205
+
206
+ /** @param {number | null} v @param {number} [digits] @returns {string} */
207
+ const num = (v, digits = 0) => (v === null ? '-' : v.toFixed(digits));
208
+
209
+ /** @param {number} n @param {number} of @returns {string} */
210
+ const pct = (n, of) => (of ? `${n} (${Math.round((n / of) * 100)}%)` : '0');
211
+
212
+ /**
213
+ * The recall section body.
214
+ *
215
+ * @param {ReturnType<typeof summarize>} s
216
+ * @returns {string}
217
+ */
218
+ export function render(s) {
219
+ if (!s.decisions)
220
+ return s.otherProjects
221
+ ? `not measured: none of the ${s.otherProjects} logged decisions in this window belong to ` +
222
+ `${s.slug}. The log is machine-wide; this project has not run with recall armed.`
223
+ : 'not measured: no recall decisions logged in this window.';
224
+
225
+ const window = s.first && s.last ? ` (${s.first.slice(0, 10)} … ${s.last.slice(0, 10)})` : '';
226
+ const out = [
227
+ s.slug
228
+ ? `${s.decisions} decisions for ${s.slug}${window}` +
229
+ (s.otherProjects
230
+ ? ` — ${s.otherProjects} more in this window belong to other projects`
231
+ : '')
232
+ : `${s.decisions} decisions, every project on this machine${window}`,
233
+ `injected ${pct(s.injected, s.decisions)} abstained ${pct(s.abstained, s.decisions)}`,
234
+ '',
235
+ // Scores are NOT comparable across the two rows: the server arm is cosine (gate 0.55) and the
236
+ // keyword arm is absolute BM25 (gate 6.0). Read each row against its own gate.
237
+ table(
238
+ ['arm', 'decisions', 'injected', 'score p50', 'score p90', 'ms p50', 'ms p95'],
239
+ s.arms.map(([name, a]) => [
240
+ name,
241
+ a.decisions,
242
+ pct(a.injected, a.decisions),
243
+ num(percentile(a.scores, 50), 2),
244
+ num(percentile(a.scores, 90), 2),
245
+ num(percentile(a.latencies, 50), 1),
246
+ num(percentile(a.latencies, 95), 1),
247
+ ]),
248
+ ),
249
+ 'server = the fused vector arm, keyword = the BM25 fallback, (no index) = neither ran. Scores',
250
+ 'are on different scales: cosine against a 0.55 gate, BM25 against 6.0 — never compare rows.',
251
+ 'ms is the WHOLE armed path from process start, not the arm alone, so a keyword row includes',
252
+ 'node startup and any server round trip that failed or timed out before it.',
253
+ ];
254
+
255
+ if (s.untimed)
256
+ out.push(
257
+ '',
258
+ `${s.untimed} of ${s.decisions} decisions predate latency logging — not counted in ms.`,
259
+ );
260
+ if (s.unlisted)
261
+ out.push(
262
+ '',
263
+ `${s.unlisted} of ${s.injected} injections predate candidate logging — only their top note is`,
264
+ 'counted, so the never-injected list below is an UPPER BOUND until they age out of the window.',
265
+ );
266
+ // NOT "the budget", which was the first wording and was wrong for half the records: the keyword
267
+ // arm renders with a trailing weak-hit floor (MIN_SCORE / 2) that renderLines checks BEFORE the
268
+ // character budget, so its candidates can be dropped for being weak rather than for being long.
269
+ // Only the semantic arm renders floorless, where k > injected does mean the budget.
270
+ if (s.trimmed)
271
+ out.push(
272
+ '',
273
+ `${s.trimmed} injection(s) rendered fewer notes than the arm offered — the ${MAX_CHARS}-char ` +
274
+ 'budget, or (keyword arm only) the trailing weak-hit floor.',
275
+ );
276
+
277
+ if (s.reasons.length)
278
+ out.push(
279
+ '',
280
+ 'abstained by reason',
281
+ // Count first: `table` pads every column but the last, and a reason is long and variable.
282
+ table(
283
+ ['n', 'reason'],
284
+ s.reasons.map(([r, n]) => [n, r]),
285
+ ),
286
+ );
287
+
288
+ if (s.top.length)
289
+ out.push(
290
+ '',
291
+ `most injected notes (of ${s.top.length} ever injected)`,
292
+ table(
293
+ ['n', 'note'],
294
+ s.top.slice(0, TOP_N).map(([n, c]) => [c, n]),
295
+ ),
296
+ );
297
+
298
+ if (s.never === null) {
299
+ out.push(
300
+ '',
301
+ s.emptyIndex
302
+ ? 'never-injected notes: not measured — this project has an index and it holds no notes.'
303
+ : 'never-injected notes: not measured — no readable index for this project.',
304
+ );
305
+ } else if (!s.never.length) {
306
+ out.push('', `never-injected notes: none — all ${s.indexed} indexed notes have surfaced.`);
307
+ } else {
308
+ out.push(
309
+ '',
310
+ `never injected: ${s.never.length} of ${s.indexed} indexed notes`,
311
+ s.never
312
+ .slice(0, TOP_N)
313
+ .map((n) => ` ${n}`)
314
+ .join('\n') + (s.never.length > TOP_N ? `\n … ${s.never.length - TOP_N} more` : ''),
315
+ 'A note nobody retrieves is dead weight — or is phrased in words no prompt uses.',
316
+ );
317
+ }
318
+
319
+ return out.join('\n');
320
+ }
321
+
322
+ /**
323
+ * The whole `--stats` report, as one string.
324
+ *
325
+ * @param {{
326
+ * logDir: string,
327
+ * days?: number,
328
+ * indexNotes?: readonly string[] | null,
329
+ * slug?: string | null,
330
+ * }} options
331
+ * @returns {string}
332
+ */
333
+ export function report({ logDir, days = DEFAULT_DAYS, indexNotes = null, slug = null }) {
334
+ const files = logFiles(logDir, days);
335
+ const summary = summarize(readLines(files), indexNotes, slug);
336
+ const body = render(summary);
337
+ const head = files.length
338
+ ? `${files.length} log file(s), most recent first: ${files
339
+ .slice(-3)
340
+ .reverse()
341
+ .map((f) => path.basename(f))
342
+ .join(', ')}`
343
+ : `no recall logs in ${logDir} — recall is off, or has never run armed.`;
344
+ // This is the only doctor section that prints VAULT CONTENT — note names, from a private vault —
345
+ // and the command body tells the reader to show doctor output verbatim, next to a header calling
346
+ // a paste of the whole thing what an issue wants. The warning ships with the data rather than
347
+ // only in the docs, because the two get separated the moment someone copies the report.
348
+ const named = summary.top.length || summary.never?.length;
349
+ const caution = named
350
+ ? '\n\nThe note names above come from your vault. Everything else in /memory:doctor is safe to' +
351
+ '\npaste into a public issue; this section is not.'
352
+ : '';
353
+ return `\nrecall analytics\n${`${head}\n\n${body}${caution}`.replace(/^(?=.)/gm, ' ')}\n`;
354
+ }
@@ -0,0 +1,70 @@
1
+ // Claude Code keeps every installed version of a plugin, each with its own node_modules — it does
2
+ // NOT replace the cache wholesale on update. Measured 2026-08-18: six versions of this plugin,
3
+ // 381 MB each, link count 1, 2.2 GB total. Slimming the install divides that constant; it does not
4
+ // stop it multiplying. The runtime is identical across versions and is exactly what the repo's own
5
+ // rule says belongs in $CLAUDE_MEMORY_HOME, so it moves there once and every version dir gets a
6
+ // symlink. Node resolves through symlinks by default, so nothing else changes.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ // This module deletes directories. It only ever does so inside a plugin cache, and this is the
11
+ // only thing standing between a wrong CWD and a developer's checkout.
12
+ const CACHE_MARKER = path.join('plugins', 'cache');
13
+
14
+ /**
15
+ * @param {string} dir
16
+ * @returns {boolean}
17
+ */
18
+ export function isPluginInstall(dir) {
19
+ return dir.split(path.sep).join(path.sep).includes(CACHE_MARKER);
20
+ }
21
+
22
+ /**
23
+ * Refuses anything that is not a node_modules directly inside a plugin cache dir.
24
+ *
25
+ * @param {string} p
26
+ * @returns {boolean}
27
+ */
28
+ export function isRemovable(p) {
29
+ return path.basename(p) === 'node_modules' && isPluginInstall(path.dirname(p));
30
+ }
31
+
32
+ /** @type {(p: string) => import('node:fs').Stats | null} */
33
+ const stat = (p) => {
34
+ try {
35
+ return fs.lstatSync(p);
36
+ } catch {
37
+ return null;
38
+ }
39
+ };
40
+
41
+ /** @type {(p: string) => boolean} */
42
+ export const isRealDir = (p) => stat(p)?.isDirectory() === true;
43
+ /** @type {(p: string) => boolean} */
44
+ export const isLink = (p) => stat(p)?.isSymbolicLink() === true;
45
+ /** @type {(p: string) => boolean} */
46
+ export const hasInstall = (p) =>
47
+ isRealDir(p) && fs.existsSync(path.join(p, 'onnxruntime-node', 'package.json'));
48
+
49
+ /**
50
+ * Other installed versions of the same plugin that still carry their own copy.
51
+ * versionDir is this version's directory; its siblings are the other versions.
52
+ *
53
+ * @param {string} versionDir
54
+ * @returns {string[]}
55
+ */
56
+ export function siblingCopies(versionDir) {
57
+ const parent = path.dirname(versionDir);
58
+ if (!isPluginInstall(parent)) return [];
59
+ /** @type {import('node:fs').Dirent[]} */
60
+ let entries = [];
61
+ try {
62
+ entries = fs.readdirSync(parent, { withFileTypes: true });
63
+ } catch {
64
+ return [];
65
+ }
66
+ return entries
67
+ .filter((e) => e.isDirectory() && path.join(parent, e.name) !== versionDir)
68
+ .map((e) => path.join(parent, e.name, 'node_modules'))
69
+ .filter((p) => isRealDir(p) && !isLink(p));
70
+ }