@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,168 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** @typedef {{ script: string, usage: string, about: string, args?: (rest: string[]) => string[] }} Command */
5
+
6
+ /** @type {Record<string, Command>} */
7
+ export const COMMANDS = {
8
+ search: {
9
+ script: 'memory-semantic.mjs',
10
+ usage: 'search <query...> [-k 5] [--json] [--slug <slug>] [--vault <dir>]',
11
+ about: 'search the vault; one hit per line: score<TAB>layer<TAB>path<TAB>snippet',
12
+ args: searchArgs,
13
+ },
14
+ index: {
15
+ script: 'memory-semantic.mjs',
16
+ usage: 'index [dir] [--rebuild]',
17
+ about: "build or refresh this project's search index",
18
+ args: (rest) => ['--index', ...rest],
19
+ },
20
+ semantic: {
21
+ script: 'memory-semantic.mjs',
22
+ usage: 'semantic --coverage | --dupes | --clusters | --check-embedding | ...',
23
+ about: 'run memory-semantic.mjs with its own flags',
24
+ },
25
+ doctor: {
26
+ script: 'doctor.sh',
27
+ usage: 'doctor [--perf | --stats | --hooks]',
28
+ about: 'diagnose the install (read-only)',
29
+ },
30
+ eval: {
31
+ script: 'memory-eval.mjs',
32
+ usage: 'eval --run [--cases <path>] [--json] | --generate <n> | --author',
33
+ about: 'score retrieval against a fixed case set',
34
+ },
35
+ setup: {
36
+ script: 'memory-setup.mjs',
37
+ usage: 'setup [--vault <path>] [--model <name>] [--force]',
38
+ about: 'write config.json, state dirs, download and check the model, build the index',
39
+ },
40
+ prune: {
41
+ script: 'memory-prune.mjs',
42
+ usage: 'prune [--slug <key>] [--dry-run]',
43
+ about: 'archive logs older than 90 days, refresh the index, list candidate duplicates',
44
+ },
45
+ mark: {
46
+ script: 'memory-mark.mjs',
47
+ usage: 'mark [--unmark] <note> [...]',
48
+ about: 'set reconcile: manual so nothing auto-merges into a note',
49
+ },
50
+ merge: {
51
+ script: 'memory-merge.mjs',
52
+ usage: 'merge [--dry-run] <survivor> <redundant> [...] | --plan <file.json>',
53
+ about: 'merge duplicate notes into one survivor',
54
+ },
55
+ adopt: {
56
+ script: 'memory-adopt.mjs',
57
+ usage: 'adopt <staged-note> --min-rank1 <percent> [--cases <path>] | --dry-run',
58
+ about: 'promote a reviewed Staging/ draft into permanent/',
59
+ },
60
+ audit: {
61
+ script: 'memory-audit-checks.mjs',
62
+ usage: 'audit [repo] | --check-file <f> | --deferred',
63
+ about: 'mechanical vault-audit checks',
64
+ },
65
+ mcp: {
66
+ script: 'memory-mcp.mjs',
67
+ usage: 'mcp',
68
+ about: 'stdio MCP server with one tool, memory_search',
69
+ },
70
+ };
71
+
72
+ /** @param {string[]} rest */
73
+ function searchArgs(rest) {
74
+ const out = [];
75
+ const words = [];
76
+ let json = false;
77
+ for (let i = 0; i < rest.length; i++) {
78
+ const a = rest[i];
79
+ if (a === '--') {
80
+ words.push(...rest.slice(i + 1));
81
+ break;
82
+ }
83
+ if (a === '--json') json = true;
84
+ else if (a === '-k' || a === '--slug' || a === '--vault') {
85
+ if (!rest[i + 1] || rest[i + 1].startsWith('-'))
86
+ throw new Error(`search: ${a} needs a value`);
87
+ out.push(a, rest[++i]);
88
+ } else words.push(a);
89
+ }
90
+ const query = words.join(' ');
91
+ if (!query.trim()) throw new Error('search needs a query');
92
+ return ['--query', query, ...out, json ? '--json' : '--tsv'];
93
+ }
94
+
95
+ /** @param {string} version */
96
+ export function help(version) {
97
+ const w = Math.max(...Object.keys(COMMANDS).map((k) => k.length));
98
+ return [
99
+ `claude-memory ${version} — layered memory over a Markdown vault`,
100
+ '',
101
+ 'usage: claude-memory <command> [args] (claude-memory <command> --help for its flags)',
102
+ '',
103
+ ...Object.entries(COMMANDS).map(([k, c]) => ` ${k.padEnd(w)} ${c.about}`),
104
+ ].join('\n');
105
+ }
106
+
107
+ /**
108
+ * The argv for one subcommand, or the text to print instead.
109
+ *
110
+ * @param {string[]} argv
111
+ * @param {{ scriptsDir: string, node: string, version: string }} env
112
+ * @returns {{ print: string, code: number } | { cmd: string, args: string[] }}
113
+ */
114
+ export function resolve(argv, { scriptsDir, node, version }) {
115
+ const [name, ...rest] = argv;
116
+ if (!name || name === '--help' || name === '-h' || name === 'help')
117
+ return { print: help(version), code: 0 };
118
+ if (name === '--version' || name === '-v') return { print: version, code: 0 };
119
+ if (!Object.hasOwn(COMMANDS, name))
120
+ return { print: `unknown command: ${name}\n\n${help(version)}`, code: 1 };
121
+ const c = COMMANDS[name];
122
+ if (rest.length === 1 && (rest[0] === '--help' || rest[0] === '-h'))
123
+ return { print: `usage: claude-memory ${c.usage}\n\n${c.about}`, code: 0 };
124
+ let args;
125
+ try {
126
+ args = c.args ? c.args(rest) : rest;
127
+ } catch (e) {
128
+ return {
129
+ print: `${/** @type {Error} */ (e).message}\nusage: claude-memory ${c.usage}`,
130
+ code: 1,
131
+ };
132
+ }
133
+ const file = path.join(scriptsDir, c.script);
134
+ return c.script.endsWith('.sh')
135
+ ? { cmd: 'bash', args: [file, ...args] }
136
+ : { cmd: node, args: [file, ...args] };
137
+ }
138
+
139
+ /**
140
+ * A warning when this CLI and the plugin that last ran a SessionStart differ in version — once per
141
+ * pair, claimed with `wx` like log retention, so an agent calling search in a loop sees it once.
142
+ *
143
+ * @param {string} home $CLAUDE_MEMORY_HOME
144
+ * @param {string} version
145
+ * @returns {string | null}
146
+ */
147
+ export function versionWarning(home, version) {
148
+ let plugin;
149
+ try {
150
+ const root = fs.readFileSync(path.join(home, 'plugin-root'), 'utf8').trim();
151
+ plugin = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;
152
+ } catch {
153
+ return null;
154
+ }
155
+ if (
156
+ typeof plugin !== 'string' ||
157
+ !/^\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/.test(plugin) ||
158
+ plugin === version
159
+ )
160
+ return null;
161
+ try {
162
+ fs.mkdirSync(path.join(home, 'run'), { recursive: true });
163
+ fs.closeSync(fs.openSync(path.join(home, 'run', `version-warned-${version}-${plugin}`), 'wx'));
164
+ } catch {
165
+ return null;
166
+ }
167
+ return `claude-memory: CLI is ${version}, installed plugin is ${plugin} — update the older one`;
168
+ }
@@ -0,0 +1,434 @@
1
+ // The `--perf` half of /memory:doctor: where the CPU, the RAM and the disk actually went.
2
+ // The CLI entry is scripts/doctor-perf.mjs.
3
+ //
4
+ // doctor.sh answers "is this wired up". It cannot answer "why is this slow" or "what is eating my
5
+ // RAM" — the multi-server RSS problem this exists to diagnose is in CLAUDE.md's "One `--serve` for
6
+ // the whole machine" section.
7
+ //
8
+ // Read-only, and that is a hard rule, not a preference: this must never start a server, load a
9
+ // model or re-index. Everything below either reads a file, parses `ps`, or talks to a socket that
10
+ // is ALREADY listening.
11
+ //
12
+ // Node rather than more bash because every line of it loops — over db files, over a directory
13
+ // tree, over ps output — and a hook that loops belongs in Node.
14
+
15
+ import fs from 'node:fs';
16
+ import net from 'node:net';
17
+ import path from 'node:path';
18
+ import { execFileSync } from 'node:child_process';
19
+
20
+ /** @typedef {{ pid: number, rss: number, elapsed: string }} ServerRow */
21
+ /** @typedef {{ bytes: number, files: number, missing: boolean }} DirUsage */
22
+ /** @typedef {{ slug: string, model: string }} IndexName */
23
+ /**
24
+ * @typedef {{
25
+ * slug: string,
26
+ * model: string,
27
+ * file: string,
28
+ * bytes: number,
29
+ * chunks: number | null,
30
+ * notes: number | null,
31
+ * mtime: Date | null,
32
+ * }} IndexRow
33
+ */
34
+ /** @typedef {(file: string) => { chunks: number, notes: number } | null} CountsReader */
35
+ /** @typedef {{ ok: true, ms: number, hits: number | null }} ProbeOk */
36
+ /** @typedef {{ ok: false, reason?: string }} ProbeFail */
37
+ /** @typedef {ProbeOk | ProbeFail} ProbeResult */
38
+ /**
39
+ * @typedef {{
40
+ * state: string,
41
+ * activeModel: string,
42
+ * activeSlug: string,
43
+ * modelKeys?: readonly string[],
44
+ * counts?: CountsReader,
45
+ * ps?: string,
46
+ * }} ReportOptions
47
+ */
48
+
49
+ /**
50
+ * Bytes as a human reads them. Two significant-ish digits: 1.3 GB, not 1.29 GB or 1 GB.
51
+ *
52
+ * @param {number} n
53
+ * @returns {string}
54
+ */
55
+ export function formatBytes(n) {
56
+ if (!Number.isFinite(n) || n < 0) return '-';
57
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
58
+ let i = 0;
59
+ let v = n;
60
+ while (v >= 1024 && i < units.length - 1) {
61
+ v /= 1024;
62
+ i++;
63
+ }
64
+ return `${i === 0 ? v : v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
65
+ }
66
+
67
+ /**
68
+ * Column-aligned rows. The last column is never padded — trailing spaces survive a paste.
69
+ *
70
+ * @param {readonly string[]} headers
71
+ * @param {readonly (readonly unknown[])[]} rows
72
+ * @returns {string}
73
+ */
74
+ export function table(headers, rows) {
75
+ const all = [headers, ...rows].map((r) => r.map((c) => String(c ?? '')));
76
+ const width = headers.map((_, i) => Math.max(...all.map((r) => (r[i] ?? '').length)));
77
+ return all
78
+ .map((r) =>
79
+ r
80
+ .map((c, i) => (i === r.length - 1 ? c : c.padEnd(width[i])))
81
+ .join(' ')
82
+ .replace(/\s+$/, ''),
83
+ )
84
+ .join('\n');
85
+ }
86
+
87
+ /**
88
+ * The resident search servers, from one `ps` listing.
89
+ *
90
+ * Parsed rather than looked up by pid file because the thing worth reporting is exactly the case
91
+ * no pid file covers: MORE THAN ONE server alive. `command=` is last so a command containing
92
+ * spaces cannot eat the columns before it.
93
+ *
94
+ * @param {unknown} psOutput
95
+ * @returns {ServerRow[]}
96
+ */
97
+ export function parseServers(psOutput) {
98
+ /** @type {ServerRow[]} */
99
+ const out = [];
100
+ for (const line of String(psOutput ?? '').split('\n')) {
101
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
102
+ if (!m) continue;
103
+ const [, pid, rssKb, elapsed, cmd] = m;
104
+ if (!/memory-semantic\.mjs/.test(cmd) || !/--serve/.test(cmd)) continue;
105
+ out.push({ pid: Number(pid), rss: Number(rssKb) * 1024, elapsed });
106
+ }
107
+ return out;
108
+ }
109
+
110
+ // `modelIdleMs` unloads the model and leaves the socket, indexes and BM25 tokens behind, so the two
111
+ // states are an order of magnitude apart in RSS and nothing else has to be asked. Measured on this
112
+ // machine 2026-08-20, one server, bge-m3: 15 MB idle-unloaded, 370 MB immediately after a query.
113
+ // The midpoint is the threshold; it is not close to either state.
114
+ // ponytail: RSS threshold, not a real probe — add a status field to the socket reply if it ever
115
+ // has to be exact.
116
+ export const MODEL_RSS_THRESHOLD = 100 * 1024 * 1024;
117
+
118
+ /** @param {number} rss @returns {string} */
119
+ export const modelState = (rss) => (rss >= MODEL_RSS_THRESHOLD ? 'model loaded' : 'model unloaded');
120
+
121
+ /**
122
+ * Total bytes and file count under `dir`. A missing directory is zeroes, not a throw.
123
+ *
124
+ * `recursive: true` walks it; the entries come back with a `parentPath`, so no recursion here.
125
+ *
126
+ * Symlinks are skipped rather than followed. Not for a reason specific to these directories — none
127
+ * of the six scanned here is a link today — but because every past size check in this repo that
128
+ * dereferenced one measured something other than what it claimed to (risk R8 in
129
+ * docs/architecture.md), and `$CLAUDE_MEMORY_HOME` is exactly where links get added.
130
+ *
131
+ * @param {string} dir
132
+ * @returns {DirUsage}
133
+ */
134
+ export function dirUsage(dir) {
135
+ let entries;
136
+ try {
137
+ entries = fs.readdirSync(dir, { recursive: true, withFileTypes: true });
138
+ } catch {
139
+ return { bytes: 0, files: 0, missing: true };
140
+ }
141
+ let bytes = 0;
142
+ let files = 0;
143
+ for (const e of entries) {
144
+ // Not `isFile()`: run/ holds unix SOCKETS, and reporting it as empty would hide the servers.
145
+ if (e.isDirectory() || e.isSymbolicLink()) continue;
146
+ try {
147
+ bytes += fs.lstatSync(path.join(e.parentPath, e.name)).size;
148
+ files++;
149
+ } catch {
150
+ /* raced with a delete */
151
+ }
152
+ }
153
+ return { bytes, files, missing: false };
154
+ }
155
+
156
+ /**
157
+ * `semantic-<slug>-<model>.db` -> its two parts.
158
+ *
159
+ * Both halves contain dashes (`bge-small-en`, `github.com-spike1292-claude-memory`), so the split
160
+ * cannot be positional — it is driven by the KNOWN model keys, longest first, since `bge-m3` and
161
+ * `bge-small-en` share a prefix. The keys come from MODELS in models.mjs; a second list here would
162
+ * drift and silently mislabel every row.
163
+ *
164
+ * @param {string} file
165
+ * @param {readonly string[]} modelKeys
166
+ * @returns {IndexName | null}
167
+ */
168
+ export function parseIndexName(file, modelKeys) {
169
+ if (!file.startsWith('semantic-')) return null;
170
+ for (const model of [...modelKeys].sort((a, b) => b.length - a.length)) {
171
+ const tail = `-${model}.db`;
172
+ if (!file.endsWith(tail)) continue;
173
+ const slug = file.slice('semantic-'.length, -tail.length);
174
+ if (slug) return { slug, model };
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /**
180
+ * One row per index on this machine: size, chunks, notes, and when it was last written.
181
+ *
182
+ * `counts(file)` is injected: `node:sqlite` belongs to the entry point, which owns the handle, so
183
+ * this module takes the numbers as values and stays testable without a database. Enforced by CI.
184
+ * A db it cannot read comes back null and is REPORTED as unreadable rather than skipped — that is
185
+ * precisely the state that makes recall go quiet.
186
+ *
187
+ * @param {string} dbDir
188
+ * @param {readonly string[]} [modelKeys]
189
+ * @param {CountsReader} [counts]
190
+ * @returns {IndexRow[]}
191
+ */
192
+ export function indexStats(dbDir, modelKeys = [], counts = () => null) {
193
+ let files;
194
+ try {
195
+ files = fs.readdirSync(dbDir).filter((f) => f.endsWith('.db'));
196
+ } catch {
197
+ return [];
198
+ }
199
+ return files
200
+ .map((f) => {
201
+ const parts = parseIndexName(f, modelKeys) ?? { slug: f.replace(/\.db$/, ''), model: '?' };
202
+ const full = path.join(dbDir, f);
203
+ const row = /** @type {IndexRow} */ ({
204
+ ...parts,
205
+ file: f,
206
+ bytes: 0,
207
+ chunks: null,
208
+ notes: null,
209
+ mtime: null,
210
+ });
211
+ try {
212
+ const st = fs.statSync(full);
213
+ row.bytes = st.size;
214
+ row.mtime = st.mtime;
215
+ } catch {
216
+ /* reported as zeroes */
217
+ }
218
+ const c = counts(full);
219
+ if (c) {
220
+ row.chunks = c.chunks;
221
+ row.notes = c.notes;
222
+ }
223
+ return row;
224
+ })
225
+ .sort((a, b) => b.bytes - a.bytes);
226
+ }
227
+
228
+ /**
229
+ * Time one query against a socket that is already listening.
230
+ *
231
+ * Never spawns. `existsSync` is not proof the other end is alive — a socket file outlives the
232
+ * process that bound it — so a refused connection is a normal answer here, not an error.
233
+ *
234
+ * @param {string} sockPath
235
+ * @param {{ slug?: string, q?: string, timeoutMs?: number }} [options]
236
+ * @returns {Promise<ProbeResult>}
237
+ */
238
+ export function probeSocket(sockPath, { slug, q = 'what did we decide', timeoutMs = 3000 } = {}) {
239
+ return new Promise((resolve) => {
240
+ if (!fs.existsSync(sockPath)) return resolve({ ok: false, reason: 'no socket' });
241
+ const started = process.hrtime.bigint();
242
+ const c = net.createConnection(sockPath);
243
+ /** @param {ProbeResult} v */
244
+ const done = (v) => {
245
+ try {
246
+ c.destroy();
247
+ } catch {
248
+ /* already gone */
249
+ }
250
+ resolve(v);
251
+ };
252
+ const timer = setTimeout(
253
+ () => done({ ok: false, reason: `no answer in ${timeoutMs}ms` }),
254
+ timeoutMs,
255
+ );
256
+ let buf = '';
257
+ c.on('connect', () => c.write(JSON.stringify({ q, k: 5, slug }) + '\n'));
258
+ c.on('data', (d) => {
259
+ buf += d;
260
+ });
261
+ c.on('end', () => {
262
+ clearTimeout(timer);
263
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
264
+ /** @type {number|null} */
265
+ let hits = null;
266
+ try {
267
+ hits = JSON.parse(buf)?.results?.length ?? null;
268
+ } catch {
269
+ /* a reply we cannot parse is still a timing */
270
+ }
271
+ done({ ok: true, ms, hits });
272
+ });
273
+ c.on('error', (e) => {
274
+ clearTimeout(timer);
275
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code;
276
+ done({
277
+ ok: false,
278
+ reason: code === 'ECONNREFUSED' ? 'socket file is orphaned' : (code ?? 'connection failed'),
279
+ });
280
+ });
281
+ });
282
+ }
283
+
284
+ // `^(?=.)` and not `^`: indenting a blank line leaves trailing whitespace behind.
285
+ /** @param {string} title @param {string} body @returns {string} */
286
+ const section = (title, body) => `\n${title}\n${body.replace(/^(?=.)/gm, ' ')}\n`;
287
+
288
+ /**
289
+ * The whole report, as one string.
290
+ *
291
+ * `activeModel` and `activeSlug` are what THIS project resolves to; everything else is
292
+ * machine-wide on purpose — the cost being diagnosed is never confined to one repo.
293
+ *
294
+ * @param {ReportOptions} options
295
+ * @returns {Promise<string>}
296
+ */
297
+ export async function report(
298
+ {
299
+ state,
300
+ activeModel,
301
+ activeSlug,
302
+ modelKeys = [],
303
+ counts,
304
+ ps = readPs(),
305
+ } = /** @type {ReportOptions} */ ({}),
306
+ ) {
307
+ /** @type {string[]} */
308
+ const out = [];
309
+
310
+ const servers = parseServers(ps);
311
+ if (servers.length === 0) {
312
+ out.push(section('search servers', 'none running — the next recall spawns one (~1.5s)'));
313
+ } else {
314
+ out.push(
315
+ section(
316
+ 'search servers',
317
+ table(
318
+ ['pid', 'rss', 'uptime', 'state'],
319
+ servers.map((s) => [s.pid, formatBytes(s.rss), s.elapsed, modelState(s.rss)]),
320
+ ) +
321
+ (servers.length > 1
322
+ ? `\n\n${servers.length} servers are alive. One per MODEL is the design; more than that is` +
323
+ ' the 16 GB failure mode — each holds its own copy of the weights.'
324
+ : ''),
325
+ ),
326
+ );
327
+ }
328
+
329
+ // A probe is a REAL query: the server embeds it, which reloads the ~1.3 GB model if modelIdleMs
330
+ // had unloaded it, and every connection resets the idle timers. So it is only sent to a server
331
+ // that is already holding the model — measuring the unloaded state would destroy the state being
332
+ // measured, and hand back a first-query time that is really a model load.
333
+ const sock = path.join(state, 'run', `search-${activeModel}.sock`);
334
+ // `every`, not `some`: one server per MODEL, and `ps` cannot say which pid serves which, because
335
+ // the model comes from env/config and never reaches the command line. `some` would probe whenever
336
+ // ANY server were warm — including when the warm one is another model's and the socket below
337
+ // points at a cold one, which is the reload this gate exists to avoid. Unknown means do not
338
+ // touch. The length guard is not decoration: every([]) is true.
339
+ const holding = servers.length > 0 && servers.every((s) => s.rss >= MODEL_RSS_THRESHOLD);
340
+ /** @type {ProbeResult} */
341
+ const first = holding
342
+ ? await probeSocket(sock, { slug: activeSlug })
343
+ : {
344
+ ok: false,
345
+ reason: servers.length
346
+ ? 'a server on this machine has its model unloaded — probing could reload it'
347
+ : 'no server running',
348
+ };
349
+ const second = first.ok ? await probeSocket(sock, { slug: activeSlug }) : null;
350
+ out.push(
351
+ section(
352
+ 'recall round trip',
353
+ first.ok
354
+ ? `${first.ms.toFixed(0)} ms first query, ` +
355
+ // The second probe can fail on its own: the server may have exited, or evicted the
356
+ // socket, between the two. Saying so beats a stack trace where a line belongs.
357
+ (second?.ok
358
+ ? `${second.ms.toFixed(0)} ms second `
359
+ : `second not measured: ${second?.reason ?? 'no answer'} `) +
360
+ `(${first.hits ?? '?'} hits, slug ${activeSlug})\n` +
361
+ 'A first query far above the second means the index for this slug was loaded on demand.'
362
+ : `not measured: ${first.reason}\n` +
363
+ 'Nothing here starts a server or reloads a model. Run a prompt with recall armed to ' +
364
+ 'warm one, then re-run.',
365
+ ),
366
+ );
367
+
368
+ const rows = indexStats(path.join(state, 'db'), modelKeys, counts);
369
+ out.push(
370
+ section(
371
+ 'indexes',
372
+ rows.length === 0
373
+ ? 'none'
374
+ : table(
375
+ ['slug', 'model', 'size', 'chunks', 'notes', 'last indexed'],
376
+ rows.map((r) => [
377
+ r.slug + (r.slug === activeSlug ? ' *' : ''),
378
+ r.model + (r.model === activeModel ? ' *' : ''),
379
+ formatBytes(r.bytes),
380
+ r.chunks ?? 'unreadable',
381
+ r.notes ?? '-',
382
+ r.mtime ? r.mtime.toISOString().slice(0, 16).replace('T', ' ') : '-',
383
+ ]),
384
+ ) +
385
+ '\n\n* = this project / the active model. An index on another model is dead weight:' +
386
+ '\n every mode except --index refuses a model change. Delete it or re-index.',
387
+ ),
388
+ );
389
+
390
+ const dirs = ['db', 'models', 'logs', 'run', 'eval', 'cache'];
391
+ const usage = dirs.map(
392
+ (d) => /** @type {[string, DirUsage]} */ ([d, dirUsage(path.join(state, d))]),
393
+ );
394
+ const total = usage.reduce((n, [, u]) => n + u.bytes, 0);
395
+ out.push(
396
+ section(
397
+ `disk — ${state}`,
398
+ table(
399
+ ['dir', 'size', 'files'],
400
+ usage
401
+ .map(([d, u]) => [
402
+ d + '/',
403
+ u.missing ? '-' : formatBytes(u.bytes),
404
+ u.missing ? '-' : u.files,
405
+ ])
406
+ .concat([['total', formatBytes(total), '']]),
407
+ ),
408
+ ),
409
+ );
410
+
411
+ return out.join('');
412
+ }
413
+
414
+ /**
415
+ * `ps` for every process on the machine. Failure is an empty listing, never a throw.
416
+ *
417
+ * Exported for one reason: a test runs the REAL `ps` on whatever platform it is on and checks that
418
+ * parseServers can find THIS process in the output. `-Ao pid=,rss=,etime=,command=` is POSIX, but a
419
+ * flag this platform did not like would not error here — it would return rows nothing matches, and
420
+ * the report would say "none running" with a server up. macOS (BSD ps) is covered by running it;
421
+ * that test is what covers the ubuntu CI runners.
422
+ *
423
+ * @returns {string}
424
+ */
425
+ export function readPs() {
426
+ try {
427
+ return execFileSync('ps', ['-Ao', 'pid=,rss=,etime=,command='], {
428
+ encoding: 'utf8',
429
+ maxBuffer: 8 * 1024 * 1024,
430
+ });
431
+ } catch {
432
+ return '';
433
+ }
434
+ }