@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,52 @@
1
+ #!/usr/bin/env node
2
+ // PostToolUse entry: warn (never block) when a written vault note breaks the conventions.
3
+ //
4
+ // Thin on purpose: stdin, file path, stdout. Logic and tests live in lib/validate-note.mjs.
5
+ // hooks.json points at this path, so it is a contract — keep it.
6
+ import { readStdin, payload, hookCwd, logHook, standDown, harness } from './lib/hook-io.mjs';
7
+ import { report, patchFiles } from './lib/validate-note.mjs';
8
+
9
+ // readStdin() and not `new Response(process.stdin)`. This is the hottest hook in the system — it
10
+ // runs on every Write/Edit — and the web-streams path cost it ~18 ms of runtime bootstrap before
11
+ // it had even looked at the payload, against ~0.5 ms for one readFileSync(0). Measured
12
+ // 2026-08-20, docs/decisions/2026-08-20-hook-startup-cost.md.
13
+ const j = payload(readStdin());
14
+ if (standDown('validate-note', j)) process.exit(0);
15
+ const direct = String(j?.tool_input?.file_path || j?.tool_input?.path || '');
16
+ const files = direct ? [direct] : patchFiles(j?.tool_input?.command, hookCwd(j));
17
+
18
+ // A hook must never fail a write.
19
+ /** @type {import('./lib/hook-io.mjs').HookOutcome} */
20
+ let outcome = 'ran';
21
+ /** @type {string | undefined} */
22
+ let reason = files.length ? undefined : 'no file path in payload';
23
+ if (files.length) {
24
+ try {
25
+ const text = files.map(report).filter(Boolean).join('\n');
26
+ // Codex CLI drops plain PostToolUse stdout; only this shape reaches the model.
27
+ if (text)
28
+ console.log(
29
+ harness() === 'codex'
30
+ ? JSON.stringify({
31
+ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: text },
32
+ })
33
+ : text,
34
+ );
35
+ reason = text ? 'warned' : 'clean';
36
+ } catch (e) {
37
+ outcome = 'error';
38
+ reason = String(/** @type {Error} */ (e)?.message ?? e);
39
+ }
40
+ }
41
+
42
+ // The hottest hook in the system — one line per Write/Edit, so the log grows fastest here. That is
43
+ // also why it is the one whose duration is worth watching: the same ~18 ms that mattered enough to
44
+ // change how stdin is read is a fifth of this hook's budget.
45
+ logHook({
46
+ hook: 'validate-note',
47
+ event: String(j.hook_event_name ?? ''),
48
+ cwd: hookCwd(j),
49
+ session: /** @type {string|undefined} */ (j.session_id),
50
+ outcome,
51
+ reason,
52
+ });
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env bash
2
+ # Enforce: every project's auto-memory dir lives in the Obsidian vault (per-project subfolder),
3
+ # and the global ~/.claude/CLAUDE.md lives there too. Idempotent; safe to run every SessionStart.
4
+ # ponytail: only moves regular files when repointing — memory dirs hold .md files, not subdirs.
5
+ set -euo pipefail
6
+
7
+ # A headless child run has a $TMPDIR cwd; syncing it makes vault folders for no project (#200).
8
+ # Same two variables as isChildRun() in lib/hook-io.mjs.
9
+ [ -n "${CLAUDE_DISTILL_CHILD:-}${CBM_GRAPHGEN_CHILD:-}" ] && exit 0
10
+
11
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
12
+ . "$HERE/lib/vault-env.sh"
13
+ VAULT=$(resolve_vault)
14
+
15
+ # Breadcrumb so /memory:* commands can find the plugin. ${CLAUDE_PLUGIN_ROOT} is only
16
+ # guaranteed inside hooks.json command strings; a command body running in the Bash tool
17
+ # may not have it, and inside ctx_execute it is context-mode's root. This file is the
18
+ # fallback, rewritten every session so a /plugin update to a new version dir cannot leave it
19
+ # stale.
20
+ MEM_HOME=$(memory_home); mkdir -p "$MEM_HOME"
21
+ printf '%s' "$(cd "$HERE/.." && pwd)" > "$MEM_HOME/plugin-root"
22
+
23
+ # One-time migration off the two marker files that 0.1.1/0.1.2 briefly used, before
24
+ # settling on one config.json like every other plugin. Runs first in the session, so
25
+ # later hooks read the merged result.
26
+ if [ ! -f "$MEM_HOME/config.json" ] && { [ -f "$MEM_HOME/vault" ] || [ -f "$MEM_HOME/recall-enabled" ]; }; then
27
+ _mv=$(head -n1 "$MEM_HOME/vault" 2>/dev/null | tr -d '\r\n')
28
+ _mr=false; [ -f "$MEM_HOME/recall-enabled" ] && _mr=true
29
+ {
30
+ printf '{\n'
31
+ [ -n "$_mv" ] && printf ' "vault": "%s",\n' "$_mv"
32
+ printf ' "recall": %s\n}\n' "$_mr"
33
+ } > "$MEM_HOME/config.json"
34
+ rm -f "$MEM_HOME/vault" "$MEM_HOME/recall-enabled"
35
+ fi
36
+
37
+ cwd=$(cat | jq -r '.cwd // empty' 2>/dev/null || true)
38
+ [ -z "${cwd:-}" ] && cwd="$PWD"
39
+
40
+ # Three different names, deliberately:
41
+ # slug = legacy cwd slug : the pre-2026-08-08 vault folder name; keeps `_`.
42
+ # key = git remote ident : the vault folder, stable across machines and checkout paths.
43
+ # ccp = Claude Code's ~/.claude/projects/<ccp>/ name; `_` becomes `-` too (#199).
44
+ # One load, in THIS shell: the accessors below run in $(...) subshells, where a load would not
45
+ # survive. cwd comes from the hook payload and is not necessarily $PWD.
46
+ _memory_env_load "$cwd"
47
+ slug=$(legacy_key "$cwd")
48
+ key=$(project_key "$cwd")
49
+
50
+ mem="$HOME/.claude/projects/$(claude_projects_key "$cwd")/memory"
51
+ # key==slug: git gave no answer. Keep the Memory/<key> the link already names rather than fork it (#140).
52
+ if [ "$key" = "$slug" ] && [ -L "$mem" ]; then
53
+ linked=$(readlink "$mem"); linked=${linked%/}
54
+ [ "$(basename "$(dirname "$linked")")" = Memory ] && key=$(basename "$linked")
55
+ fi
56
+ dest="$VAULT/Memory/$key"
57
+
58
+ # One-time migration off the old cwd-slug vault naming (pre-2026-08-08). Only moves
59
+ # when the destination is free — never merges two folders behind your back.
60
+ if [ "$slug" != "$key" ]; then
61
+ for layer in Memory Logs Insights Graph; do
62
+ old="$VAULT/$layer/$slug"
63
+ new="$VAULT/$layer/$key"
64
+ if [ -d "$old" ] && [ ! -e "$new" ]; then
65
+ mkdir -p "$(dirname "$new")"
66
+ mv "$old" "$new"
67
+ fi
68
+ done
69
+ fi
70
+
71
+ # Per-project vault subfolders for every memory layer (idempotent).
72
+ mkdir -p "$dest" \
73
+ "$VAULT/Logs/$key" \
74
+ "$VAULT/Insights/$key/Patterns" \
75
+ "$VAULT/Insights/$key/Mistakes" \
76
+ "$VAULT/Insights/$key/Decisions" \
77
+ "$VAULT/Graph/$key" \
78
+ "$VAULT/permanent"
79
+
80
+ if [ -L "$mem" ]; then
81
+ # already a symlink — repoint if it targets the wrong place.
82
+ cur=$(readlink "$mem")
83
+ if [ "$cur" != "$dest" ]; then
84
+ # COPY, never move. The old target is a populated vault; $dest may live under a
85
+ # completely different root (e.g. someone testing with CLAUDE_VAULT=/tmp/...).
86
+ # Moving there and then discarding that root destroys L1 memory — it did exactly
87
+ # that on 2026-08-08, costing 24 notes that only a backup got back. A stray
88
+ # duplicate is recoverable; a move is not.
89
+ [ -d "$cur" ] && find "$cur" -maxdepth 1 -type f -exec cp -n {} "$dest"/ \;
90
+ rm "$mem"; ln -s "$dest" "$mem"
91
+ fi
92
+ elif [ -d "$mem" ]; then
93
+ # real dir Claude already created — migrate contents, replace with symlink
94
+ find "$mem" -maxdepth 1 -type f -exec mv -n {} "$dest"/ \;
95
+ rmdir "$mem" 2>/dev/null || rm -rf "$mem"
96
+ ln -s "$dest" "$mem"
97
+ else
98
+ mkdir -p "$(dirname "$mem")"
99
+ ln -s "$dest" "$mem"
100
+ fi
101
+
102
+ # --- Config lives in git (~/.claude), NOT in the vault -------------------------
103
+ # Direction was inverted 2026-08-08: ~/.claude is a git repo (github spike1292/claude),
104
+ # so committing CLAUDE.md and commands/ as symlinks-into-the-vault shipped dangling
105
+ # links to every clone. Real files now live here; the vault gets a link back.
106
+ #
107
+ # Symlink rule learned the hard way: a link *into* the vault is fine (the memory-dir
108
+ # link above), but a link *inside* the vault is not — Synology Drive silently replaces
109
+ # directory symlinks with empty dirs. File symlinks survive. So CLAUDE.md gets a vault
110
+ # link (for Obsidian) and commands/ does not.
111
+
112
+ # CLAUDE.md: real file in the repo; migrate back if an old-layout symlink is found.
113
+ gc="$HOME/.claude/CLAUDE.md"
114
+ if [ -L "$gc" ]; then
115
+ tgt=$(readlink "$gc")
116
+ if [ -f "$tgt" ]; then rm "$gc"; cp "$tgt" "$gc"; fi # vault copy -> real repo file
117
+ fi
118
+ # Vault-side convenience link (recreate if Synology clobbered or dropped it).
119
+ if [ -f "$gc" ] && [ "$(readlink "$VAULT/CLAUDE.md" 2>/dev/null)" != "$gc" ]; then
120
+ [ -d "$VAULT/CLAUDE.md" ] && rmdir "$VAULT/CLAUDE.md" 2>/dev/null || true
121
+ [ -f "$VAULT/CLAUDE.md" ] && [ ! -L "$VAULT/CLAUDE.md" ] && mv -n "$VAULT/CLAUDE.md" "$VAULT/CLAUDE.md.bak" || true
122
+ rm -f "$VAULT/CLAUDE.md"; ln -s "$gc" "$VAULT/CLAUDE.md"
123
+ fi
124
+
125
+ # Drop the empty stub Synology leaves behind. The commands themselves ship inside this
126
+ # plugin now, so there is nothing in ~/.claude/commands/memory left to migrate.
127
+ rmdir "$VAULT/Commands/memory" 2>/dev/null || true
128
+ rmdir "$VAULT/Commands" 2>/dev/null || true
129
+
130
+ # --- standing retrieval rules --------------------------------------------------
131
+ # A plugin cannot append to CLAUDE.md, and these rules change behaviour in the moment
132
+ # rather than when a note is written — so they go in the session context, not in the on-demand
133
+ # /memory:protocol skill. Kept to ~15 lines: this is paid every session.
134
+ cat <<CTX
135
+
136
+ # Memory (plugin: $(cd "$HERE/.." && pwd))
137
+
138
+ Layers in the vault: L1 facts \`Memory/$key/\` · L2 logs \`Logs/$key/\` · L3 lessons
139
+ \`Insights/$key/{Patterns,Mistakes,Decisions}/\` · L4 graph \`Graph/$key/\` · cross-project \`permanent/\`.
140
+
141
+ **Retrieval — \`$(cd "$HERE/.." && pwd)/scripts/memory-semantic.mjs --query "..." [-k 5]\` is the tool.**
142
+ It runs vector + keyword arms and rank-fuses them, so it wins on described-not-named questions AND
143
+ on identifiers. Local embeddings, so private notes never leave the machine.
144
+
145
+ **Expand the query into domain vocabulary first — the single biggest recall lever.** The lexical
146
+ arm is keyword-only: "firewall" never matches \`WAF\`, "short outage" never matches \`cutover\`, and
147
+ generic words are weighted to nothing. Do not search the user's phrasing verbatim; restate it as
148
+ the terms the answer would be written in, and search both.
149
+
150
+ Writing or auditing a note? Load the \`/memory:protocol\` skill first — filename/frontmatter rules,
151
+ per-claim recency and supersession, aliases, and when knowledge graduates to \`permanent/\`.
152
+ CTX
153
+
154
+ exit 0
package/omp/index.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from '../hooks/lib/omp.mjs';
@@ -0,0 +1 @@
1
+ export { default } from '../hooks/lib/opencode.mjs';
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@spike1292/claude-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.14.0",
4
+ "description": "Layered memory for Claude Code and any agent: hybrid semantic + keyword search over a Markdown vault, local embeddings. CLI: claude-memory",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/spike1292/claude-memory.git"
10
+ },
11
+ "homepage": "https://github.com/spike1292/claude-memory#readme",
12
+ "bin": {
13
+ "claude-memory": "scripts/claude-memory.mjs"
14
+ },
15
+ "files": [
16
+ "hooks/**/*.mjs",
17
+ "hooks/**/*.sh",
18
+ "hooks/hooks.json",
19
+ "omp/index.js",
20
+ "opencode/index.js",
21
+ "scripts/**/*.mjs",
22
+ "scripts/**/*.sh",
23
+ "stubs/*/index.mjs",
24
+ "stubs/*/package.json",
25
+ "!**/*.test.mjs",
26
+ "!scripts/{,lib/}{bench-hooks,prose-guard,review-prompt}.mjs",
27
+ "!scripts/release.sh"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "engines": {
33
+ "node": ">=22.5"
34
+ },
35
+ "dependencies": {
36
+ "@huggingface/transformers": "4.2.0"
37
+ },
38
+ "omp": {
39
+ "extensions": [
40
+ "./omp/index.js"
41
+ ]
42
+ },
43
+ "allowScripts": {
44
+ "onnxruntime-node@1.24.3": true
45
+ },
46
+ "scripts": {
47
+ "postinstall": "node scripts/slim-install.mjs",
48
+ "format": "npx --yes prettier@3.6.2 --write .",
49
+ "format:check": "npx --yes prettier@3.6.2 --check .",
50
+ "prose": "node scripts/prose-guard.mjs",
51
+ "typecheck": "npx --yes -p typescript@7.0.2 tsc -p tsconfig.json"
52
+ }
53
+ }
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ // The `claude-memory` command (npm bin). Usage: claude-memory --help
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { constants } from 'node:os';
6
+ import { spawnSync } from 'node:child_process';
7
+ import * as paths from '../hooks/lib/paths.mjs';
8
+ import { resolve, versionWarning } from './lib/claude-memory.mjs';
9
+
10
+ const version = JSON.parse(
11
+ fs.readFileSync(path.join(paths.pluginRoot, 'package.json'), 'utf8'),
12
+ ).version;
13
+ const argv = process.argv.slice(2);
14
+ const r = resolve(argv, {
15
+ scriptsDir: paths.scriptsDir,
16
+ node: process.execPath,
17
+ version,
18
+ });
19
+ if ('print' in r) {
20
+ (r.code ? process.stderr : process.stdout).write(r.print + '\n');
21
+ process.exitCode = r.code;
22
+ } else {
23
+ const dryPrune = argv[0] === 'prune' && argv.includes('--dry-run');
24
+ const warn = dryPrune ? null : versionWarning(paths.memoryHome(), version);
25
+ if (warn) process.stderr.write(warn + '\n');
26
+ const child = spawnSync(r.cmd, r.args, { stdio: 'inherit' });
27
+ if (child.error) {
28
+ process.stderr.write(`claude-memory: ${child.error.message}\n`);
29
+ }
30
+ process.exitCode = child.signal ? 128 + constants.signals[child.signal] : (child.status ?? 1);
31
+ }
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ // CLI entry for the /memory:doctor --perf, --stats and --hooks reports. Owns argv, the database
3
+ // handles and stdout; the logic is in scripts/lib/doctor-perf.mjs, scripts/lib/recall-stats.mjs and
4
+ // scripts/lib/hook-stats.mjs.
5
+ //
6
+ // `--stats` is the read side of the recall log: what recall decided, how often it abstained and
7
+ // which notes it never surfaced. `--hooks` is the read side of the hook log: what every hook did,
8
+ // how long it took, and how close it ran to the timeout the manifest declares for it. Each is a
9
+ // separate flag rather than more of `--perf` because each answers a different question — "is this
10
+ // helping" and "is this alive" rather than "why is this slow". All three are equally read-only.
11
+ import { hooksDir, memoryHome, projectKey } from '../hooks/lib/paths.mjs';
12
+ import { activeModel } from './lib/model-default.mjs';
13
+ import { MODELS } from './lib/models.mjs';
14
+ import { report } from './lib/doctor-perf.mjs';
15
+ import { report as recallReport } from './lib/recall-stats.mjs';
16
+ import { report as hookReport } from './lib/hook-stats.mjs';
17
+ import { DatabaseSync } from 'node:sqlite';
18
+ import path from 'node:path';
19
+
20
+ // The entry owns the database handle; lib/ takes the numbers as values. Read-only, and null on
21
+ // anything unreadable so the report can say so rather than drop the row.
22
+ /** @type {import('./lib/doctor-perf.mjs').CountsReader} */
23
+ const counts = (file) => {
24
+ try {
25
+ const db = new DatabaseSync(file, { readOnly: true });
26
+ const r = {
27
+ chunks: /** @type {{ c: number }} */ (db.prepare('select count(*) c from chunks').get()).c,
28
+ notes: /** @type {{ c: number }} */ (
29
+ db.prepare('select count(distinct file) c from chunks').get()
30
+ ).c,
31
+ };
32
+ db.close();
33
+ return r;
34
+ } catch {
35
+ return null;
36
+ }
37
+ };
38
+
39
+ // The note set of THIS project's index, for the never-injected list. A missing or unreadable db is
40
+ // null — that one line then reports "not measured" and the rest of the report stands.
41
+ /** @param {string} file @returns {string[] | null} */
42
+ const indexNotes = (file) => {
43
+ try {
44
+ const db = new DatabaseSync(file, { readOnly: true });
45
+ const rows = /** @type {{ note: string }[]} */ (
46
+ /** @type {unknown} */ (db.prepare('select distinct note from chunks').all())
47
+ );
48
+ db.close();
49
+ return rows.map((r) => r.note);
50
+ } catch {
51
+ return null;
52
+ }
53
+ };
54
+
55
+ // argv is positional-then-flags: `doctor-perf.mjs [cwd] [--stats[=days]] [--hooks[=days]]`.
56
+ // Anything else is ignored rather than an error — this is invoked from a report that must always
57
+ // exit 0.
58
+ const args = process.argv.slice(2);
59
+ const statsArg = args.find((a) => a === '--stats' || a.startsWith('--stats='));
60
+ const hooksArg = args.find((a) => a === '--hooks' || a.startsWith('--hooks='));
61
+ const cwd = args.find((a) => !a.startsWith('--')) || process.cwd();
62
+ /** @param {string} [arg] @returns {number | undefined} */
63
+ const windowOf = (arg) => {
64
+ const n = Number(arg?.split('=')[1]);
65
+ return Number.isFinite(n) && n > 0 ? n : undefined;
66
+ };
67
+
68
+ // `null` rather than a placeholder when the key does not resolve: `--stats` FILTERS on this, and a
69
+ // slug no line can match would empty the whole report behind a message that reads like a bug. The
70
+ // machine-wide view is the honest answer there, and render() says which one it is showing.
71
+ /** @type {string | null} */
72
+ let slug = null;
73
+ try {
74
+ slug = projectKey(cwd);
75
+ } catch {
76
+ /* reported as (unresolved) in the perf report, and as machine-wide in --stats */
77
+ }
78
+
79
+ const state = memoryHome();
80
+ const model = activeModel();
81
+
82
+ // ADDITIVE, not a ternary. `commands/doctor.md` tells the model the flags may be combined, and
83
+ // through doctor.sh they are — it invokes this script once per flag. Passed together to the entry
84
+ // itself, a ternary chain silently printed one section and dropped the rest, so the doc was true
85
+ // only by accident of which wrapper was used.
86
+ if (hooksArg)
87
+ process.stdout.write(
88
+ hookReport({
89
+ logDir: path.join(state, 'logs'),
90
+ // The manifest is the ONLY source of the timeouts. Read at run time and never copied into
91
+ // a log line or into the reader, because a duplicated timeout drifts in silence.
92
+ manifest: path.join(hooksDir, 'hooks.json'),
93
+ days: windowOf(hooksArg),
94
+ slug,
95
+ }),
96
+ );
97
+
98
+ if (statsArg)
99
+ process.stdout.write(
100
+ recallReport({
101
+ logDir: path.join(state, 'logs'),
102
+ days: windowOf(statsArg),
103
+ indexNotes: slug ? indexNotes(path.join(state, 'db', `semantic-${slug}-${model}.db`)) : null,
104
+ // The logs are machine-wide and the index is not, so the report is scoped to THIS project —
105
+ // otherwise one project's never-injected notes would be measured against every project's
106
+ // retrievals. doctor.sh runs this from $PWD for exactly that reason.
107
+ slug,
108
+ }),
109
+ );
110
+
111
+ // The perf report is the DEFAULT, so it prints when no flag selected something else.
112
+ if (!hooksArg && !statsArg)
113
+ process.stdout.write(
114
+ await report({
115
+ state,
116
+ activeModel: model,
117
+ activeSlug: slug ?? '(unresolved)',
118
+ modelKeys: Object.keys(MODELS),
119
+ counts,
120
+ }),
121
+ );