@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,33 @@
1
+ #!/usr/bin/env node
2
+ // Set up machine-local state, the embedding model and the index. Usage: memory-setup.mjs --help
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import * as paths from '../hooks/lib/paths.mjs';
6
+ import { isPluginInstall } from './lib/share-modules.mjs';
7
+ import { USAGE, parseSetupArgs, setup } from './lib/memory-setup.mjs';
8
+
9
+ const argv = process.argv.slice(2);
10
+ if (argv.includes('--help') || argv.includes('-h')) {
11
+ console.log(`usage: ${USAGE}`);
12
+ process.exit(0);
13
+ }
14
+ const opts = parseSetupArgs(argv, process.cwd());
15
+ if ('error' in opts) {
16
+ console.error(`${opts.error}\nusage: ${USAGE}`);
17
+ process.exit(1);
18
+ }
19
+ process.exitCode = setup(opts, {
20
+ home: paths.memoryHome(),
21
+ nodeVersion: process.versions.node,
22
+ pluginInstall: isPluginInstall(paths.pluginRoot),
23
+ resolveVault: paths.vault,
24
+ run: (script, args, model) => {
25
+ const r = spawnSync(process.execPath, [path.join(paths.scriptsDir, script), ...args], {
26
+ env: { ...process.env, MEMORY_SEMANTIC_MODEL: process.env.MEMORY_SEMANTIC_MODEL || model },
27
+ encoding: 'utf8',
28
+ stdio: ['ignore', 'pipe', 'inherit'],
29
+ });
30
+ return { code: r.status ?? 1, out: r.stdout ?? '' };
31
+ },
32
+ print: (l) => console.log(l),
33
+ });
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env node
2
+ // Generate a FIXED synthetic vault + query sets, so retrieval numbers are reproducible.
3
+ //
4
+ // Thin CLI entry: argv in, files out. The material (DOMAINS), the seeded PRNG and the note
5
+ // formatter live in lib/memory-synth-vault.mjs, with their tests beside them.
6
+ //
7
+ // Usage:
8
+ // node scripts/memory-synth-vault.mjs --out /tmp/synthvault [--notes 300] [--seed 7] [--echoes 2]
9
+ // node scripts/memory-semantic.mjs --vault /tmp/synthvault --slug bench --index --rebuild
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import {
13
+ mulberry32,
14
+ noteText,
15
+ DOMAINS,
16
+ ECHO_CAUSES,
17
+ FILLER_ASPECTS,
18
+ SUPERSEDED,
19
+ SUPERSEDED_ON,
20
+ ABSTAIN,
21
+ } from './lib/memory-synth-vault.mjs';
22
+ import { TYPE } from './lib/memory-eval.mjs';
23
+
24
+ /** @typedef {{ q: string, gold: string[], style: string, owner?: string, type?: string }} EvalCase */
25
+
26
+ const argv = process.argv.slice(2);
27
+ /**
28
+ * @template T
29
+ * @param {string} n
30
+ * @param {T} d
31
+ * @returns {string | T}
32
+ */
33
+ const val = (n, d) => {
34
+ const i = argv.indexOf(n);
35
+ return i >= 0 ? argv[i + 1] : d;
36
+ };
37
+ const OUT = val('--out', /** @type {string | null} */ (null));
38
+ const RAW_NOTES = val('--notes', 300);
39
+ const TOTAL = Number(RAW_NOTES);
40
+ const RAW_SEED = val('--seed', 7);
41
+ const SEED = Number(RAW_SEED);
42
+ const RAW_ECHOES = val('--echoes', 2);
43
+ const ECHOES_PER_GOLD = Number(RAW_ECHOES);
44
+
45
+ if (!OUT) {
46
+ console.log('usage: --out <dir> [--notes 300] [--seed 7] [--echoes 2]');
47
+ process.exit(1);
48
+ }
49
+
50
+ // --notes is a CEILING on the whole vault, and gold+echoes are written first. Below one gold
51
+ // note plus its echoes there is nothing to measure, so refuse rather than write an empty case
52
+ // set; above it, MAX_GOLD scales the gold cases down so the printed total is the real one.
53
+ // Silently ignoring --notes is what #49 was.
54
+ if (!Number.isInteger(SEED)) {
55
+ // mulberry32 coerces with |0, so --seed abc silently generated the seed-0 vault under a
56
+ // MANIFEST claiming "seed NaN" — a stated parameter nobody can regenerate from.
57
+ console.error(`--seed must be a whole number, got ${RAW_SEED}`);
58
+ process.exit(1);
59
+ }
60
+ if (!(Number.isInteger(ECHOES_PER_GOLD) && ECHOES_PER_GOLD >= 0)) {
61
+ console.error(`--echoes must be a whole number >= 0, got ${RAW_ECHOES}`);
62
+ process.exit(1);
63
+ }
64
+ const PER_GOLD = 1 + ECHOES_PER_GOLD;
65
+ // Number.isInteger, not `TOTAL < PER_GOLD`: it is the one predicate that also rejects NaN (a
66
+ // non-numeric --notes), Infinity, and a fraction (--notes 60 --echoes 0.5 wrote 80). Each of
67
+ // those was #49 again through a different door. It does NOT bound the filler loop from above —
68
+ // --notes 1e21 is an integer and runs until you kill it, as it did before this.
69
+ // ponytail: no upper bound; add one if anyone ever asks for a vault they did not mean.
70
+ if (!(Number.isInteger(TOTAL) && TOTAL >= PER_GOLD)) {
71
+ console.error(
72
+ `--notes ${RAW_NOTES} must be a whole number >= the minimum ${PER_GOLD} (one gold note plus ${ECHOES_PER_GOLD} echoes)`,
73
+ );
74
+ process.exit(1);
75
+ }
76
+ const MAX_GOLD = Math.floor(TOTAL / PER_GOLD);
77
+
78
+ const rand = mulberry32(SEED);
79
+ const SLUG = 'bench';
80
+ const dirs = {
81
+ Memory: path.join(OUT, 'Memory', SLUG),
82
+ Patterns: path.join(OUT, 'Insights', SLUG, 'Patterns'),
83
+ Mistakes: path.join(OUT, 'Insights', SLUG, 'Mistakes'),
84
+ Decisions: path.join(OUT, 'Insights', SLUG, 'Decisions'),
85
+ permanent: path.join(OUT, 'permanent', 'tools'),
86
+ };
87
+ fs.rmSync(OUT, { recursive: true, force: true });
88
+ for (const d of Object.values(dirs)) fs.mkdirSync(d, { recursive: true });
89
+
90
+ /** @type {(keyof typeof dirs)[]} */
91
+ const layers = ['Memory', 'Patterns', 'Mistakes', 'Decisions', 'permanent'];
92
+ /** @type {string[]} */
93
+ const allNames = [];
94
+ /** @type {Record<'paraphrase' | 'keyword' | 'dutch' | 'supersede' | 'abstain', EvalCase[]>} */
95
+ const cases = { paraphrase: [], keyword: [], dutch: [], supersede: [], abstain: [] };
96
+
97
+ // gold notes — spread across layers so layer scoping is exercised, not assumed
98
+ // Truncation is round-robin across domains, then written back in the original order: taking the
99
+ // first MAX_GOLD of a domain-major walk gave CI's --notes 60 twenty gold cases from four of the
100
+ // eight domains, while filler kept coming from all eight — a case set whose vocabulary coverage
101
+ // changed silently with --notes. The second sort is what keeps the ORDER of cases-*.jsonl
102
+ // identical to an untruncated run, which is half of byte-identity at --notes 300.
103
+ //
104
+ // `i` below is the position in the SELECTED list, not the original index, and that is the other
105
+ // half of the same lesson: every domain has as many cases as there are layers, so the original
106
+ // index modulo layers.length IS the round-robin key — slicing it sliced whole layers, and CI's
107
+ // --notes 60 got no gold at all in Decisions or permanent. By position, the 20 survivors land
108
+ // 4-4-4-4-4. Untruncated the two are the same number, so 300 is unmoved.
109
+ const gold = DOMAINS.flatMap((d, di) => d.cases.map((c, ci) => ({ d, c, di, ci })))
110
+ .map((g, idx) => ({ ...g, idx }))
111
+ .sort((a, b) => a.ci - b.ci || a.di - b.di)
112
+ .slice(0, MAX_GOLD)
113
+ .sort((a, b) => a.idx - b.idx);
114
+
115
+ for (const [i, { d, c }] of gold.entries()) {
116
+ const name = `${d.product.toLowerCase()}-${c.title}`;
117
+ const layer = layers[i % layers.length];
118
+ const description = c.title.replace(/-/g, ' ');
119
+ fs.writeFileSync(
120
+ path.join(dirs[layer], `${name}.md`),
121
+ noteText(name, `${d.product}: ${description}`, c.body, [c.ask, c.key], []),
122
+ );
123
+ allNames.push(name);
124
+ // two echoes per gold note, same domain, same symptom, different cause
125
+ for (let e = 0; e < ECHOES_PER_GOLD; e++) {
126
+ const [cause, fix] = ECHO_CAUSES[(i + e) % ECHO_CAUSES.length];
127
+ const symptom = c.body.split('. ')[0];
128
+ const en = `${d.product.toLowerCase()}-similar-${e + 1}-${c.title}`;
129
+ const el = layers[(i + e + 1) % layers.length];
130
+ fs.writeFileSync(
131
+ path.join(dirs[el], `${en}.md`),
132
+ noteText(
133
+ en,
134
+ `${d.product}: a similar-looking ${d.name} symptom with a different cause (${e + 1})`,
135
+ `${symptom}. It looks like the better known problem in this area, but here the cause is ${cause}, ` +
136
+ `which is unrelated. The fix is to ${fix}. Confirm which one you have before changing anything.`,
137
+ [`${d.name} symptom with an unrelated cause ${e + 1}`],
138
+ [],
139
+ ),
140
+ );
141
+ allNames.push(en);
142
+ }
143
+ cases.paraphrase.push({ q: c.ask, gold: [name], style: 'synthetic-paraphrase' });
144
+ cases.keyword.push({ q: c.key, gold: [name], style: 'synthetic-keyword' });
145
+ cases.dutch.push({ q: c.nl, gold: [name], style: 'synthetic-dutch' });
146
+ }
147
+ const goldCount = cases.paraphrase.length; // gold cases, NOT files: echoes are distractors
148
+ const availableGold = DOMAINS.reduce((n, d) => n + d.cases.length, 0);
149
+ if (goldCount < availableGold)
150
+ console.log(
151
+ `--notes ${TOTAL} fits ${goldCount} of ${availableGold} gold cases (${PER_GOLD} note${PER_GOLD === 1 ? '' : 's'} each)`,
152
+ );
153
+
154
+ // knowledge updates take their room from filler, so --notes stays the whole vault
155
+ let pairNotes = 0;
156
+ for (const [i, u] of SUPERSEDED.entries()) {
157
+ if (allNames.length + 2 > TOTAL) break;
158
+ const d = DOMAINS[i];
159
+ const newer = `${d.product.toLowerCase()}-${u.topic}`;
160
+ const older = `${newer}-earlier`;
161
+ const description = `${d.product}: ${u.topic.replace(/-/g, ' ')}`;
162
+ fs.writeFileSync(
163
+ path.join(dirs[layers[i % layers.length]], `${newer}.md`),
164
+ noteText(newer, description, u.after, [u.ask], []),
165
+ );
166
+ fs.writeFileSync(
167
+ path.join(dirs[layers[(i + 1) % layers.length]], `${older}.md`),
168
+ noteText(
169
+ older,
170
+ description,
171
+ `${u.before} (superseded ${SUPERSEDED_ON} by [[${newer}]])`,
172
+ [u.ask],
173
+ [],
174
+ ),
175
+ );
176
+ allNames.push(newer, older);
177
+ pairNotes += 2;
178
+ cases.supersede.push({
179
+ q: u.ask,
180
+ owner: newer,
181
+ gold: [older],
182
+ type: TYPE.supersede,
183
+ style: 'synthetic-supersede',
184
+ });
185
+ }
186
+ for (const q of ABSTAIN)
187
+ cases.abstain.push({ q, gold: [], type: TYPE.abstain, style: 'synthetic-abstain' });
188
+
189
+ // filler notes — same subject areas, so they compete rather than pad
190
+ let f = 0;
191
+ while (allNames.length < TOTAL) {
192
+ const d = DOMAINS[Math.floor(rand() * DOMAINS.length)];
193
+ const [aspect, prose] = FILLER_ASPECTS[f % FILLER_ASPECTS.length];
194
+ const name = `${d.product.toLowerCase()}-${aspect}-${String(f).padStart(3, '0')}`;
195
+ const layer = layers[Math.floor(rand() * layers.length)];
196
+ fs.writeFileSync(
197
+ path.join(dirs[layer], `${name}.md`),
198
+ noteText(
199
+ name,
200
+ `${d.product}: ${aspect.replace(/-/g, ' ')} for ${d.name}`,
201
+ prose,
202
+ [`${d.name} ${aspect.replace(/-/g, ' ')}`],
203
+ [],
204
+ ),
205
+ );
206
+ allNames.push(name);
207
+ f++;
208
+ }
209
+
210
+ for (const [k, v] of Object.entries(cases))
211
+ fs.writeFileSync(
212
+ path.join(OUT, `cases-${k}.jsonl`),
213
+ v.map((c) => JSON.stringify(c)).join('\n') + (v.length ? '\n' : ''),
214
+ );
215
+
216
+ fs.writeFileSync(
217
+ path.join(OUT, 'MANIFEST.md'),
218
+ `# Synthetic benchmark vault
219
+
220
+ Generated by \`memory-synth-vault.mjs\` — seed ${SEED}, ${allNames.length} notes, ${goldCount} gold cases.
221
+ Regenerating with the same seed produces a byte-identical vault, so numbers measured here are
222
+ comparable across days and machines. **Every number quoted from this vault must name the seed and
223
+ the note count**, because both change the difficulty.
224
+
225
+ Query sets, which fail for different reasons:
226
+ - \`cases-paraphrase.jsonl\` — outsider wording, no title words, no product name. The real test.
227
+ - \`cases-keyword.jsonl\` — product name plus title words. Keyword search should win here.
228
+ - \`cases-dutch.jsonl\` — Dutch paraphrase against English notes. Cross-language reach.
229
+ - \`cases-supersede.jsonl\` — a knowledge update: the newer note must outrank the one it superseded.
230
+ - \`cases-abstain.jsonl\` — no answer in the vault. Passes only if the recall hook stays silent;
231
+ scored in semantic mode only.
232
+
233
+ What this does NOT measure (borrowed discipline from obsidian-second-brain's BENCHMARK.md):
234
+ - **Single gold answer per query.** Real vaults have several defensible answers; a note ranked above
235
+ the target may genuinely be about the subject. Scores here are pessimistic in that respect.
236
+ - **Synthetic prose is tidier than real notes.** No half-finished notes, no dead links, no
237
+ contradictions — so absolute scores are optimistic relative to a real vault.
238
+ - **${allNames.length} notes is small.** Index size, latency and scan caps are not exercised.
239
+ - **Filler notes are templated**, so they compete less fiercely than real sibling notes do.
240
+ `,
241
+ );
242
+
243
+ console.log(
244
+ `${allNames.length} notes (${goldCount} gold, ${goldCount * ECHOES_PER_GOLD} echoes, ${pairNotes} in superseded pairs, ${allNames.length - goldCount * (1 + ECHOES_PER_GOLD) - pairNotes} filler) → ${OUT}`,
245
+ );
246
+ console.log(
247
+ `cases: paraphrase ${cases.paraphrase.length}, keyword ${cases.keyword.length}, dutch ${cases.dutch.length}, supersede ${cases.supersede.length}, abstain ${cases.abstain.length}`,
248
+ );
249
+ console.log(
250
+ `index it: node "${new URL('./memory-semantic.mjs', import.meta.url).pathname}" --vault ${OUT} --slug ${SLUG} --index --rebuild`,
251
+ );
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // Archive session logs older than N days (default 90) into <logs-dir>/Archive/.
3
+ // Moving only (reversible); never deletes. Usage: prune-logs.mjs <logs-dir>
4
+ import fs from 'node:fs';
5
+ import { parseDays, pruneLogs } from './lib/prune-logs.mjs';
6
+
7
+ /** @typedef {import('./lib/prune-logs.mjs').PrunePartialError} PrunePartialError */
8
+
9
+ const dir = process.argv[2];
10
+ if (!dir) {
11
+ console.error('usage: prune-logs.mjs <logs-dir>');
12
+ process.exit(1);
13
+ }
14
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
15
+ console.log(`no logs dir: ${dir}`);
16
+ process.exit(0);
17
+ }
18
+
19
+ const raw = process.env.PRUNE_DAYS ?? '';
20
+ const days = parseDays(raw);
21
+ if (!Number.isInteger(days)) {
22
+ console.error(`PRUNE_DAYS must be a whole number of days, got: ${JSON.stringify(raw)}`);
23
+ process.exit(1);
24
+ }
25
+
26
+ /** @param {import('./lib/prune-logs.mjs').PruneResult} result */
27
+ function report({ moved, skipped, collisions }) {
28
+ console.log(`archived ${moved.length} log(s) older than ${days}d from ${dir}`);
29
+ for (const n of skipped) console.log(`skipped (no usable date in filename): ${n}`);
30
+ for (const n of collisions) console.log(`skipped (already in Archive/, left in place): ${n}`);
31
+ }
32
+
33
+ try {
34
+ report(pruneLogs(dir, { days }));
35
+ } catch (err) {
36
+ // A mid-run failure still has to say what already moved, or the move is not reversible in
37
+ // practice — `err.partial` is the result so far, attached by pruneLogs().
38
+ const e = /** @type {PrunePartialError} */ (err);
39
+ if (e.partial) report(e.partial);
40
+ console.error(`prune failed: ${e.message}`);
41
+ process.exit(1);
42
+ }
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ // Point every installed version of this plugin at one node_modules in $CLAUDE_MEMORY_HOME.
3
+ // Run from /memory:install. Unlike the other scripts here this one deletes directories, so it
4
+ // refuses to run anywhere but inside a plugin cache — a git checkout must be left alone.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+ import { fileURLToPath } from 'node:url';
9
+ import {
10
+ isPluginInstall,
11
+ isRemovable,
12
+ isRealDir,
13
+ isLink,
14
+ hasInstall,
15
+ siblingCopies,
16
+ } from './lib/share-modules.mjs';
17
+ import { bytes } from './lib/slim-install.mjs';
18
+
19
+ const versionDir = fileURLToPath(new URL('..', import.meta.url)).replace(/\/$/, '');
20
+ const state = process.env.CLAUDE_MEMORY_HOME || path.join(os.homedir(), '.claude-memory');
21
+ const shared = path.join(state, 'node_modules');
22
+ const here = path.join(versionDir, 'node_modules');
23
+
24
+ if (!isPluginInstall(versionDir)) {
25
+ console.error(`refusing: ${versionDir} is not a plugin install (no plugins/cache in the path).`);
26
+ console.error(
27
+ 'This is for the installed plugin, not a checkout — a checkout keeps its own node_modules.',
28
+ );
29
+ process.exit(1);
30
+ }
31
+
32
+ /** @type {(p: string) => number} */
33
+ const remove = (p) => {
34
+ if (!isRemovable(p)) throw new Error(`refusing to remove ${p}`);
35
+ const size = bytes(p);
36
+ fs.rmSync(p, { recursive: true, force: true });
37
+ return size;
38
+ };
39
+
40
+ let freed = 0;
41
+
42
+ // 1. Establish the shared copy. rename() is a no-copy move when $CLAUDE_MEMORY_HOME is on the
43
+ // same filesystem, and a fallback is needed when it is not.
44
+ if (!hasInstall(shared)) {
45
+ if (!hasInstall(here)) {
46
+ console.error(
47
+ `nothing to share: no install in ${here} or ${shared}. Run npm ci first (step 4).`,
48
+ );
49
+ process.exit(1);
50
+ }
51
+ try {
52
+ if (isRealDir(shared)) fs.rmdirSync(shared);
53
+ } catch {
54
+ console.error(`refusing: ${shared} has files but no install. Remove it by hand, then re-run.`);
55
+ process.exit(1);
56
+ }
57
+ fs.mkdirSync(state, { recursive: true });
58
+ try {
59
+ fs.renameSync(here, shared);
60
+ } catch {
61
+ fs.cpSync(here, shared, { recursive: true, verbatimSymlinks: true });
62
+ remove(here);
63
+ }
64
+ console.log(`moved node_modules to ${shared}`);
65
+ }
66
+
67
+ // 2. This version, then every other installed version, points at it.
68
+ for (const dir of [here, ...siblingCopies(versionDir)]) {
69
+ if (isLink(dir)) continue; // already shared
70
+ if (isRealDir(dir)) freed += remove(dir);
71
+ fs.symlinkSync(shared, dir, 'dir');
72
+ }
73
+
74
+ const total = Math.round(bytes(shared) / 2 ** 20);
75
+ console.log(
76
+ freed
77
+ ? `shared node_modules: reclaimed ${Math.round(freed / 2 ** 20)} MB, ${total} MB now kept once`
78
+ : `shared node_modules: already consolidated (${total} MB)`,
79
+ );
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ // postinstall: strip the 320 MB of node_modules this plugin can never execute — other platforms'
3
+ // native binaries, the browser WASM backend, and the image pipeline. See scripts/lib/slim-install.mjs
4
+ // for why each one is dead weight, and stubs/README.md for why two of them need a stub rather than
5
+ // a delete. Best-effort like every hook here: a failure must never fail an install.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import {
10
+ pruneTargets,
11
+ providerBlobs,
12
+ findPackages,
13
+ isStub,
14
+ bytes,
15
+ STUBBED,
16
+ DELETED,
17
+ } from './lib/slim-install.mjs';
18
+
19
+ const root = fileURLToPath(new URL('..', import.meta.url));
20
+ const modules = path.join(root, 'node_modules');
21
+ let freed = 0;
22
+ const done = [];
23
+
24
+ /** @type {(target: string, label: string) => number} */
25
+ const drop = (target, label) => {
26
+ const size = bytes(target);
27
+ freed += size;
28
+ fs.rmSync(target, { recursive: true, force: true });
29
+ if (label) done.push(label);
30
+ return size;
31
+ };
32
+
33
+ try {
34
+ const binDir = path.join(modules, 'onnxruntime-node', 'bin');
35
+ for (const dir of pruneTargets(binDir)) drop(dir, `ort-node ${path.relative(binDir, dir)}`);
36
+
37
+ let gpu = 0;
38
+ for (const blob of providerBlobs(binDir)) gpu += drop(blob, '') || 0;
39
+ if (gpu) done.push('gpu execution providers');
40
+
41
+ for (const dir of findPackages(modules, STUBBED)) {
42
+ if (isStub(dir)) continue; // already slimmed
43
+ const stub = path.join(root, 'stubs', path.basename(dir));
44
+ if (!fs.existsSync(stub)) continue; // stub missing — leave the real package working
45
+ drop(dir, `${path.basename(dir)} (stubbed)`);
46
+ fs.cpSync(stub, dir, { recursive: true });
47
+ }
48
+
49
+ for (const dir of findPackages(modules, DELETED)) drop(dir, path.basename(dir));
50
+
51
+ if (freed)
52
+ console.log(`slim-install: freed ${Math.round(freed / 2 ** 20)} MB — ${done.join(', ')}`);
53
+ } catch (err) {
54
+ console.warn(`slim-install skipped: ${/** @type {Error} */ (err).message}`);
55
+ }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // Read-only MCP server over the vault. Usage:
3
+ // node scripts/vault-mcp.mjs --port <n> [--host <addr>] [--token-file <path>]
4
+ // The token comes from --token-file, else $CREDENTIALS_DIRECTORY/vault-mcp-token, never from env.
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { CARD } from './lib/lexical.mjs';
7
+ import { readToken, startServer } from './lib/vault-mcp.mjs';
8
+
9
+ /** @param {string} dbFile */
10
+ function readCards(dbFile) {
11
+ const db = new DatabaseSync(dbFile, { readOnly: true });
12
+ try {
13
+ return /** @type {import('./lib/vault-mcp.mjs').Card[]} */ (
14
+ /** @type {unknown} */ (
15
+ db.prepare('SELECT note, layer, text FROM chunks WHERE heading = ?').all(CARD)
16
+ )
17
+ );
18
+ } finally {
19
+ db.close();
20
+ }
21
+ }
22
+
23
+ const argv = process.argv.slice(2);
24
+ const val = (/** @type {string} */ n) => {
25
+ const i = argv.indexOf(n);
26
+ return i >= 0 ? argv[i + 1] : undefined;
27
+ };
28
+
29
+ const port = Number(val('--port'));
30
+ if (val('--port') === undefined || !Number.isInteger(port) || port < 0 || port > 65535) {
31
+ console.error('usage: vault-mcp --port <n> [--host <addr>] [--token-file <path>]');
32
+ process.exit(2);
33
+ }
34
+ let token;
35
+ try {
36
+ token = readToken({
37
+ tokenFile: val('--token-file'),
38
+ credentialsDir: process.env.CREDENTIALS_DIRECTORY,
39
+ });
40
+ } catch (e) {
41
+ console.error(`vault-mcp: ${/** @type {Error} */ (e).message}`);
42
+ process.exit(1);
43
+ }
44
+ const host = val('--host') ?? '127.0.0.1';
45
+ const server = startServer({ host, port, token, readCards });
46
+ server.on('listening', () => console.error(`vault-mcp listening on ${host}:${port}`));
47
+ server.on('error', (e) => {
48
+ console.error(`vault-mcp: ${e.message}`);
49
+ process.exit(1);
50
+ });
@@ -0,0 +1,11 @@
1
+ // Stub for onnxruntime-web. @huggingface/transformers imports it statically from
2
+ // transformers.node.mjs, so it cannot simply be absent — but nothing on the
3
+ // text-embedding path ever calls it. Throwing beats a silent wrong backend.
4
+ const die = () => {
5
+ throw new Error(
6
+ 'onnxruntime-web is stubbed in this install (text-only build). ' +
7
+ 'If you need it, drop the override in package.json.',
8
+ );
9
+ };
10
+
11
+ export default new Proxy(die, { get: () => die, apply: () => die() });
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "onnxruntime-web",
3
+ "version": "0.0.0-stub",
4
+ "description": "Stub — see README.md in this directory.",
5
+ "license": "MIT",
6
+ "private": true,
7
+ "type": "module",
8
+ "main": "index.mjs",
9
+ "exports": {
10
+ ".": "./index.mjs"
11
+ }
12
+ }
@@ -0,0 +1,11 @@
1
+ // Stub for sharp. @huggingface/transformers imports it statically from
2
+ // transformers.node.mjs, so it cannot simply be absent — but nothing on the
3
+ // text-embedding path ever calls it. Throwing beats a silent wrong backend.
4
+ const die = () => {
5
+ throw new Error(
6
+ 'sharp is stubbed in this install (text-only build). ' +
7
+ 'If you need it, drop the override in package.json.',
8
+ );
9
+ };
10
+
11
+ export default new Proxy(die, { get: () => die, apply: () => die() });
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "sharp",
3
+ "version": "0.0.0-stub",
4
+ "description": "Stub — see README.md in this directory.",
5
+ "license": "MIT",
6
+ "private": true,
7
+ "type": "module",
8
+ "main": "index.mjs",
9
+ "exports": {
10
+ ".": "./index.mjs"
11
+ }
12
+ }