@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.
- package/LICENSE +21 -0
- package/README.md +412 -2
- package/hooks/distill-session.mjs +74 -0
- package/hooks/graph-staleness-check.mjs +25 -0
- package/hooks/hooks.json +94 -0
- package/hooks/insights-surface.mjs +48 -0
- package/hooks/lib/distill-session.mjs +1560 -0
- package/hooks/lib/dupe-report.mjs +61 -0
- package/hooks/lib/env-shell.mjs +92 -0
- package/hooks/lib/graph-staleness-check.mjs +394 -0
- package/hooks/lib/hook-io.mjs +715 -0
- package/hooks/lib/insights-surface.mjs +165 -0
- package/hooks/lib/memory-link-lint.mjs +499 -0
- package/hooks/lib/memory-recall.mjs +219 -0
- package/hooks/lib/omp.mjs +103 -0
- package/hooks/lib/opencode.mjs +231 -0
- package/hooks/lib/paths.mjs +452 -0
- package/hooks/lib/semantic-index-refresh.mjs +155 -0
- package/hooks/lib/validate-note.mjs +218 -0
- package/hooks/lib/vault-env.sh +110 -0
- package/hooks/memory-link-lint.mjs +65 -0
- package/hooks/memory-recall.mjs +251 -0
- package/hooks/semantic-index-refresh.mjs +23 -0
- package/hooks/session-context.mjs +9 -0
- package/hooks/validate-note.mjs +52 -0
- package/hooks/vault-memory-sync.sh +154 -0
- package/omp/index.js +1 -0
- package/opencode/index.js +1 -0
- package/package.json +51 -4
- package/scripts/claude-memory.mjs +31 -0
- package/scripts/doctor-perf.mjs +121 -0
- package/scripts/doctor.sh +558 -0
- package/scripts/env.mjs +6 -0
- package/scripts/lib/claude-memory.mjs +168 -0
- package/scripts/lib/doctor-perf.mjs +434 -0
- package/scripts/lib/hook-stats.mjs +864 -0
- package/scripts/lib/lexical.mjs +85 -0
- package/scripts/lib/memory-adopt.mjs +69 -0
- package/scripts/lib/memory-audit-checks.mjs +344 -0
- package/scripts/lib/memory-eval.mjs +381 -0
- package/scripts/lib/memory-mark.mjs +135 -0
- package/scripts/lib/memory-mcp.mjs +142 -0
- package/scripts/lib/memory-merge.mjs +316 -0
- package/scripts/lib/memory-mine.mjs +108 -0
- package/scripts/lib/memory-promote.mjs +207 -0
- package/scripts/lib/memory-prune.mjs +84 -0
- package/scripts/lib/memory-semantic.mjs +999 -0
- package/scripts/lib/memory-setup.mjs +170 -0
- package/scripts/lib/memory-synth-vault.mjs +538 -0
- package/scripts/lib/model-default.mjs +7 -0
- package/scripts/lib/models.mjs +58 -0
- package/scripts/lib/prune-logs.mjs +130 -0
- package/scripts/lib/recall-stats.mjs +354 -0
- package/scripts/lib/share-modules.mjs +70 -0
- package/scripts/lib/slim-install.mjs +162 -0
- package/scripts/lib/vault-mcp.mjs +405 -0
- package/scripts/memory-adopt.mjs +160 -0
- package/scripts/memory-audit-checks.mjs +375 -0
- package/scripts/memory-eval.mjs +753 -0
- package/scripts/memory-mark.mjs +39 -0
- package/scripts/memory-mcp.mjs +35 -0
- package/scripts/memory-merge.mjs +55 -0
- package/scripts/memory-prune.mjs +44 -0
- package/scripts/memory-semantic.mjs +1192 -0
- package/scripts/memory-setup.mjs +33 -0
- package/scripts/memory-synth-vault.mjs +251 -0
- package/scripts/prune-logs.mjs +42 -0
- package/scripts/share-modules.mjs +79 -0
- package/scripts/slim-install.mjs +55 -0
- package/scripts/vault-mcp.mjs +50 -0
- package/stubs/onnxruntime-web/index.mjs +11 -0
- package/stubs/onnxruntime-web/package.json +12 -0
- package/stubs/sharp/index.mjs +11 -0
- package/stubs/sharp/package.json +12 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
// THE resolver. Vault path, $CLAUDE_MEMORY_HOME, recall arming, project_key and legacy_key are
|
|
2
|
+
// resolved here and nowhere else. Everything resolves relative to this file, so the plugin works
|
|
3
|
+
// from its version-pinned cache dir, from a dev checkout, and via symlink.
|
|
4
|
+
//
|
|
5
|
+
// Single implementation since 2026-08-18 (previously mirrored in vault-env.sh, which forked bash
|
|
6
|
+
// for project_key) — docs/decisions/2026-08-18-single-resolver.md.
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
|
|
13
|
+
export const libDir = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
export const hooksDir = path.dirname(libDir);
|
|
15
|
+
export const pluginRoot = path.dirname(hooksDir);
|
|
16
|
+
export const scriptsDir = path.join(pluginRoot, 'scripts');
|
|
17
|
+
|
|
18
|
+
/** User settings file. Environment variables override its values. */
|
|
19
|
+
export function configFile() {
|
|
20
|
+
return path.join(memoryHome(), 'config.json');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {object} MemoryConfig
|
|
25
|
+
* @property {string} [vault]
|
|
26
|
+
* @property {boolean} [recall]
|
|
27
|
+
* @property {string} [model]
|
|
28
|
+
* @property {number} [modelIdleMs]
|
|
29
|
+
* @property {number} [serveIdleMs]
|
|
30
|
+
* @property {number} [logRetentionDays]
|
|
31
|
+
* @property {number|string|Record<string, number|string>} [freshnessDays]
|
|
32
|
+
* @property {boolean} [gitAutoCommit]
|
|
33
|
+
* @property {string[]} [crossProjectRecall]
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** @type {MemoryConfig|undefined} */
|
|
37
|
+
let _config;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} [file]
|
|
41
|
+
* @returns {MemoryConfig & Record<string, unknown>}
|
|
42
|
+
*/
|
|
43
|
+
export function readConfig(file = configFile()) {
|
|
44
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
45
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
46
|
+
throw new Error('config must be a JSON object');
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @returns {MemoryConfig} */
|
|
51
|
+
export function config() {
|
|
52
|
+
if (_config) return _config;
|
|
53
|
+
try {
|
|
54
|
+
_config = readConfig();
|
|
55
|
+
} catch {
|
|
56
|
+
_config = {};
|
|
57
|
+
}
|
|
58
|
+
return /** @type {MemoryConfig} */ (_config);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Vault root. Mirrors resolve_vault(): env var, then config.json, then the default. */
|
|
62
|
+
/** @param {MemoryConfig} [settings] */
|
|
63
|
+
export function vault(settings) {
|
|
64
|
+
return (
|
|
65
|
+
process.env.CLAUDE_VAULT ||
|
|
66
|
+
(settings ?? config()).vault ||
|
|
67
|
+
path.join(os.homedir(), 'Documents', 'ClaudeVault')
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Which source decided the vault — for /memory:doctor, so "wrong vault" is diagnosable.
|
|
73
|
+
* Must stay in step with vault(): same order, same branches.
|
|
74
|
+
*/
|
|
75
|
+
export function vaultSource() {
|
|
76
|
+
if (process.env.CLAUDE_VAULT) return 'CLAUDE_VAULT env';
|
|
77
|
+
if (config().vault) return configFile();
|
|
78
|
+
return 'built-in default';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Vault root for a WRITE path: env var or config.json only, never the built-in default.
|
|
83
|
+
*
|
|
84
|
+
* A write that falls through to the default scaffolds an empty vault and can move one project's
|
|
85
|
+
* notes into another's — the 2026-08-15 incident CLAUDE.md's "One deliberate, scoped exception"
|
|
86
|
+
* note records. A read that falls back gives a bad answer; a write that falls back writes to the
|
|
87
|
+
* wrong place, so only writers call this.
|
|
88
|
+
*
|
|
89
|
+
* Delegates to `vault()`/`vaultSource()` rather than re-deriving the env → config.json order, so a
|
|
90
|
+
* third fallback added to `vault()` later cannot silently miss this — the same drift `vaultSource()`
|
|
91
|
+
* itself is only documented, not structurally prevented, against.
|
|
92
|
+
*
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
export function requireVault() {
|
|
96
|
+
if (vaultSource() === 'built-in default') {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`no vault configured for a write — checked $CLAUDE_VAULT and "vault" in ${configFile()}`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
return vault();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* `requireVault()`'s sibling for the project key. A path-shaped key (`legacyKey()`, always a
|
|
106
|
+
* leading `-`) is accepted only when the vault already has a folder for it: a non-git project or a
|
|
107
|
+
* pre-migration folder has one, a directory that vanished before the write does not (#138).
|
|
108
|
+
*
|
|
109
|
+
* @param {string} key
|
|
110
|
+
* @param {string} vaultDir
|
|
111
|
+
* @returns {string}
|
|
112
|
+
*/
|
|
113
|
+
export function requireProjectKey(key, vaultDir) {
|
|
114
|
+
if (!key.startsWith('-')) return key;
|
|
115
|
+
if (
|
|
116
|
+
['Memory', 'Insights', 'Logs', 'Graph'].some((l) => fs.existsSync(path.join(vaultDir, l, key)))
|
|
117
|
+
)
|
|
118
|
+
return key;
|
|
119
|
+
// No key in the message: it lands in --hooks, whose redact() misses a slash-free path.
|
|
120
|
+
throw new Error(
|
|
121
|
+
'project key is a path slug with no vault folder — the directory is likely gone, refusing to write under it',
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Per-prompt recall is off unless explicitly armed. */
|
|
126
|
+
export function recallEnabled() {
|
|
127
|
+
return process.env.MEMORY_RECALL_ENABLED === '1' || config().recall === true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Does recall in this project read every project's notes? Opt-in per slug: a home repo that reaches
|
|
132
|
+
* other repos needs their lessons, every other project keeps its own.
|
|
133
|
+
* `MEMORY_CROSS_PROJECT_RECALL` is a comma-separated list and replaces the config list.
|
|
134
|
+
* @param {string} slug
|
|
135
|
+
*/
|
|
136
|
+
export function crossProjectRecall(slug) {
|
|
137
|
+
const env = process.env.MEMORY_CROSS_PROJECT_RECALL;
|
|
138
|
+
const list = env != null ? env.split(',').map((s) => s.trim()) : config().crossProjectRecall;
|
|
139
|
+
return Array.isArray(list) && list.includes(slug);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Auto-commit is off unless explicitly armed — a hook writing git history unattended must
|
|
143
|
+
* never be the default. */
|
|
144
|
+
export function gitAutoCommitEnabled() {
|
|
145
|
+
return process.env.MEMORY_GIT_AUTO_COMMIT === '1' || config().gitAutoCommit === true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// env -> config.json -> default, the order every setting resolves in. Anything unparseable or
|
|
149
|
+
// non-positive falls through to the default rather than disabling a timer: a typo'd env var must
|
|
150
|
+
// not leave a 1.3GB model resident forever.
|
|
151
|
+
/**
|
|
152
|
+
* @param {string} envName
|
|
153
|
+
* @param {keyof MemoryConfig} configKey
|
|
154
|
+
* @param {number} fallback
|
|
155
|
+
* @returns {number}
|
|
156
|
+
*/
|
|
157
|
+
const positiveMs = (envName, configKey, fallback) => {
|
|
158
|
+
const n = Number(process.env[envName] ?? config()[configKey]);
|
|
159
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* How long a resident --serve sits idle before dropping the MODEL (but staying alive).
|
|
164
|
+
* See CLAUDE.md's "modelIdleMs (5 min) unloads the model" note for the two-timer rationale.
|
|
165
|
+
*/
|
|
166
|
+
export function modelIdleMs() {
|
|
167
|
+
return positiveMs('MEMORY_MODEL_IDLE_MS', 'modelIdleMs', 5 * 60 * 1000);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* How long a resident --serve sits idle before exiting entirely.
|
|
172
|
+
* Reads config.json, not just the env var — hooks set this, and a value written to
|
|
173
|
+
* settings.json's `env` block does not reach the session that wrote it.
|
|
174
|
+
*/
|
|
175
|
+
export function serveIdleMs() {
|
|
176
|
+
return positiveMs('MEMORY_SERVE_IDLE_MS', 'serveIdleMs', 30 * 60 * 1000);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* How many days of dated JSONL logs (`recall-<date>`, `hooks-<date>`) are kept under `logs/`.
|
|
181
|
+
* 0 is legitimate (keep today only), so this cannot use `positiveMs`'s `> 0` guard. A non-digit
|
|
182
|
+
* value falls back to 30; a digits-only value is CLAMPED to a century rather than falling back,
|
|
183
|
+
* since an oversized value means "keep everything" and an Invalid Date would otherwise throw
|
|
184
|
+
* inside `pruneDatedLogs()` (found in review, 2026-08-21).
|
|
185
|
+
*/
|
|
186
|
+
const MAX_RETENTION_DAYS = 36500;
|
|
187
|
+
export function logRetentionDays() {
|
|
188
|
+
// An EXPORTED-BUT-EMPTY env var is unset, not a value — `??` alone keeps '' and shadows
|
|
189
|
+
// config.json (found by this function's own test).
|
|
190
|
+
const env = process.env.MEMORY_LOG_RETENTION_DAYS;
|
|
191
|
+
const raw = env === undefined || env.trim() === '' ? config().logRetentionDays : env;
|
|
192
|
+
// Digits only, not Number() — a stray space would otherwise cast to 0 and delete every log but
|
|
193
|
+
// today's, silently (2026-08-21, the same defect the vault pruner records).
|
|
194
|
+
const s = String(raw ?? '').trim();
|
|
195
|
+
if (!/^\d+$/.test(s)) return 30;
|
|
196
|
+
return Math.min(Number(s), MAX_RETENTION_DAYS);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const DEFAULT_FRESHNESS_DAYS = 90;
|
|
200
|
+
/**
|
|
201
|
+
* FRESH-2's window for a vault-relative note path: `freshnessDays` is a number, or folder prefixes
|
|
202
|
+
* mapped to days plus an optional `default`; the longest prefix wins. Why 90:
|
|
203
|
+
* docs/decisions/2026-10-12-freshness-window.md.
|
|
204
|
+
* @param {string} rel
|
|
205
|
+
* @returns {{ days: number, folder: string }}
|
|
206
|
+
*/
|
|
207
|
+
export function freshnessWindow(rel) {
|
|
208
|
+
/** @param {unknown} v */
|
|
209
|
+
const days = (v) => (/^\d+$/.test(String(v ?? '').trim()) ? Number(v) : null);
|
|
210
|
+
const env = process.env.MEMORY_FRESHNESS_DAYS;
|
|
211
|
+
const cfg = env === undefined || env.trim() === '' ? config().freshnessDays : env;
|
|
212
|
+
/** @type {Record<string, unknown>} */
|
|
213
|
+
const table = cfg && typeof cfg === 'object' ? cfg : { default: cfg };
|
|
214
|
+
const hit = Object.keys(table)
|
|
215
|
+
.filter((k) => k !== 'default' && rel.startsWith(k.replace(/\/+$/, '') + '/'))
|
|
216
|
+
.filter((k) => days(table[k]) !== null)
|
|
217
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
218
|
+
if (hit) return { days: /** @type {number} */ (days(table[hit])), folder: hit };
|
|
219
|
+
return { days: days(table.default) ?? DEFAULT_FRESHNESS_DAYS, folder: 'default' };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Mutable state root — never inside the plugin, which is wiped on update.
|
|
224
|
+
* Mirrors memory_home(). Subdirs: db/ models/ logs/ run/ eval/
|
|
225
|
+
*/
|
|
226
|
+
export function memoryHome() {
|
|
227
|
+
return process.env.CLAUDE_MEMORY_HOME || path.join(os.homedir(), '.claude-memory');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* memoryHome()/<name>, created if absent.
|
|
232
|
+
*
|
|
233
|
+
* @param {string} name
|
|
234
|
+
* @returns {string}
|
|
235
|
+
*/
|
|
236
|
+
export function stateDir(name) {
|
|
237
|
+
const d = path.join(memoryHome(), name);
|
|
238
|
+
fs.mkdirSync(d, { recursive: true });
|
|
239
|
+
return d;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @type {Map<string, string>} */
|
|
243
|
+
const keyCache = new Map();
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Locate the git config that decides this dir's project key, for cache validation only.
|
|
247
|
+
*
|
|
248
|
+
* Returns the config path (cacheable, validated by its mtime), `undefined` when there is no repo
|
|
249
|
+
* at all (cacheable — the key is then a pure function of the path), or `null` when `.git` is a
|
|
250
|
+
* FILE, i.e. a worktree or submodule, whose config lives somewhere this walk cannot cheaply
|
|
251
|
+
* confirm (not cacheable — always recompute).
|
|
252
|
+
*
|
|
253
|
+
* This is NOT a second implementation of project_key: it never derives a key, only answers
|
|
254
|
+
* "has anything that could change the key been touched?". Getting it wrong costs a cache miss,
|
|
255
|
+
* never a wrong answer, because computeProjectKey() below is the only thing that derives one.
|
|
256
|
+
*
|
|
257
|
+
* @param {string} dir
|
|
258
|
+
* @returns {string|null|undefined}
|
|
259
|
+
*/
|
|
260
|
+
function gitConfigFor(dir) {
|
|
261
|
+
let d = path.resolve(dir);
|
|
262
|
+
for (;;) {
|
|
263
|
+
const g = path.join(d, '.git');
|
|
264
|
+
try {
|
|
265
|
+
return fs.statSync(g).isDirectory() ? path.join(g, 'config') : null;
|
|
266
|
+
} catch {
|
|
267
|
+
/* not here — walk up */
|
|
268
|
+
}
|
|
269
|
+
const parent = path.dirname(d);
|
|
270
|
+
if (parent === d) return undefined;
|
|
271
|
+
d = parent;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const KEY_CACHE_FILE = () => path.join(memoryHome(), 'cache', 'project-keys.json');
|
|
276
|
+
|
|
277
|
+
/** @typedef {{ key: string, stamp: string|null }} KeyCacheEntry */
|
|
278
|
+
|
|
279
|
+
/** @returns {Record<string, KeyCacheEntry>} */
|
|
280
|
+
function readKeyCache() {
|
|
281
|
+
try {
|
|
282
|
+
return JSON.parse(fs.readFileSync(KEY_CACHE_FILE(), 'utf8'));
|
|
283
|
+
} catch {
|
|
284
|
+
return {};
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** @param {Record<string, KeyCacheEntry>} all */
|
|
289
|
+
function writeKeyCache(all) {
|
|
290
|
+
// Atomic: several hooks can fire at once, and a half-written cache must not become a parse
|
|
291
|
+
// error every session afterwards. A failed write is fine — it just costs the next lookup.
|
|
292
|
+
try {
|
|
293
|
+
const f = KEY_CACHE_FILE();
|
|
294
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
295
|
+
const tmp = `${f}.${process.pid}.tmp`;
|
|
296
|
+
fs.writeFileSync(tmp, JSON.stringify(all));
|
|
297
|
+
fs.renameSync(tmp, f);
|
|
298
|
+
} catch {
|
|
299
|
+
/* best effort */
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Normalise a git remote URL into a project key. Each step below is the `sed -e` expression it
|
|
304
|
+
// replaced in vault-env.sh, in the same order sed applied them.
|
|
305
|
+
// ASCII lowercase on purpose, not toLowerCase() — toLowerCase() is unicode-aware and would key a
|
|
306
|
+
// non-ASCII capital differently, silently splitting one project's vault folder in two.
|
|
307
|
+
/** @param {string} t */
|
|
308
|
+
const asciiLower = (t) => t.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* @param {string} url
|
|
312
|
+
* @returns {string}
|
|
313
|
+
*/
|
|
314
|
+
export function normaliseRemote(url) {
|
|
315
|
+
return asciiLower(
|
|
316
|
+
String(url)
|
|
317
|
+
.replace(/^[a-z+][a-z+]*:\/\//, '') // s#^[a-z+][a-z+]*://## scheme
|
|
318
|
+
.replace(/^[^@/]*@/, '') // s#^[^@/]*@## credentials, never keyed on
|
|
319
|
+
.replace(':', '/') // s#:#/# FIRST colon only: scp syntax
|
|
320
|
+
.replace(/\.git$/, '') // s#\.git$##
|
|
321
|
+
.replace(/\/*$/, ''), // s#/*$## trailing slashes
|
|
322
|
+
).replace(/\//g, '-'); // s#/#-#g
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* @param {string} dir
|
|
327
|
+
* @param {string[]} args
|
|
328
|
+
* @returns {string}
|
|
329
|
+
*/
|
|
330
|
+
const gitOut = (dir, args) => {
|
|
331
|
+
try {
|
|
332
|
+
return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: 'pipe' }).trim();
|
|
333
|
+
} catch {
|
|
334
|
+
return '';
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* The project key for a directory, computed for real.
|
|
340
|
+
*
|
|
341
|
+
* Identifies the PROJECT, not the checkout path, so one repo maps to one vault folder on every
|
|
342
|
+
* machine. Falls back to the repo directory name, then to the legacy cwd-slug for non-git dirs.
|
|
343
|
+
*
|
|
344
|
+
* @param {string} dir
|
|
345
|
+
* @returns {string}
|
|
346
|
+
*/
|
|
347
|
+
export function computeProjectKey(dir) {
|
|
348
|
+
const url = gitOut(dir, ['remote', 'get-url', 'origin']);
|
|
349
|
+
if (url) {
|
|
350
|
+
const key = normaliseRemote(url);
|
|
351
|
+
if (key) return key;
|
|
352
|
+
}
|
|
353
|
+
const top = gitOut(dir, ['rev-parse', '--show-toplevel']);
|
|
354
|
+
// asciiLower ONLY, not normaliseRemote() — the full pipeline on this branch silently re-keys a
|
|
355
|
+
// no-origin repo (`foo.git/` -> `foo`); see docs/architecture.md's "Known hacks" H1.
|
|
356
|
+
if (top) return asciiLower(path.basename(top));
|
|
357
|
+
return legacyKey(dir);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Stable per-project identifier, cached on disk.
|
|
362
|
+
* The cache is why this is not just `computeProjectKey`: short-lived hooks can't reuse the
|
|
363
|
+
* in-process Map, and forking git per hook was the largest cost in the per-prompt recall hook —
|
|
364
|
+
* 72 ms measured 2026-08-17, most of it a bash fork wrapping a git fork (the bash half is gone
|
|
365
|
+
* since 2026-08-18; the git half is what this still saves). Validated against a stamp on the git
|
|
366
|
+
* config that decides the key, so `git remote set-url` is a miss next call, not a stale key forever.
|
|
367
|
+
*
|
|
368
|
+
* @param {string} [dir]
|
|
369
|
+
* @returns {string}
|
|
370
|
+
*/
|
|
371
|
+
export function projectKey(dir = process.cwd()) {
|
|
372
|
+
if (keyCache.has(dir)) return /** @type {string} */ (keyCache.get(dir));
|
|
373
|
+
|
|
374
|
+
const cfg = gitConfigFor(dir);
|
|
375
|
+
/** @type {string|null} */
|
|
376
|
+
let stamp = null; // null => do not cache (worktree/submodule)
|
|
377
|
+
if (cfg === undefined) {
|
|
378
|
+
stamp = '0'; // no repo: key is a pure function of the path
|
|
379
|
+
} else if (typeof cfg === 'string') {
|
|
380
|
+
// "<whole seconds>:<size>:<inode>" — all three load-bearing; see CLAUDE.md's
|
|
381
|
+
// "project-key cache ... is now Node's alone" note, and the derivation in
|
|
382
|
+
// docs/decisions/2026-08-17-shell-vs-node-hooks.md.
|
|
383
|
+
try {
|
|
384
|
+
const st = fs.statSync(cfg);
|
|
385
|
+
stamp = `${Math.floor(st.mtimeMs / 1000)}:${st.size}:${st.ino}`;
|
|
386
|
+
} catch {
|
|
387
|
+
stamp = null;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const all = stamp === null ? null : readKeyCache();
|
|
392
|
+
const hit = all?.[dir];
|
|
393
|
+
if (hit && hit.stamp === stamp && typeof hit.key === 'string') {
|
|
394
|
+
keyCache.set(dir, hit.key);
|
|
395
|
+
return hit.key;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const out = computeProjectKey(dir);
|
|
399
|
+
keyCache.set(dir, out);
|
|
400
|
+
if (all) writeKeyCache({ ...all, [dir]: { key: out, stamp } });
|
|
401
|
+
return out;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Pre-2026-08-08 vault naming, and the vault key of a non-git dir. Keeps `_`, unlike
|
|
406
|
+
* `claudeProjectsKey()`; changing it would rename vault folders (#199).
|
|
407
|
+
*
|
|
408
|
+
* @param {string} [dir]
|
|
409
|
+
* @returns {string}
|
|
410
|
+
*/
|
|
411
|
+
export function legacyKey(dir = process.cwd()) {
|
|
412
|
+
return dir.replace(/[^A-Za-z0-9_-]/g, '-');
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* What Claude Code names ~/.claude/projects/<slug>/ after: every non-alphanumeric char is `-`.
|
|
417
|
+
*
|
|
418
|
+
* @param {string} [dir]
|
|
419
|
+
* @returns {string}
|
|
420
|
+
*/
|
|
421
|
+
export function claudeProjectsKey(dir = process.cwd()) {
|
|
422
|
+
return dir.replace(/[^A-Za-z0-9]/g, '-');
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Points transformers.js at $CLAUDE_MEMORY_HOME/models rather than its default cache inside the
|
|
427
|
+
* plugin dir (see CLAUDE.md's "paths.useModelCache() exists because..." note — v4 ignores
|
|
428
|
+
* HF_HOME/TRANSFORMERS_CACHE, so mutating `env.cacheDir` is the only way). Call before pipeline().
|
|
429
|
+
* @param {{ env: { cacheDir: string|null } }} transformers
|
|
430
|
+
* @returns {string}
|
|
431
|
+
*/
|
|
432
|
+
export function useModelCache(transformers) {
|
|
433
|
+
const d = stateDir('models');
|
|
434
|
+
transformers.env.cacheDir = d;
|
|
435
|
+
return d;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// The query a file-scoped recall sends (#226): path segments, then the nearest package name.
|
|
439
|
+
// ponytail: package.json only; add go.mod/pyproject when a non-JS repo is measured.
|
|
440
|
+
/** @param {string} file @param {string} cwd @returns {string} */
|
|
441
|
+
export function fileQuery(file, cwd) {
|
|
442
|
+
const abs = path.resolve(cwd, file);
|
|
443
|
+
const rel = path.relative(cwd, abs);
|
|
444
|
+
const parts = (rel.startsWith('..') ? abs : rel).split(/[\\/]/).filter(Boolean);
|
|
445
|
+
for (let d = path.dirname(abs); ; d = path.dirname(d)) {
|
|
446
|
+
try {
|
|
447
|
+
const { name } = JSON.parse(fs.readFileSync(path.join(d, 'package.json'), 'utf8'));
|
|
448
|
+
if (typeof name === 'string') return [...parts, name].join(' ');
|
|
449
|
+
} catch {}
|
|
450
|
+
if (d === path.dirname(d)) return parts.join(' ');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// SessionStart: keep the semantic vault index current, in the background — the logic half. The
|
|
2
|
+
// CLI entry is hooks/semantic-index-refresh.mjs. Why a hook rather than a convention, and why
|
|
3
|
+
// SessionStart rather than SessionEnd: docs/architecture.md's Flow 1.
|
|
4
|
+
//
|
|
5
|
+
// Cost when nothing changed: the indexer compares mtimes and exits before loading the model, so
|
|
6
|
+
// a no-op costs a stat pass. Either way the child is detached, so session start never waits.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { vault, projectKey, legacyKey, stateDir, scriptsDir, pluginRoot } from './paths.mjs';
|
|
11
|
+
import { detach, logBanner } from './hook-io.mjs';
|
|
12
|
+
|
|
13
|
+
// Constants, not literals — outcomeOf() below decides on them too; see CLAUDE.md's
|
|
14
|
+
// "reason string that an outcome mapper decides on" rule.
|
|
15
|
+
export const REASONS = {
|
|
16
|
+
noVault: 'no vault memory for this project',
|
|
17
|
+
noScript: 'indexer script missing',
|
|
18
|
+
noRuntime: 'embedding runtime not installed',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {{ run: false, reason: string, warn?: string }} SkipPlan
|
|
23
|
+
* @typedef {{
|
|
24
|
+
* run: true, slug: string, script: string, args: string[], logFile: string, spawned?: boolean,
|
|
25
|
+
* }} RunPlan
|
|
26
|
+
* @typedef {SkipPlan | RunPlan} RefreshPlan
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** @param {string} p */
|
|
30
|
+
const isDir = (p) => {
|
|
31
|
+
try {
|
|
32
|
+
return fs.statSync(p).isDirectory();
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The slug whose vault memory actually exists on disk, or null.
|
|
40
|
+
* Falls back to the legacy slug for this one session: vault-memory-sync's legacy_key ->
|
|
41
|
+
* project_key rename may not have run yet, since SessionStart hook order is not guaranteed.
|
|
42
|
+
* @param {string} cwd
|
|
43
|
+
* @param {string} [vaultRoot]
|
|
44
|
+
* @returns {string | null}
|
|
45
|
+
*/
|
|
46
|
+
export function resolveSlug(cwd, vaultRoot = vault()) {
|
|
47
|
+
let slug;
|
|
48
|
+
try {
|
|
49
|
+
slug = projectKey(cwd);
|
|
50
|
+
} catch {
|
|
51
|
+
slug = legacyKey(cwd);
|
|
52
|
+
}
|
|
53
|
+
if (isDir(path.join(vaultRoot, 'Memory', slug))) return slug;
|
|
54
|
+
const legacy = legacyKey(cwd);
|
|
55
|
+
if (legacy !== slug && isDir(path.join(vaultRoot, 'Memory', legacy))) return legacy;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Is the embedding runtime actually installed?
|
|
61
|
+
* `existsSync` dereferences on purpose: node_modules is a symlink into $CLAUDE_MEMORY_HOME
|
|
62
|
+
* (scripts/share-modules.mjs), and lstat-ing the link instead of the target is the bug that made
|
|
63
|
+
* /memory:doctor report 0 MB on 2026-08-18.
|
|
64
|
+
* @param {string} [root]
|
|
65
|
+
* @returns {boolean}
|
|
66
|
+
*/
|
|
67
|
+
export function runtimeInstalled(root = pluginRoot) {
|
|
68
|
+
return isDir(path.join(root, 'node_modules', '@huggingface', 'transformers'));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Decide without acting — reads the filesystem, spawns and writes nothing, so it's testable
|
|
73
|
+
* against a temp vault.
|
|
74
|
+
* @param {string} cwd
|
|
75
|
+
* @param {{ vaultRoot?: string }} [options]
|
|
76
|
+
* @returns {RefreshPlan}
|
|
77
|
+
*/
|
|
78
|
+
export function plan(cwd, { vaultRoot = vault() } = {}) {
|
|
79
|
+
const slug = resolveSlug(cwd, vaultRoot);
|
|
80
|
+
if (!slug) return { run: false, reason: REASONS.noVault };
|
|
81
|
+
|
|
82
|
+
const script = path.join(scriptsDir, 'memory-semantic.mjs');
|
|
83
|
+
if (!fs.existsSync(script)) return { run: false, reason: REASONS.noScript };
|
|
84
|
+
|
|
85
|
+
// `npm ci` skips lifecycle scripts (docs/architecture.md, Flow 5), so the native binary can be
|
|
86
|
+
// missing even when the package dir exists. Say so once instead of failing at query time.
|
|
87
|
+
if (!runtimeInstalled())
|
|
88
|
+
return {
|
|
89
|
+
run: false,
|
|
90
|
+
reason: REASONS.noRuntime,
|
|
91
|
+
warn: '⚠ memory: embedding runtime not installed — semantic recall is off. Run /memory:install',
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
run: true,
|
|
96
|
+
slug,
|
|
97
|
+
script,
|
|
98
|
+
args: [script, '--index', cwd],
|
|
99
|
+
logFile: path.join(stateDir('logs'), 'semantic-index.log'),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The environment the detached indexer runs under.
|
|
105
|
+
* Two variables, not one — the session id alone is inherited by the distiller's own re-index too;
|
|
106
|
+
* see CLAUDE.md's "indexer's line is guarded by MEMORY_INDEX_HOOK" note.
|
|
107
|
+
* @param {string} [session]
|
|
108
|
+
* @returns {Record<string, string | undefined>}
|
|
109
|
+
*/
|
|
110
|
+
export function workerEnv(session) {
|
|
111
|
+
return { MEMORY_HOOK_SESSION: session, MEMORY_INDEX_HOOK: '1' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Plan, then act.
|
|
116
|
+
* No lock here — the indexer takes its own cross-process, per-model lock (db/.index-<model>.lock).
|
|
117
|
+
* This hook used to take a second, coarser one on the same file; its only effect was a silent
|
|
118
|
+
* skip on contention (exit 0, no output), so a session that indexed nothing looked like one with
|
|
119
|
+
* nothing to index.
|
|
120
|
+
* @param {string} cwd
|
|
121
|
+
* @param {Date} [now]
|
|
122
|
+
* @param {string} [session] forwarded to the detached indexer so its own log line and this hook's
|
|
123
|
+
* gate line read as one background run
|
|
124
|
+
* @returns {RefreshPlan}
|
|
125
|
+
*/
|
|
126
|
+
export function refresh(cwd, now = new Date(), session) {
|
|
127
|
+
const p = plan(cwd);
|
|
128
|
+
if (!p.run) {
|
|
129
|
+
if (p.warn) console.error(p.warn);
|
|
130
|
+
return p;
|
|
131
|
+
}
|
|
132
|
+
logBanner(p.logFile, p.slug, now.toISOString().replace(/\.\d+Z$/, 'Z'));
|
|
133
|
+
// Null pid is the only signal the spawn failed (it fails async) — see CLAUDE.md's
|
|
134
|
+
// "gate that detaches decides its outcome on detach()'s pid" note.
|
|
135
|
+
const pid = detach(process.execPath, p.args, {
|
|
136
|
+
cwd,
|
|
137
|
+
logFile: p.logFile,
|
|
138
|
+
env: workerEnv(session),
|
|
139
|
+
});
|
|
140
|
+
return { ...p, spawned: pid != null };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Same objects plan() returns, not copies of their text — a permanently-dead hook must not read
|
|
144
|
+
// as one that ran and found nothing to do.
|
|
145
|
+
const MISSING_DEP = new Set([REASONS.noRuntime, REASONS.noScript]);
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* @param {RefreshPlan} p
|
|
149
|
+
* @returns {import('./hook-io.mjs').HookOutcome}
|
|
150
|
+
*/
|
|
151
|
+
export function outcomeOf(p) {
|
|
152
|
+
// Absent `spawned` means nobody acted; report the loud reading rather than claiming success.
|
|
153
|
+
if (p.run) return p.spawned ? 'spawned' : 'error';
|
|
154
|
+
return MISSING_DEP.has(p.reason) ? 'noop-missing-dep' : 'ran';
|
|
155
|
+
}
|