@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,218 @@
1
+ #!/usr/bin/env node
2
+ // PostToolUse (Write|Edit|MultiEdit): check a vault note the moment it is written.
3
+ //
4
+ // Every other mechanism in this system runs at SessionStart or during an audit — hours or days
5
+ // after the write, when the author no longer has the context to fix it cheaply. This is the
6
+ // missing enforcement point, borrowed from obsidian-second-brain's validate-ai-first.sh, whose
7
+ // comment says it best: the vault holds its shape because every write is checked, not because a
8
+ // future session remembers all the conventions.
9
+ //
10
+ // WARNS ONLY — never blocks a write, and never exits non-zero. A note half-written is still worth
11
+ // keeping; the point is to tell the author now rather than let an audit find it next week.
12
+ //
13
+ // Ported from validate-note.sh on 2026-08-17: shell forked ~15 processes at 165.9 ms/edit; node
14
+ // runs the claim-level checks in-process (import-safe `memory-audit-checks.mjs`) at 54.0 ms. Full
15
+ // numbers + verification: docs/decisions/2026-08-17-shell-vs-node-hooks.md "validate-note.sh ->
16
+ // validate-note.mjs".
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { vault } from './paths.mjs';
20
+ import { checkFile } from '../../scripts/lib/memory-audit-checks.mjs';
21
+ import { findOrphans, readCorpus } from './memory-link-lint.mjs';
22
+
23
+ /**
24
+ * Frontmatter block: the lines between the opening fence on line 1 and the next `---`.
25
+ *
26
+ * @param {string} raw
27
+ * @returns {string | null}
28
+ */
29
+ export function frontmatter(raw) {
30
+ const lines = raw.split('\n');
31
+ if (lines[0] !== '---') return null; // no fence on line 1
32
+ const end = lines.indexOf('---', 1);
33
+ return lines.slice(1, end === -1 ? undefined : end).join('\n');
34
+ }
35
+
36
+ /**
37
+ * Everything after the closing frontmatter fence — and the WHOLE file when there is no
38
+ * frontmatter, which is what makes the body checks still fire on an unfenced note.
39
+ * Mirrors the awk in the shell version: lines before the first fence are kept too.
40
+ *
41
+ * @param {string} raw
42
+ * @returns {string}
43
+ */
44
+ export function noteBody(raw) {
45
+ /** @type {string[]} */
46
+ const out = [];
47
+ let fences = 0,
48
+ past = false;
49
+ for (const line of raw.split('\n')) {
50
+ if (past) {
51
+ out.push(line);
52
+ continue;
53
+ }
54
+ if (line === '---') {
55
+ fences++;
56
+ if (fences === 2) past = true;
57
+ continue;
58
+ }
59
+ if (fences === 0) out.push(line);
60
+ }
61
+ return out.join('\n').replace(/\n+$/, ''); // $(...) strips trailing newlines
62
+ }
63
+
64
+ /**
65
+ * Is this path a note we check at all? Operating surfaces are not notes.
66
+ *
67
+ * @param {string} file
68
+ * @param {string} vaultRoot
69
+ * @returns {boolean}
70
+ */
71
+ export function isCheckable(file, vaultRoot) {
72
+ if (!file || !file.startsWith(`${vaultRoot}/`)) return false;
73
+ if (!file.endsWith('.md')) return false;
74
+ return !(
75
+ file.endsWith('/REFLECTIONS.md') ||
76
+ file.endsWith('/MEMORY.md') ||
77
+ file.includes('/Logs/') ||
78
+ file.includes('/Graph/')
79
+ );
80
+ }
81
+
82
+ /**
83
+ * The convention warnings for one note. Pure: takes content, returns strings, touches nothing.
84
+ *
85
+ * @param {string} file
86
+ * @param {string} raw
87
+ * @param {string} vaultRoot
88
+ * @returns {string[]}
89
+ */
90
+ export function warnings(file, raw, vaultRoot) {
91
+ const name = path.basename(file, '.md');
92
+ /** @type {string[]} */
93
+ const warn = [];
94
+ const fm = frontmatter(raw);
95
+
96
+ // Frontmatter must open on line 1 and close — a missing fence silently voids every field below it.
97
+ if (fm === null) {
98
+ warn.push('no frontmatter fence on line 1 — every field below it is invisible to the tooling');
99
+ } else {
100
+ if (fm.includes('\t')) warn.push('tab inside frontmatter — YAML needs spaces');
101
+ if (file.startsWith(path.join(vaultRoot, 'Memory') + '/')) {
102
+ const status = fm.match(/^status:[ \t]*["']?([^"'\n]*?)["']?[ \t]*$/m)?.[1];
103
+ if (status !== undefined && status !== 'open' && status !== 'closed') {
104
+ warn.push(
105
+ `status: ${status} — a fork is status: open or closed; anything else is never surfaced`,
106
+ );
107
+ }
108
+ if (
109
+ !new RegExp(
110
+ `^name:[ \\t]*["']?${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']?[ \\t]*$`,
111
+ 'm',
112
+ ).test(fm)
113
+ ) {
114
+ warn.push(
115
+ `frontmatter name: must equal the filename (${name}) or [[wikilinks]] will not resolve`,
116
+ );
117
+ }
118
+ if (!/^[ \t]*confidence:[ \t]*(high|medium|low)/m.test(fm)) {
119
+ warn.push('no confidence: — /memory:health cannot pick a winner when two notes disagree');
120
+ }
121
+ }
122
+ }
123
+
124
+ const body = noteBody(raw);
125
+
126
+ // Retrievability: the alias line is the paraphrase bridge for keyword search. Measured
127
+ // 2026-08-14 — authored paraphrase questions reach the right note only ~46% of the time.
128
+ if (!body.includes('_Also asked as:')) {
129
+ warn.push(
130
+ "no '_Also asked as:' line — add 2-3 paraphrases in an OUTSIDER's words, not the note's own jargon",
131
+ );
132
+ }
133
+
134
+ // A reversal announced only in prose is invisible to every check (see memory-audit-checks.mjs).
135
+ if (
136
+ /(⚠ *)?\**(SUPERSEDED|superseded by|no longer true)/i.test(body) &&
137
+ !/superseded +[0-9]{4}-[0-9]{2}-[0-9]{2} +by +\[\[/i.test(body)
138
+ ) {
139
+ warn.push('says superseded in prose — mark the claim: (superseded YYYY-MM-DD by [[note]])');
140
+ }
141
+ return warn;
142
+ }
143
+
144
+ // Suffix-path detection is deliberately NOT here. It needs the repo's full file list to decide, and
145
+ // an early version of this block silently never fired — a check that does not run is worse than no
146
+ // check, because it reads as coverage. memory-audit-checks.mjs does it vault-wide and is tested.
147
+
148
+ /**
149
+ * The convention report for one written file, or '' when it is clean or not a checkable note.
150
+ *
151
+ * Returns text rather than printing, so it is testable without stdin or a subprocess.
152
+ *
153
+ * @param {string} file
154
+ * @returns {string}
155
+ */
156
+ export function report(file) {
157
+ let vaultRoot;
158
+ try {
159
+ // Auto memory writes through ~/.claude/projects/<slug>/memory, a symlink into the vault (#144).
160
+ vaultRoot = fs.realpathSync(vault());
161
+ file = fs.realpathSync(file);
162
+ } catch {
163
+ return '';
164
+ }
165
+ if (!isCheckable(file, vaultRoot)) return '';
166
+ let raw;
167
+ try {
168
+ if (!fs.statSync(file).isFile()) return '';
169
+ raw = fs.readFileSync(file, 'utf8');
170
+ } catch {
171
+ return '';
172
+ }
173
+
174
+ const warn = warnings(file, raw, vaultRoot);
175
+
176
+ const mem = path.dirname(file);
177
+ if (path.dirname(mem) === path.join(vaultRoot, 'Memory')) {
178
+ const name = path.basename(file, '.md');
179
+ const corpus = readCorpus(mem, path.join(vaultRoot, 'Insights', path.basename(mem)));
180
+ if (findOrphans(mem, [name], corpus).length) {
181
+ warn.push(
182
+ `no sibling note links [[${name}]] — the note graph cannot reach it; link it from a related note`,
183
+ );
184
+ }
185
+ }
186
+
187
+ // Claim-level checks (CLAIM-1 metric provenance, FRESH-1 staleness, prose-only supersession) run
188
+ // from the tested predicates rather than being re-implemented here. This is the write-time half:
189
+ // an inflated recall figure once reached a public README *between* two audits.
190
+ /** @type {string[]} */
191
+ let claims = [];
192
+ try {
193
+ claims = checkFile(file);
194
+ } catch {
195
+ /* best effort — never break a write */
196
+ }
197
+
198
+ if (!warn.length && !claims.length) return '';
199
+ const out = [`note conventions — ${path.basename(file, '.md')}`];
200
+ for (const w of warn) out.push(` · ${w}`);
201
+ if (claims.length) out.push(claims.join('\n'));
202
+ return out.join('\n');
203
+ }
204
+
205
+ /**
206
+ * The files a Codex CLI `apply_patch` wrote, resolved against the session cwd. Deleted files are
207
+ * skipped: there is nothing left to check.
208
+ *
209
+ * @param {unknown} patch
210
+ * @param {string} cwd
211
+ * @returns {string[]}
212
+ */
213
+ export function patchFiles(patch, cwd) {
214
+ if (typeof patch !== 'string') return [];
215
+ return [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm)].map((m) =>
216
+ path.resolve(cwd, m[1].trim()),
217
+ );
218
+ }
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bash
2
+ # Shared vault resolution, project key, and state dir, for the two shell files that remain:
3
+ # hooks/vault-memory-sync.sh and scripts/doctor.sh.
4
+ #
5
+ # . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/vault-env.sh"
6
+ # VAULT=$(resolve_vault); key=$(project_key "$cwd"); HOME_DIR=$(memory_home)
7
+ #
8
+ # THIS FILE NO LONGER RESOLVES ANYTHING. It asks Node and caches the answer.
9
+ #
10
+ # Until 2026-08-18 it was the source of truth and hooks/lib/paths.mjs mirrored it — two
11
+ # implementations of one set of rules, kept in step by a comment and by paths.mjs forking bash so
12
+ # that project_key at least had a single implementation. That bargain cost a fork on the Node side
13
+ # and ~110 lines of duplicated resolution on this one. Node resolves now; this asks.
14
+ #
15
+ # One `node` call answers everything below, so a caller pays one fork rather than a source plus a
16
+ # jq read plus a git fork. Resolve relative to this file, never to an absolute install path: the
17
+ # plugin runs from a version-pinned cache dir, from a dev checkout, and via symlink.
18
+
19
+ _memory_env_dir="" # which directory the cached answer is for
20
+ MEMORY_ENV_DEGRADED=0 # 1 when Node could not be asked; see the fallback below
21
+
22
+ # Where this file is, resolved once at source time.
23
+ #
24
+ # BASH_SOURCE is bash-only. The two shell files that source this are bash, but
25
+ # every commands/*.md tells the agent to source it too — and an agent's Bash
26
+ # tool may be zsh, where BASH_SOURCE is unset. `dirname ""` is then `.`, the
27
+ # env.mjs path misses, and _memory_env_load falls into DEGRADED: no config.json,
28
+ # so the vault silently becomes ~/Documents/ClaudeVault and the project key
29
+ # becomes a cwd-slug. That is the exact failure mode the vault resolution is
30
+ # built to prevent, arriving through the command surface instead of a hook.
31
+ #
32
+ # ${(%):-%x} is zsh's equivalent, kept inside eval so bash never parses it.
33
+ if [ -n "${BASH_SOURCE[0]:-}" ]; then
34
+ _memory_env_self="${BASH_SOURCE[0]}"
35
+ elif [ -n "${ZSH_VERSION:-}" ]; then
36
+ eval '_memory_env_self="${(%):-%x}"'
37
+ else
38
+ _memory_env_self="$0"
39
+ fi
40
+
41
+ # Ask Node once per directory. Callers use a single cwd each, so this is one fork per script.
42
+ _memory_env_load() {
43
+ _d="${1:-$PWD}"
44
+ [ "${_memory_env_dir:-}" = "$_d" ] && return 0
45
+ _root="$(cd "$(dirname "$_memory_env_self")/../.." && pwd)"
46
+ _entry="$_root/scripts/env.mjs"
47
+
48
+ if command -v node >/dev/null 2>&1 && [ -f "$_entry" ]; then
49
+ if _out=$(node "$_entry" "$_d" 2>/dev/null) && [ -n "$_out" ]; then
50
+ eval "$_out" # values are single-quoted by shellQuote(); safe to eval
51
+ MEMORY_ENV_DEGRADED=0
52
+ _memory_env_dir="$_d"
53
+ return 0
54
+ fi
55
+ fi
56
+
57
+ # DEGRADED: no Node, or it failed. Environment variables and built-in defaults only — no
58
+ # config.json, no git. This is not a second implementation of the rules; it is the minimum that
59
+ # lets /memory:doctor run far enough to report WHY nothing works, which is the one job that
60
+ # cannot be delegated to the runtime being diagnosed.
61
+ MEMORY_ENV_VAULT="${CLAUDE_VAULT:-$HOME/Documents/ClaudeVault}"
62
+ MEMORY_ENV_VAULT_SOURCE="${CLAUDE_VAULT:+CLAUDE_VAULT env}"
63
+ MEMORY_ENV_VAULT_SOURCE="${MEMORY_ENV_VAULT_SOURCE:-built-in default (node unavailable)}"
64
+ MEMORY_ENV_HOME="${CLAUDE_MEMORY_HOME:-$HOME/.claude-memory}"
65
+ # The legacy cwd-slug, deliberately: it is also the pre-migration folder name, so a fallback
66
+ # lands somewhere vault-memory-sync.sh already knows how to migrate rather than on a new name.
67
+ MEMORY_ENV_LEGACY_KEY=$(printf '%s' "$_d" | sed 's#/#-#g')
68
+ MEMORY_ENV_PROJECT_KEY="$MEMORY_ENV_LEGACY_KEY"
69
+ MEMORY_ENV_CLAUDE_PROJECTS_KEY=$(printf '%s' "$_d" | sed 's#[^A-Za-z0-9]#-#g')
70
+ MEMORY_ENV_RECALL=$([ "${MEMORY_RECALL_ENABLED:-}" = "1" ] && printf 1 || printf 0)
71
+ MEMORY_ENV_RECALL_CONFIG=""
72
+ MEMORY_ENV_MODEL=""
73
+ # Left EMPTY on purpose: repeating the 30-day default here would be a second place it
74
+ # lives. A caller prints "?" and the report already says node could not be asked.
75
+ MEMORY_ENV_LOG_RETENTION_DAYS=""
76
+ MEMORY_ENV_DEGRADED=1
77
+ _memory_env_dir="$_d"
78
+ }
79
+
80
+ # --- public interface ---------------------------------------------------------
81
+ # Same names and same output as before the migration, so callers did not change.
82
+
83
+ config_file() { printf '%s' "$(memory_home)/config.json"; }
84
+ log_retention_days() { _memory_env_load "$PWD"; printf '%s' "$MEMORY_ENV_LOG_RETENTION_DAYS"; }
85
+
86
+ resolve_vault() { _memory_env_load "$PWD"; printf '%s' "$MEMORY_ENV_VAULT"; }
87
+ vault_source() { _memory_env_load "$PWD"; printf '%s' "$MEMORY_ENV_VAULT_SOURCE"; }
88
+ memory_home() { _memory_env_load "$PWD"; printf '%s' "$MEMORY_ENV_HOME"; }
89
+ project_key() { _memory_env_load "${1:-$PWD}"; printf '%s' "$MEMORY_ENV_PROJECT_KEY"; }
90
+ legacy_key() { _memory_env_load "${1:-$PWD}"; printf '%s' "$MEMORY_ENV_LEGACY_KEY"; }
91
+ claude_projects_key() { _memory_env_load "${1:-$PWD}"; printf '%s' "$MEMORY_ENV_CLAUDE_PROJECTS_KEY"; }
92
+
93
+ # Off unless explicitly armed: injecting into every prompt changes how every session reads, so it
94
+ # is the user's call, not a default. Exit status, not output — callers use it in `if`.
95
+ recall_enabled() { _memory_env_load "$PWD"; [ "$MEMORY_ENV_RECALL" = "1" ]; }
96
+
97
+ # What config.json itself says, as distinct from the effective value — /memory:doctor tells the
98
+ # two apart so it can warn that an env-only arming does not survive a mid-session write.
99
+ recall_config() { _memory_env_load "$PWD"; printf '%s' "$MEMORY_ENV_RECALL_CONFIG"; }
100
+
101
+ # Load eagerly, in the PARENT shell, at source time.
102
+ #
103
+ # Not an optimisation — a correctness requirement. Every accessor above is called as `$(...)`, which
104
+ # runs in a subshell, so a load performed there sets variables that die with it and the next call
105
+ # forks node again. Loading here means the accessors read variables that are already set, and both
106
+ # callers pay exactly one fork.
107
+ #
108
+ # A caller that needs a DIFFERENT directory (vault-memory-sync.sh takes cwd from the hook payload)
109
+ # must call `_memory_env_load "$that_dir"` itself, in its own shell, before using the accessors.
110
+ _memory_env_load "$PWD"
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart entry: name the L1 notes reachable only from the MOC, and once a day the duplicate pairs.
3
+ //
4
+ // Thin on purpose: stdin, cwd, stdout, and the index handle. Logic and tests live in lib/.
5
+ // hooks.json points at this path, so it is a contract — keep it.
6
+ import { readStdin, payload, hookCwd, logHook, standDown, sessionContext } from './lib/hook-io.mjs';
7
+ import { lint } from './lib/memory-link-lint.mjs';
8
+ import { DatabaseSync } from 'node:sqlite';
9
+ import { dupeReport } from './lib/dupe-report.mjs';
10
+ import { CARD } from '../scripts/lib/lexical.mjs';
11
+
12
+ /** @typedef {import('./lib/dupe-report.mjs').CardRow} CardRow */
13
+ /** @type {import('./lib/dupe-report.mjs').ReadIndex} */
14
+ const readIndex = (dbPath) => {
15
+ const db = new DatabaseSync(dbPath, { readOnly: true });
16
+ try {
17
+ const meta = /** @type {{ value?: string } | undefined} */ (
18
+ db.prepare("SELECT value FROM meta WHERE key = 'model'").get()
19
+ );
20
+ const rows = db
21
+ .prepare('SELECT note, layer, file, vec FROM chunks WHERE heading = ?')
22
+ .all(CARD);
23
+ return { model: meta?.value, rows: /** @type {CardRow[]} */ (/** @type {unknown} */ (rows)) };
24
+ } finally {
25
+ db.close();
26
+ }
27
+ };
28
+
29
+ // readStdin() and not `new Response(process.stdin)` — the web-streams path costs ~18 ms of runtime
30
+ // bootstrap per hook. See docs/decisions/2026-08-20-hook-startup-cost.md.
31
+ const p = payload(readStdin());
32
+ if (standDown('memory-link-lint', p)) process.exit(0);
33
+ const cwd = hookCwd(p);
34
+
35
+ // A SessionStart hook must never break a session.
36
+ /** @type {import('./lib/hook-io.mjs').HookOutcome} */
37
+ let outcome = 'ran';
38
+ /** @type {string | undefined} */
39
+ let reason;
40
+ /** @type {Record<string, number> | undefined} */
41
+ let extra;
42
+ try {
43
+ const text = [lint(cwd), await dupeReport(cwd, readIndex)].filter(Boolean).join('\n\n');
44
+ if (text) console.log(sessionContext(text));
45
+ reason = text ? 'reported' : 'nothing to report';
46
+ // What this hook COSTS the session, in bytes of context window. Omitted rather than logged as 0
47
+ // when it injects nothing, so "injected nothing" and "was not measuring yet" stay distinguishable
48
+ // — a week of older log files sits in the reader's window.
49
+ if (text) extra = { bytes: Buffer.byteLength(text) };
50
+ } catch (e) {
51
+ outcome = 'error';
52
+ reason = String(/** @type {Error} */ (e)?.message ?? e);
53
+ }
54
+
55
+ // This hook is the one whose cost depends on the vault: 74 ms in this repo, 10.9 s on a 49-note
56
+ // project, against a 10 s timeout. Its duration is the reason the log exists.
57
+ logHook({
58
+ hook: 'memory-link-lint',
59
+ event: String(p.hook_event_name ?? ''),
60
+ cwd,
61
+ session: /** @type {string|undefined} */ (p.session_id),
62
+ outcome,
63
+ reason,
64
+ extra,
65
+ });
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env node
2
+ // UserPromptSubmit: inject a small brief of relevant vault notes — or nothing at all.
3
+ //
4
+ // BOUNDED at most MAX_NOTES notes and MAX_CHARS characters. A hint, not a dump.
5
+ // ABSTAINS weak matches inject NOTHING. Silence beats noise: a wrong note costs more attention
6
+ // than no note, and it teaches the reader to ignore the brief.
7
+ // OBSERVABLE every decision — inject or abstain, with the reason — appends one JSONL line, so the
8
+ // abstention rate is measurable later instead of assumed.
9
+ // FAIL-OPEN any error inside the try exits 0 silently. Recall must never break a prompt. The
10
+ // static imports below are the exception and cannot be made to fail open: a missing
11
+ // `node:sqlite` (Node < 22.5, or Bun) or a typo'd module path exits 1 with a stack
12
+ // trace, which hooks.json's trailing `|| exit 0` masks into transcript noise rather
13
+ // than a blocked prompt. Adding an import here adds one more of those.
14
+ //
15
+ // Why this exists: MEMORY.md is auto-loaded in full every session and grows without limit — the
16
+ // system's oldest open gap. Per-prompt retrieval is the alternative to loading everything always.
17
+ //
18
+ // Retrieval is the SAME ranking the CLI and the eval harness use — vector + keyword rank fusion —
19
+ // served by a resident process over a unix socket (~60ms). It used to be keyword-only, because
20
+ // loading model and index per prompt costs ~1540ms warm and ~3100ms cold; that is what the server
21
+ // exists to amortise. If the socket is missing or slow the hook spawns it for next time and answers
22
+ // this prompt from keyword search, so a prompt never waits on infrastructure.
23
+ //
24
+ // This file owns argv/stdin/stdout, the socket and `node:sqlite`, and nothing else. The gates, the
25
+ // ranking, the formatting and the log-record shapes live in hooks/lib/memory-recall.mjs with their
26
+ // tests — `node:sqlite` stays HERE precisely so that module can be imported by a test without one.
27
+ //
28
+ // That twin's own import graph must not reach scripts/lib/memory-semantic.mjs — the guard and the
29
+ // why are at hooks/lib/memory-recall.mjs:1, with docs/architecture.md B1 (~line 432) behind it.
30
+ // Anything that can fail belongs in an `await import()` in the try, like model-default.mjs below.
31
+
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+ import net from 'node:net';
35
+ import { DatabaseSync } from 'node:sqlite';
36
+ import {
37
+ CHILD_RUN,
38
+ appendJsonl,
39
+ detach,
40
+ harness,
41
+ isChildRun,
42
+ logHook,
43
+ setHarness,
44
+ } from './lib/hook-io.mjs';
45
+ import {
46
+ crossProjectRecall,
47
+ fileQuery,
48
+ projectKey,
49
+ stateDir,
50
+ scriptsDir,
51
+ recallEnabled,
52
+ } from './lib/paths.mjs';
53
+ import {
54
+ CARD,
55
+ MAX_NOTES,
56
+ MIN_PROMPT,
57
+ keywordArm,
58
+ recallOutput,
59
+ semanticArm,
60
+ } from './lib/memory-recall.mjs';
61
+
62
+ // `--preview [--cwd d] (--file f | prompt…)`: this same path with argv for the payload — so it
63
+ // cannot drift from the hook — printing the brief, the decision on stderr, and logging nothing.
64
+ const argv = process.argv.slice(2);
65
+ const preview = argv[0] === '--preview';
66
+ /** @param {string} f */
67
+ const opt = (f) => (argv.indexOf(f) > 0 ? argv.splice(argv.indexOf(f), 2)[1] : undefined);
68
+
69
+ // Ships INERT. Injecting into every prompt changes how every session reads, so arming it is the
70
+ // user's call: {"recall": true} in $CLAUDE_MEMORY_HOME/config.json, or MEMORY_RECALL_ENABLED=1.
71
+ if (!preview && !recallEnabled()) process.exit(0);
72
+
73
+ // One line per ARMED invocation, in the `hooks` family, beside the decision line this hook has
74
+ // always written in the `recall` family. Two lines because they answer two questions: the recall
75
+ // line is about retrieval quality, this one is about the hook as a hook — how long the whole
76
+ // process took against its 10 s timeout, and whether it reached a decision at all.
77
+ //
78
+ // Registered on `exit` rather than called at each return, because this file exits from four
79
+ // places and the paths that exit EARLIEST (a prompt below MIN_PROMPT, an unparseable payload) are
80
+ // exactly the ones no decision line covers. A disarmed session writes nothing at all: recall ships
81
+ // inert, and an inert feature must not cost every prompt of every user a file append.
82
+ /** @type {import('./lib/hook-io.mjs').HookOutcome} */
83
+ let outcome = 'ran';
84
+ /** @type {string | undefined} */
85
+ let hookReason;
86
+ /** @type {{ cwd?: string, session?: string, event?: string }} */
87
+ const ctx = {};
88
+ process.on('exit', () =>
89
+ preview
90
+ ? fs.writeSync(2, `${outcome}: ${hookReason ?? ''}\n`)
91
+ : logHook({
92
+ hook: 'memory-recall',
93
+ event: ctx.event ?? '',
94
+ cwd: ctx.cwd,
95
+ session: ctx.session,
96
+ outcome,
97
+ reason: hookReason,
98
+ }),
99
+ );
100
+
101
+ /** @returns {Record<string, any>} */
102
+ function previewPayload() {
103
+ const cwd = path.resolve(opt('--cwd') ?? process.cwd());
104
+ const file = opt('--file');
105
+ return { cwd, file, prompt: file ? fileQuery(file, cwd) : argv.slice(1).join(' ') };
106
+ }
107
+
108
+ try {
109
+ const payload = preview ? previewPayload() : JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
110
+ setHarness(payload);
111
+ const prompt = (payload.prompt || '').trim();
112
+ const cwd = payload.cwd || process.cwd();
113
+ const transformed = typeof payload.transformedPrompt === 'string';
114
+ ctx.cwd = cwd;
115
+ ctx.session = payload.session_id ?? payload.sessionId;
116
+ ctx.event = payload.hook_event_name ?? (transformed ? 'userPromptTransformed' : undefined);
117
+ if (isChildRun()) {
118
+ outcome = 'child-guard';
119
+ hookReason = CHILD_RUN;
120
+ process.exit(0);
121
+ }
122
+ if (harness() === 'copilot' && !transformed) {
123
+ outcome = 'debounced';
124
+ hookReason = 'copilot: recall runs on userPromptTransformed';
125
+ process.exit(0);
126
+ }
127
+ if (prompt.length < MIN_PROMPT && !payload.file) {
128
+ hookReason = 'prompt shorter than MIN_PROMPT';
129
+ process.exit(0);
130
+ }
131
+
132
+ const slug = projectKey(cwd);
133
+ // Indexes are per-model, so the DB name depends on the active model. Recall reads chunk TEXT and
134
+ // never the vectors, but the path must still resolve — and a missing DB exits 0 silently, so a
135
+ // drifted default here would turn recall off with no error. Hence the shared constant.
136
+ const { activeModel } = await import(
137
+ // @ts-expect-error Node accepts a URL specifier for a dynamic import; TypeScript wants a string.
138
+ new URL('../scripts/lib/model-default.mjs', import.meta.url)
139
+ );
140
+ const model = activeModel();
141
+ const dbPath = path.join(stateDir('db'), `semantic-${slug}-${model}.db`);
142
+
143
+ const runDir = stateDir('run');
144
+ // The appender is shared with every other hook (hooks/lib/hook-io.mjs) and stamps `t` and `slug`;
145
+ // everything after them is this record, in this order, unchanged since the log began. It swallows
146
+ // its own errors — logging must never break the prompt either.
147
+ const log = (/** @type {import('./lib/memory-recall.mjs').LogEntry} */ entry) => {
148
+ hookReason = entry.abstained ? `abstained: ${entry.reason ?? ''}`.trim() : 'injected';
149
+ if (!preview)
150
+ appendJsonl('recall', cwd, {
151
+ ...entry,
152
+ // `performance.now()` is measured from process start, NOT from here, and that is the
153
+ // point: a prompt waits for the whole process, so node's own startup and this file's
154
+ // static import graph — ~40 ms of the budget — are inside the number. A clock started
155
+ // at the top of this try would have excluded exactly the part nobody can see. Read it
156
+ // against the 700 ms socket timeout, which it contains rather than sits beside.
157
+ ms: +performance.now().toFixed(1),
158
+ });
159
+ };
160
+
161
+ // The log is defined BEFORE the first exit on purpose. It used to sit after the missing-DB check,
162
+ // so "the index moved and I have been switched off for six hours" and "no relevant notes" looked
163
+ // identical — which is exactly what happened on 2026-08-15 when the DB filename gained a model
164
+ // suffix. Fail-open is right; fail-open AND silent is not.
165
+ const all = crossProjectRecall(slug);
166
+ /** @returns {never} */
167
+ const noIndex = () => {
168
+ log({ abstained: true, reason: 'no index at ' + path.basename(dbPath) });
169
+ // NOT `ran`. This is the 2026-08-15 incident in the comment above — a model suffix appeared in
170
+ // the DB filename and recall was silently off for six hours — and it is exactly what the
171
+ // outcome set is for. As `ran` it would be a healthy column of thousands of invocations.
172
+ outcome = 'noop-missing-dep';
173
+ process.exit(0);
174
+ };
175
+ // A home repo with no notes of its own still reads every other project's through the server.
176
+ if (!all && !fs.existsSync(dbPath)) noIndex();
177
+
178
+ // MRR 0.158 keyword-only vs 0.547 via the resident server — why this hook talks to the socket
179
+ // instead of staying on its own BM25 fallback.
180
+ // Keyed by MODEL alone, not slug+model: CLAUDE.md ~line 204 has the why and the old
181
+ // ~1.3GB-per-repo cost this replaced.
182
+ const sockPath = path.join(runDir, `search-${model}.sock`);
183
+ /** @typedef {{ results?: import('./lib/memory-recall.mjs').ServerHit[] | null } | null} ServerReply */
184
+ /**
185
+ * @param {string} q
186
+ * @returns {Promise<ServerReply>}
187
+ */
188
+ const askServer = (q) =>
189
+ new Promise((resolve) => {
190
+ const done = (/** @type {ServerReply} */ v) => {
191
+ try {
192
+ c.destroy();
193
+ } catch {}
194
+ resolve(v);
195
+ };
196
+ const c = net.createConnection(sockPath);
197
+ const timer = setTimeout(() => done(null), 700);
198
+ let buf = '';
199
+ // Reads only: the keyword fallback below stays on this project's own index.
200
+ c.on('connect', () =>
201
+ c.write(JSON.stringify({ q, k: MAX_NOTES, slug, all: all || undefined }) + '\n'),
202
+ );
203
+ c.on('data', (d) => {
204
+ buf += d;
205
+ });
206
+ c.on('end', () => {
207
+ clearTimeout(timer);
208
+ try {
209
+ resolve(JSON.parse(buf));
210
+ } catch {
211
+ resolve(null);
212
+ }
213
+ });
214
+ c.on('error', () => {
215
+ clearTimeout(timer);
216
+ done(null);
217
+ });
218
+ });
219
+
220
+ const semantic = fs.existsSync(sockPath) ? await askServer(prompt) : null;
221
+ // detach() is the shared contract — detached, stdio ignored, unref'd — and it swallows its own
222
+ // failures, because keyword search still answers this prompt. It is safe above the try only
223
+ // because hook-io.mjs imports nothing that can throw or print at module scope; see the header.
224
+ if (!semantic)
225
+ detach(process.execPath, [path.join(scriptsDir, 'memory-semantic.mjs'), '--serve'], { cwd });
226
+
227
+ const fromServer = semanticArm(semantic?.results);
228
+ if (fromServer) {
229
+ log(fromServer.entry);
230
+ if (fromServer.output) console.log(recallOutput(payload, fromServer.output));
231
+ } else {
232
+ if (!fs.existsSync(dbPath)) noIndex();
233
+ // Opened only once the server has failed to answer, and never closed — process exit collects it.
234
+ const db = new DatabaseSync(dbPath);
235
+ const cards = /** @type {import('./lib/memory-recall.mjs').Card[]} */ (
236
+ /** @type {unknown} */ (
237
+ db.prepare('SELECT note, layer, text FROM chunks WHERE heading = ?').all(CARD)
238
+ )
239
+ );
240
+
241
+ const fromKeyword = keywordArm(cards, prompt);
242
+ log(fromKeyword.entry);
243
+ if (fromKeyword.output) console.log(recallOutput(payload, fromKeyword.output));
244
+ }
245
+ } catch (e) {
246
+ outcome = 'error';
247
+ // With no reason this line reads as "the hook threw", which is how a malformed payload — bad
248
+ // input, not a fault — was being reported. The message is the only thing that tells them apart.
249
+ hookReason = String(/** @type {Error} */ (e)?.message ?? e);
250
+ process.exit(0); // fail-open, always
251
+ }
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart entry: refresh the semantic vault index in the background.
3
+ //
4
+ // Thin on purpose: stdin in, nothing out. Logic and tests live in lib/semantic-index-refresh.mjs.
5
+ import { readStdin, payload, hookCwd, logHook, standDown } from './lib/hook-io.mjs';
6
+ import { outcomeOf, refresh } from './lib/semantic-index-refresh.mjs';
7
+
8
+ const p = payload(readStdin());
9
+ if (standDown('semantic-index-refresh', p)) process.exit(0);
10
+ const cwd = hookCwd(p);
11
+ const session = /** @type {string|undefined} */ (p.session_id);
12
+
13
+ // A GATE: it decides and detaches, so the line below times the decision, never the re-index. The
14
+ // re-index writes its own line under the same session id, from scripts/memory-semantic.mjs.
15
+ const plan = refresh(cwd, new Date(), session);
16
+ logHook({
17
+ hook: 'semantic-index-refresh',
18
+ event: String(p.hook_event_name ?? ''),
19
+ cwd,
20
+ session,
21
+ outcome: outcomeOf(plan),
22
+ reason: plan.run ? plan.slug : plan.reason,
23
+ });
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // Pipe filter after vault-memory-sync.sh: its plain stdout becomes SessionStart context JSON, so
3
+ // Copilot CLI injects it too (#217). argv[2] is the hook payload, which the script consumed; it
4
+ // names the harness. The script stays unported; see CLAUDE.md.
5
+ import { readStdin, payload, standDown, sessionContext } from './lib/hook-io.mjs';
6
+
7
+ const p = payload(process.argv[2]);
8
+ const text = readStdin().trim();
9
+ if (!standDown('session-context', p) && text) console.log(sessionContext(text));