@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,165 @@
1
+ // L3 Mistakes and open-fork surfacing — the logic half. The CLI entry is hooks/insights-surface.mjs.
2
+ //
3
+ // Nothing here reads argv, stdin or prints: it takes a cwd and returns the text to show, so it is
4
+ // importable and testable without a subprocess. Tests: hooks/lib/insights-surface.test.mjs
5
+ //
6
+ // Ported from shell on 2026-08-17, 124 ms → 52 ms: it forked `grep` + `sed` once per note, up to 45
7
+ // subprocesses to print 15 lines. Pinning the vault to local disk moved it 174.0 → 165.2 ms, which
8
+ // is what identified it as fork-bound — docs/decisions/2026-08-17-shell-vs-node-hooks.md.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { vault, projectKey, legacyKey } from './paths.mjs';
12
+ import { defuse } from './memory-recall.mjs';
13
+
14
+ // ponytail: titles only, capped, silent when there is nothing.
15
+ export const LIMIT = 15;
16
+
17
+ /**
18
+ * The displayed title for one note: frontmatter `title:` if it carries a value, else the filename
19
+ * with its date prefix stripped and dashes spaced out.
20
+ *
21
+ * The empty-value case is why this is a function with a test. `grep -m1 '^title:' | sed` yields an
22
+ * empty string for `title:` with nothing after it, and the shell version then fell through to the
23
+ * filename — a naive port prints a blank bullet instead.
24
+ *
25
+ * @param {string} filename
26
+ * @param {string} raw
27
+ * @returns {string}
28
+ */
29
+ export function noteTitle(filename, raw) {
30
+ const m = raw.match(/^title: *(.*)$/m);
31
+ const t = m ? m[1].trim() : '';
32
+ if (t) return t;
33
+ return filename
34
+ .replace(/\.md$/, '')
35
+ .replace(/^[0-9-]*/, '')
36
+ .replace(/-/g, ' ');
37
+ }
38
+
39
+ /**
40
+ * Newest first. Filenames are date-prefixed, so a plain reverse sort is chronological.
41
+ *
42
+ * @param {string[]} names
43
+ * @returns {string[]}
44
+ */
45
+ export function orderNewestFirst(names) {
46
+ return names
47
+ .filter((f) => f.endsWith('.md'))
48
+ .sort()
49
+ .reverse();
50
+ }
51
+
52
+ /**
53
+ * @param {string} slug
54
+ * @param {string[]} files
55
+ * @param {(file: string) => string} read
56
+ * @returns {string}
57
+ */
58
+ export function render(slug, files, read) {
59
+ if (!files.length) return '';
60
+ const out = [
61
+ `Past mistakes for this project (L3 memory — avoid repeating; full lessons in Insights/${slug}/Mistakes/ or via /memory:health):`,
62
+ ];
63
+ for (const f of files.slice(0, LIMIT)) out.push(`- ${defuse(noteTitle(f, read(f)))}`);
64
+ if (files.length > LIMIT) out.push(`(+${files.length - LIMIT} older)`);
65
+ return out.join('\n');
66
+ }
67
+
68
+ /**
69
+ * L1 notes whose frontmatter says `status: open`, newest first.
70
+ *
71
+ * @param {string} dir
72
+ * @returns {{ name: string, title: string }[]}
73
+ */
74
+ export function openForks(dir) {
75
+ /** @type {{ name: string, title: string, mtime: number }[]} */
76
+ const out = [];
77
+ let names;
78
+ try {
79
+ names = fs.readdirSync(dir);
80
+ } catch {
81
+ return [];
82
+ }
83
+ for (const f of names) {
84
+ if (!f.endsWith('.md') || f === 'MEMORY.md') continue;
85
+ try {
86
+ const file = path.join(dir, f);
87
+ const raw = fs.readFileSync(file, 'utf8');
88
+ if (!raw.startsWith('---\n')) continue;
89
+ const end = raw.indexOf('\n---', 3);
90
+ const fm = raw.slice(4, end === -1 ? undefined : end + 1);
91
+ if (!/^status:[ \t]*["']?open["']?[ \t]*$/m.test(fm)) continue;
92
+ // ponytail: mtime orders by last edit, and a fresh clone resets it; add a created: field if that bites
93
+ out.push({ name: f.slice(0, -3), title: noteTitle(f, fm), mtime: fs.statSync(file).mtimeMs });
94
+ } catch {
95
+ /* unreadable note: skip it */
96
+ }
97
+ }
98
+ return out.sort((a, b) => b.mtime - a.mtime).map(({ name, title }) => ({ name, title }));
99
+ }
100
+
101
+ /**
102
+ * @param {string} slug
103
+ * @param {{ name: string, title: string }[]} forks
104
+ * @returns {string}
105
+ */
106
+ export function renderForks(slug, forks) {
107
+ if (!forks.length) return '';
108
+ const out = [
109
+ 'Open forks for this project (ideas parked mid-session; close with status: closed):',
110
+ ];
111
+ for (const f of forks.slice(0, LIMIT)) out.push(`- ${defuse(f.title)} ([[${defuse(f.name)}]])`);
112
+ if (forks.length > LIMIT) {
113
+ out.push(`(+${forks.length - LIMIT} more in Memory/${slug}/ with status: open)`);
114
+ }
115
+ return out.join('\n');
116
+ }
117
+
118
+ /** @param {string} p */
119
+ function isDir(p) {
120
+ try {
121
+ return fs.statSync(p).isDirectory();
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * The text to surface for `cwd`, or '' when there is nothing to say.
129
+ *
130
+ * @param {string} cwd
131
+ * @returns {string}
132
+ */
133
+ export function surface(cwd) {
134
+ let slug;
135
+ try {
136
+ slug = projectKey(cwd);
137
+ } catch {
138
+ slug = legacyKey(cwd);
139
+ }
140
+ // Tolerate a not-yet-migrated vault: vault-memory-sync.sh performs the rename, but SessionStart
141
+ // hook order isn't guaranteed, so fall back for this one session.
142
+ const resolve = (/** @type {string[]} */ ...sub) => {
143
+ const dir = path.join(vault(), sub[0], slug, ...sub.slice(1));
144
+ if (isDir(dir)) return { s: slug, dir };
145
+ const s = legacyKey(cwd);
146
+ return { s, dir: path.join(vault(), sub[0], s, ...sub.slice(1)) };
147
+ };
148
+ const m = resolve('Insights', 'Mistakes');
149
+ /** @type {string[]} */
150
+ let files = [];
151
+ try {
152
+ files = orderNewestFirst(fs.readdirSync(m.dir));
153
+ } catch {
154
+ /* no Mistakes folder */
155
+ }
156
+ const mistakes = render(m.s, files, (f) => {
157
+ try {
158
+ return fs.readFileSync(path.join(m.dir, f), 'utf8');
159
+ } catch {
160
+ return '';
161
+ }
162
+ });
163
+ const mem = resolve('Memory');
164
+ return [mistakes, renderForks(mem.s, openForks(mem.dir))].filter(Boolean).join('\n\n');
165
+ }
@@ -0,0 +1,499 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart: name the L1 notes that are reachable only from the MOC — and, since #75, everything
3
+ // else that is true of MEMORY.md itself: its size against the cap Claude Code loads it under, for
4
+ // this project (the lint) and for every project in the vault (capReport, read by /memory:doctor).
5
+ //
6
+ // Convention alone didn't hold it (three consecutive audit recurrences before this lint existed):
7
+ // docs/decisions/2026-08-08-memory-link-lint.md.
8
+ //
9
+ // MOC-only is not corruption — the note is findable. It is invisible to the note graph, so nothing
10
+ // leads you to it while reading a sibling. Reporting it at session start is what makes it fixable.
11
+ // ponytail: names only, no auto-fix — deciding WHICH sibling should link is the judgement call.
12
+ //
13
+ // Ported from memory-link-lint.sh on 2026-08-17: shell was O(N×(N+M)) (`grep -rlF` once per note
14
+ // over Memory+Insights), this is O(N+M) (index once). 2626 ms -> 61 ms at 120 notes; the full
15
+ // sweep and the production timeout it fixed: docs/decisions/2026-08-17-shell-vs-node-hooks.md.
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createHash } from 'node:crypto';
19
+ import { vault, projectKey, legacyKey, memoryHome } from './paths.mjs';
20
+
21
+ // A bash `[[ $var =~ re ]]` test inside a fenced block parses as a wikilink. Reported as a dangling
22
+ // link on 2026-08-22 from a note about shell arithmetic. Fences are stripped before link scanning,
23
+ // and inline code with them: a literal `[[wikilink]]` in REFLECTIONS.md false-positives otherwise.
24
+ // ponytail: backtick fences only — 0 of 442 notes use `~~~`; add it when one does.
25
+ export const FENCE = /^ {0,3}(`{3,})[^\n]*\n[\s\S]*?^ {0,3}\1[^\n]*$/gm;
26
+ export const INLINE_CODE = /`[^`\n]*`/g;
27
+ /** @param {string} text @returns {string} */
28
+ export function stripCodeBlocks(text) {
29
+ return text.replace(FENCE, '').replace(INLINE_CODE, '');
30
+ }
31
+
32
+ /**
33
+ * Every wikilink target in one note's text — the one wikilink-only parser (#99), code-aware.
34
+ *
35
+ * A target ends at the first `]`, `|` or `#`, so `[[foo bar]]` links to `foo bar`, not to `foo`.
36
+ *
37
+ * @param {string} text
38
+ * @returns {Set<string>}
39
+ */
40
+ export function linkTargets(text) {
41
+ /** @type {Set<string>} */
42
+ const out = new Set();
43
+ for (const m of stripCodeBlocks(text).matchAll(/\[\[([^\]|#]*)/g)) {
44
+ const t = m[1].trim();
45
+ if (t) out.add(t);
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /**
51
+ * Every note a text links to, in EITHER form — `[[wikilink]]` and `[Title](note.md)`.
52
+ *
53
+ * The one parser for "which note does this link point at". It exists because there were two, and
54
+ * they drifted on this exact file format: `MEMORY.md` is written with markdown links, so a
55
+ * wikilink-only parser silently matched nothing — which disabled `findDrift` here (`readNote` was
56
+ * called 0 times against a real MOC) and made `/memory:health` report every L1 note as missing from
57
+ * the MOC. Both were found on 2026-08-22, in two files, one file format, so this is the only place
58
+ * the regex lives — `findDrift` below and `/memory:health`'s MOC check both call it.
59
+ *
60
+ * NOT a replacement for `linkTargets()` above: that one is deliberately wikilink-only, because the
61
+ * note-graph checks ask whether a SIBLING can reach a note, and a markdown link from the MOC is
62
+ * exactly what does not make it reachable.
63
+ *
64
+ * @param {string} text
65
+ * @returns {string[]}
66
+ */
67
+ export function noteTargets(text) {
68
+ /** @type {string[]} */
69
+ const out = [];
70
+ // One pass, so the result is in DOCUMENT order — two passes put every wikilink before every
71
+ // markdown link, and findDrift takes [0], so a bullet mixing both forms picked the wrong one.
72
+ for (const [, wiki, md] of stripCodeBlocks(text).matchAll(
73
+ /\[\[([^\]|#]*)|\]\(([^)]+?)\.md(?:#[^)]*)?\)/g,
74
+ )) {
75
+ const t = wiki !== undefined ? wiki.trim() : md.replace(/^\.\//, '').trim();
76
+ if (t) out.push(t);
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /**
82
+ * `.md` files under `dir`, recursively. Missing directories are simply empty.
83
+ *
84
+ * @param {string} dir
85
+ * @returns {string[]}
86
+ */
87
+ export function mdFiles(dir) {
88
+ /** @type {string[]} */
89
+ const out = [];
90
+ const walk = (/** @type {string} */ d) => {
91
+ let entries;
92
+ try {
93
+ entries = fs.readdirSync(d, { withFileTypes: true });
94
+ } catch {
95
+ return;
96
+ }
97
+ for (const e of entries) {
98
+ const p = path.join(d, e.name);
99
+ if (e.isDirectory()) walk(p);
100
+ else if (e.name.endsWith('.md')) out.push(p);
101
+ }
102
+ };
103
+ walk(dir);
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * L1 notes with no inbound wikilink from anywhere except the MOC and themselves.
109
+ * `corpus` is [absolutePath, text or its linkTargets()] pairs across Memory/ and Insights/.
110
+ *
111
+ * @param {string} memDir
112
+ * @param {readonly string[]} noteNames
113
+ * @param {readonly (readonly [string, string | ReadonlySet<string>])[]} corpus
114
+ * @returns {string[]}
115
+ */
116
+ export function findOrphans(memDir, noteNames, corpus) {
117
+ const moc = path.join(memDir, 'MEMORY.md');
118
+ /** @type {Map<string, Set<string>>} */
119
+ const inbound = new Map(); // target -> Set(linking file)
120
+ for (const [file, body] of corpus) {
121
+ if (file === moc) continue; // the MOC does not count as a sibling
122
+ for (const t of typeof body === 'string' ? linkTargets(body) : body) {
123
+ if (!inbound.has(t)) inbound.set(t, new Set());
124
+ /** @type {Set<string>} */ (inbound.get(t)).add(file);
125
+ }
126
+ }
127
+ return noteNames.filter((n) => {
128
+ if (n === 'MEMORY') return false;
129
+ const from = inbound.get(n);
130
+ if (!from) return true;
131
+ // a note linking to itself is not inbound
132
+ for (const f of from) if (f !== path.join(memDir, `${n}.md`)) return false;
133
+ return true;
134
+ });
135
+ }
136
+
137
+ /**
138
+ * Bolded figures in a MOC hook that the note it points at does not contain.
139
+ *
140
+ * MOC hooks restate figures, then the note body moves and the hook does not. /memory:health caught
141
+ * this in four consecutive audits. ponytail: bolded numbers only — unbolded prose numbers are too
142
+ * noisy to gate on. Commas are stripped on both sides so "1,172" matches "1172".
143
+ *
144
+ * @param {string} mocText
145
+ * @param {(target: string) => string | null} readNote
146
+ * @returns {{ target: string, n: string }[]}
147
+ */
148
+ export function findDrift(mocText, readNote) {
149
+ /** @type {{ target: string, n: string }[]} */
150
+ const drift = [];
151
+ for (const line of mocText.split('\n')) {
152
+ if (!line.startsWith('- [')) continue;
153
+ const target = noteTargets(line)[0];
154
+ if (target === undefined) continue;
155
+ const body = readNote(target);
156
+ if (body === null) continue;
157
+ /** @type {Set<string>} */
158
+ const nums = new Set();
159
+ for (const b of line.matchAll(/\*\*([^*]*)\*\*/g)) {
160
+ for (const d of b[1].replace(/,/g, '').matchAll(/[0-9]{2,}/g)) nums.add(d[0]);
161
+ }
162
+ if (!nums.size) continue;
163
+ const flat = body.replace(/,/g, '');
164
+ // `sort -u` orders lexically, and the shell emitted findings in that order.
165
+ for (const n of [...nums].sort()) if (!flat.includes(n)) drift.push({ target, n });
166
+ }
167
+ return drift;
168
+ }
169
+
170
+ /**
171
+ * Claude Code loads the first 200 lines or 25 KB of `MEMORY.md`, whichever comes first, and drops
172
+ * the rest. Since 2026-03 its auto memory reads `~/.claude/projects/<project>/memory/MEMORY.md` —
173
+ * the path this plugin symlinks into the vault — so our L1 index IS that file, under its cap
174
+ * (#75, docs/decisions/2026-08-22-auto-memory.md). Nothing upstream reports the truncation for a
175
+ * file Claude Code did not write, so this is the only place it is ever said out loud.
176
+ */
177
+ export const AUTO_MEMORY_CAP = { bytes: 25 * 1024, lines: 200 };
178
+
179
+ // Report from here up. 80% is a heads-up while the fix is still a trim; the alternative is finding
180
+ // out by losing notes.
181
+ const NEAR = 0.8;
182
+
183
+ /**
184
+ * One percentage, floored, for both readers. They report DIFFERENT things — the SessionStart lint
185
+ * speaks only from 80% up, `/memory:doctor` reports every state — but the same file must not carry
186
+ * two numbers, and rounding them apart made one say 86% and the other 87%. Floor and not ceil
187
+ * because a file at 99.6% must not read as 100%; which side of the cap it is on is said in words,
188
+ * never left to the number.
189
+ *
190
+ * @param {number} ratio
191
+ * @returns {string}
192
+ */
193
+ const pct = (ratio) => `${Math.floor(ratio * 100)}%`;
194
+
195
+ /**
196
+ * What WE count: bytes, and lines ignoring a trailing newline. The 200/25 KB cap is documented
197
+ * upstream; how it counts a trailing newline is not, so this errs one line low rather than
198
+ * reporting a file as fitting when it does not.
199
+ *
200
+ * @param {string} text
201
+ * @returns {{ bytes: number, lines: number }}
202
+ */
203
+ export function mocSize(text) {
204
+ const bytes = Buffer.byteLength(text);
205
+ return { bytes, lines: bytes === 0 ? 0 : text.replace(/\n$/, '').split('\n').length };
206
+ }
207
+
208
+ /**
209
+ * The size finding for one MOC, or '' when it is comfortably under the cap.
210
+ *
211
+ * @param {string} text
212
+ * @returns {string}
213
+ */
214
+ export function findOversize(text) {
215
+ const { bytes, lines } = mocSize(text);
216
+ const ratio = Math.max(bytes / AUTO_MEMORY_CAP.bytes, lines / AUTO_MEMORY_CAP.lines);
217
+ if (ratio < NEAR) return '';
218
+ const size = `${bytes.toLocaleString('en-US')} bytes / ${lines} lines`;
219
+ const cap = `${AUTO_MEMORY_CAP.bytes.toLocaleString('en-US')}-byte / ${AUTO_MEMORY_CAP.lines} lines cap`;
220
+ if (ratio <= 1)
221
+ return [
222
+ `MEMORY.md is at ${pct(ratio)} of the ${cap} Claude Code loads it under`,
223
+ `(${size}). Past it the rest is dropped with nothing reported. Move detail into the notes.`,
224
+ ].join('\n');
225
+ return [
226
+ `MEMORY.md is ${size}, past the ${cap} Claude Code loads it under: everything after`,
227
+ 'the cap is DROPPED and no other check anywhere reports it. Trim the MOC — one line per note,',
228
+ 'the content belongs in the note.',
229
+ ].join('\n');
230
+ }
231
+
232
+ /**
233
+ * The lint report for `cwd`, or '' when there is nothing to say.
234
+ *
235
+ * Returns text instead of printing it, so the whole check is testable without a subprocess.
236
+ * One pass over the corpus — the shell version read it once per note, which is the O(N x (N+M))
237
+ * that took 10.9 s on a 49-note project and was being killed by the 10 s hook timeout.
238
+ *
239
+ * @param {string} cwd
240
+ * @returns {string}
241
+ */
242
+ export function lint(cwd) {
243
+ let slug;
244
+ try {
245
+ slug = projectKey(cwd);
246
+ } catch {
247
+ slug = legacyKey(cwd);
248
+ }
249
+ const isDir = (/** @type {string} */ p) => {
250
+ try {
251
+ return fs.statSync(p).isDirectory();
252
+ } catch {
253
+ return false;
254
+ }
255
+ };
256
+ let mem = path.join(vault(), 'Memory', slug);
257
+ if (!isDir(mem)) {
258
+ slug = legacyKey(cwd);
259
+ mem = path.join(vault(), 'Memory', slug);
260
+ }
261
+ if (!isDir(mem)) return '';
262
+ const id = createHash('sha1').update(mem).digest('hex').slice(0, 12);
263
+ const cache = path.join(memoryHome(), 'cache', `link-targets-${id}.json`);
264
+ return reportFor(mem, path.join(vault(), 'Insights', slug), cache);
265
+ }
266
+
267
+ /**
268
+ * [path, text] for every readable note under `mem` and `ins` — the corpus `findOrphans` takes.
269
+ *
270
+ * @param {string} mem
271
+ * @param {string} ins
272
+ * @returns {[string, string][]}
273
+ */
274
+ export function readCorpus(mem, ins) {
275
+ /** @type {[string, string][]} */
276
+ const corpus = [];
277
+ for (const f of [...mdFiles(mem), ...mdFiles(ins)]) {
278
+ try {
279
+ corpus.push([f, fs.readFileSync(f, 'utf8')]);
280
+ } catch {
281
+ /* unreadable - skip */
282
+ }
283
+ }
284
+ return corpus;
285
+ }
286
+
287
+ /**
288
+ * [path, linkTargets()] for every readable note under `mem` and `ins`. With `cacheFile`, a note
289
+ * whose `mtimeMs:size:ino` stamp is unchanged is answered from the cache and never opened.
290
+ * Opening every note ran this hook into its timeout: docs/decisions/2026-10-13-link-lint-cache.md.
291
+ *
292
+ * @param {string} mem
293
+ * @param {string} ins
294
+ * @param {string} [cacheFile]
295
+ * @returns {[string, Set<string>][]}
296
+ */
297
+ export function readLinks(mem, ins, cacheFile) {
298
+ /** @type {Record<string, { stamp: string, targets: string[] }>} */
299
+ let cache = {};
300
+ if (cacheFile)
301
+ try {
302
+ cache = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
303
+ } catch {
304
+ /* first run or unreadable: rebuild */
305
+ }
306
+ /** @type {typeof cache} */
307
+ const next = {};
308
+ /** @type {[string, Set<string>][]} */
309
+ const out = [];
310
+ for (const f of [...mdFiles(mem), ...mdFiles(ins)]) {
311
+ try {
312
+ const st = fs.statSync(f);
313
+ const stamp = `${st.mtimeMs}:${st.size}:${st.ino}`;
314
+ const hit = cache[f]?.stamp === stamp ? cache[f].targets : null;
315
+ const targets = hit ?? [...linkTargets(fs.readFileSync(f, 'utf8'))];
316
+ next[f] = { stamp, targets };
317
+ out.push([f, new Set(targets)]);
318
+ } catch {
319
+ /* unreadable - skip */
320
+ }
321
+ }
322
+ const json = JSON.stringify(next);
323
+ if (cacheFile && json !== JSON.stringify(cache))
324
+ try {
325
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
326
+ const tmp = `${cacheFile}.${process.pid}.tmp`;
327
+ fs.writeFileSync(tmp, json);
328
+ fs.renameSync(tmp, cacheFile);
329
+ } catch {
330
+ /* best effort: the next run reads the notes again */
331
+ }
332
+ return out;
333
+ }
334
+
335
+ /**
336
+ * The report for one project's `Memory/` and `Insights/` directories, or '' when there is nothing
337
+ * to say. Split out of `lint()` so the findings are testable against a directory, without a vault
338
+ * and without the resolution that picks one.
339
+ *
340
+ * @param {string} mem
341
+ * @param {string} ins
342
+ * @param {string} [cacheFile] see readLinks()
343
+ * @returns {string}
344
+ */
345
+ export function reportFor(mem, ins, cacheFile) {
346
+ const corpus = readLinks(mem, ins, cacheFile);
347
+
348
+ let names;
349
+ try {
350
+ names = fs
351
+ .readdirSync(mem)
352
+ .filter((f) => f.endsWith('.md'))
353
+ .sort()
354
+ .map((f) => f.slice(0, -3));
355
+ } catch {
356
+ return '';
357
+ }
358
+
359
+ /** @type {string[]} */
360
+ const out = [];
361
+ const orphans = findOrphans(mem, names, corpus);
362
+ if (orphans.length) {
363
+ out.push(
364
+ 'MOC-only memory notes (in MEMORY.md but no inbound [[wikilink]] from any sibling — the note',
365
+ );
366
+ out.push(
367
+ 'graph cannot reach them). Link each from a note someone would be reading when they need it:',
368
+ );
369
+ for (const n of orphans) out.push(` - ${n}`);
370
+ }
371
+
372
+ const read = (/** @type {string} */ p) => {
373
+ try {
374
+ return fs.readFileSync(p, 'utf8');
375
+ } catch {
376
+ return null;
377
+ }
378
+ };
379
+ const mocText = read(path.join(mem, 'MEMORY.md'));
380
+ if (mocText === null) return out.join('\n');
381
+ const drift = findDrift(mocText, (t) => read(path.join(mem, `${t}.md`)));
382
+ if (drift.length) {
383
+ out.push('');
384
+ out.push(
385
+ 'MEMORY.md figure drift — a bolded number in the MOC hook is absent from the note it points',
386
+ );
387
+ out.push(
388
+ 'at. Usually the note was corrected and the hook was not. Check the note, then fix the hook:',
389
+ );
390
+ for (const d of drift) out.push(` - [[${d.target}]] hook says ${d.n}, not found in the note`);
391
+ }
392
+
393
+ const oversize = findOversize(mocText);
394
+ if (oversize) {
395
+ if (out.length) out.push('');
396
+ out.push(oversize);
397
+ }
398
+ return out.join('\n');
399
+ }
400
+
401
+ /**
402
+ * Every non-missing `Memory/<slug>/MEMORY.md` in the vault, sized. The one walk both capReport and
403
+ * the per-start cost report read, so the two never disagree about which file a slug is.
404
+ *
405
+ * @param {string} vaultDir
406
+ * @returns {{ slug: string, bytes: number, lines: number, pct: number, empty: boolean }[]}
407
+ */
408
+ export function mocs(vaultDir) {
409
+ const memRoot = path.join(vaultDir, 'Memory');
410
+ /** @type {{ slug: string, bytes: number, lines: number, pct: number, empty: boolean }[]} */
411
+ const all = [];
412
+ let dirs;
413
+ try {
414
+ dirs = fs.readdirSync(memRoot, { withFileTypes: true });
415
+ } catch {
416
+ return [];
417
+ }
418
+ for (const d of dirs) {
419
+ if (!d.isDirectory()) continue;
420
+ let text;
421
+ try {
422
+ text = fs.readFileSync(path.join(memRoot, d.name, 'MEMORY.md'), 'utf8');
423
+ } catch {
424
+ continue;
425
+ }
426
+ const { bytes, lines } = mocSize(text);
427
+ all.push({
428
+ slug: d.name,
429
+ bytes,
430
+ lines,
431
+ // Content, not byte count: a MOC holding one newline injects exactly as much as a 0-byte one.
432
+ empty: text.trim() === '',
433
+ pct: Math.max(bytes / AUTO_MEMORY_CAP.bytes, lines / AUTO_MEMORY_CAP.lines),
434
+ });
435
+ }
436
+ return all;
437
+ }
438
+
439
+ /**
440
+ * `ok`/`warn`/`fail` lines about every `Memory/<slug>/MEMORY.md` in the vault, against the cap
441
+ * Claude Code loads them under. Tab-separated so `scripts/doctor.sh` can print them with its own
442
+ * helpers without a JSON parser — `jq` is optional there.
443
+ *
444
+ * Only the project the command was run from is named: this report is what people paste into
445
+ * issues, and the other slugs are normalised remotes of private repos. Every other MOC still gets
446
+ * its own percentage, largest first — "each MEMORY.md against the cap" is the point of the report,
447
+ * and a count alone cannot say whether the other one is at 99% or at 9%.
448
+ *
449
+ * @param {string} vaultDir
450
+ * @param {string} slug
451
+ * @returns {string[]}
452
+ */
453
+ export function capReport(vaultDir, slug) {
454
+ const all = mocs(vaultDir);
455
+ if (!all.length) return [];
456
+
457
+ const cap = `${AUTO_MEMORY_CAP.bytes.toLocaleString('en-US')} bytes / ${AUTO_MEMORY_CAP.lines} lines`;
458
+ const fix =
459
+ 'Claude Code loads only what fits and drops the rest, reporting nothing. Trim the MOC to one line per note.';
460
+ /** @type {string[]} */
461
+ const out = [];
462
+ const mine = all.find((m) => m.slug === slug);
463
+ if (mine) {
464
+ const size = `${mine.bytes.toLocaleString('en-US')} bytes / ${mine.lines} lines — ${pct(mine.pct)} of ${cap}`;
465
+ // Empty first: an empty MOC is 0% of the cap, and "fits the load cap" is exactly the
466
+ // empty-but-readable report this vault has been misled by before.
467
+ if (mine.empty)
468
+ out.push(
469
+ `warn\tthis project's MEMORY.md is empty\t` +
470
+ 'a readable empty index reports as healthy while nothing is injected. Add one line per note, or delete the file so the absence is visible.',
471
+ );
472
+ else if (mine.pct > 1)
473
+ out.push(`fail\tthis project's MEMORY.md is over the load cap: ${size}\t${fix}`);
474
+ else if (mine.pct >= NEAR)
475
+ out.push(`warn\tthis project's MEMORY.md is near the load cap: ${size}\t${fix}`);
476
+ else out.push(`ok\tthis project's MEMORY.md fits the load cap: ${size}`);
477
+ } else {
478
+ // Said out loud, because the alternative is worse than silence: a vault folder still under the
479
+ // legacy cwd-slug falls into `others`, which is deliberately unnamed — so "1 of 1 other
480
+ // MEMORY.md over the cap" would be YOUR index, reported as someone else's.
481
+ out.push(
482
+ `warn\tno MEMORY.md for this project (${slug})\t` +
483
+ 'nothing is injected as auto memory here. Expected on a first install; if this project has notes, its vault folder is under a different key — check Memory/ in the vault against the project name above.',
484
+ );
485
+ }
486
+ const others = all.filter((m) => m !== mine).sort((a, b) => b.pct - a.pct);
487
+ if (others.length) {
488
+ const pcts = others.map((m) => pct(m.pct)).join(', ');
489
+ const over = others.filter((m) => m.pct > 1).length;
490
+ const near = others.filter((m) => m.pct >= NEAR && m.pct <= 1).length;
491
+ if (over || near)
492
+ out.push(
493
+ `warn\t${over} of ${others.length} other MEMORY.md over the cap, ${near} near it — ${pcts}\t` +
494
+ 'other projects are not named — this report gets pasted into issues. Run /memory:doctor from each one.',
495
+ );
496
+ else out.push(`ok\t${others.length} other MEMORY.md all fit the cap — ${pcts}`);
497
+ }
498
+ return out;
499
+ }