@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,715 @@
|
|
|
1
|
+
// Shared plumbing for the hooks that are GATES: read a JSON payload on stdin, decide cheaply,
|
|
2
|
+
// then detach the real work and exit. Three hooks had each grown their own copy of this —
|
|
3
|
+
// docs/decisions/2026-08-18-node-hooks.md, "Duplication".
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { stateDir, projectKey, logRetentionDays } from './paths.mjs';
|
|
10
|
+
|
|
11
|
+
/** Claude Code sends hook input as one JSON object on stdin. A hook must never die on bad input. */
|
|
12
|
+
export function readStdin() {
|
|
13
|
+
try {
|
|
14
|
+
return fs.readFileSync(0, 'utf8');
|
|
15
|
+
} catch {
|
|
16
|
+
return '';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {{
|
|
22
|
+
* cwd?: string,
|
|
23
|
+
* prompt?: string,
|
|
24
|
+
* session_id?: string,
|
|
25
|
+
* transcript_path?: string | null,
|
|
26
|
+
* hook_event_name?: string,
|
|
27
|
+
* tool_name?: string,
|
|
28
|
+
* tool_input?: Record<string, unknown>,
|
|
29
|
+
* stop_hook_active?: boolean,
|
|
30
|
+
* } & Record<string, unknown>} HookPayload
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parse a hook payload. Anything unparseable is an empty payload, never a throw.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} [raw]
|
|
37
|
+
* @returns {HookPayload}
|
|
38
|
+
*/
|
|
39
|
+
export function payload(raw) {
|
|
40
|
+
/** @type {HookPayload} */
|
|
41
|
+
let v = {};
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(raw || '{}');
|
|
44
|
+
if (parsed && typeof parsed === 'object') v = parsed;
|
|
45
|
+
} catch {}
|
|
46
|
+
setHarness(v);
|
|
47
|
+
return v;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Copilot CLI stamps `timestamp` on every payload and names fields in camelCase for its own event
|
|
52
|
+
* names; Claude Code sends neither. Codex CLI sends Claude's shape, but its transcript is a
|
|
53
|
+
* `rollout-*.jsonl` (null under `exec --ephemeral`) and its turn events carry `turn_id`. An adapter that builds the payload itself
|
|
54
|
+
* names itself in `harness`. Read from the payload, not the env, because every CLI leaks its env
|
|
55
|
+
* vars into anything started from its shell tool.
|
|
56
|
+
*
|
|
57
|
+
* @param {HookPayload} p
|
|
58
|
+
*/
|
|
59
|
+
export function setHarness(p) {
|
|
60
|
+
process.env.MEMORY_HARNESS =
|
|
61
|
+
p.harness === 'opencode' || p.harness === 'omp'
|
|
62
|
+
? p.harness
|
|
63
|
+
: p.timestamp !== undefined || p.sessionId !== undefined
|
|
64
|
+
? 'copilot'
|
|
65
|
+
: p.turn_id !== undefined ||
|
|
66
|
+
p.transcript_path === null ||
|
|
67
|
+
/(^|\/)rollout-[^/]*\.jsonl$/.test(String(p.transcript_path ?? ''))
|
|
68
|
+
? 'codex'
|
|
69
|
+
: 'claude';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @typedef {'claude' | 'copilot' | 'codex' | 'opencode' | 'omp'} Harness */
|
|
73
|
+
|
|
74
|
+
/** Which CLI fired this hook; a detached worker inherits it from its gate. @returns {Harness} */
|
|
75
|
+
export const harness = () => {
|
|
76
|
+
const h = process.env.MEMORY_HARNESS;
|
|
77
|
+
return h === 'copilot' || h === 'codex' || h === 'opencode' || h === 'omp' ? h : 'claude';
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export const copilotHome = () => process.env.COPILOT_HOME || path.join(os.homedir(), '.copilot');
|
|
81
|
+
|
|
82
|
+
/** Locate the `copilot` CLI, as findClaude() does `claude`. */
|
|
83
|
+
export const findCopilot = () => findBin('copilot');
|
|
84
|
+
|
|
85
|
+
/** Locate the `codex` CLI. */
|
|
86
|
+
export const findCodex = () => findBin('codex');
|
|
87
|
+
|
|
88
|
+
/** @param {string} name */
|
|
89
|
+
function findBin(name) {
|
|
90
|
+
for (const cand of [which(name), `/opt/homebrew/bin/${name}`, `/usr/local/bin/${name}`]) {
|
|
91
|
+
if (cand && fs.existsSync(cand)) return cand;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The cwd a hook should act on. Claude Code always sends it; `process.cwd()` is the safety net.
|
|
98
|
+
*
|
|
99
|
+
* @param {HookPayload} [p]
|
|
100
|
+
* @returns {string}
|
|
101
|
+
*/
|
|
102
|
+
export function hookCwd(p) {
|
|
103
|
+
return p?.cwd || process.cwd();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The cwd for a WRITE path: the payload's own field only, never `process.cwd()`.
|
|
108
|
+
*
|
|
109
|
+
* `process.cwd()` is right for a hook Claude Code spawned in the project, and wrong for a detached
|
|
110
|
+
* worker or an agent-spawned subprocess — the same silent-fallback shape as `requireVault()` in
|
|
111
|
+
* paths.mjs, and for the same reason: a write that guesses scope can write into the wrong project.
|
|
112
|
+
*
|
|
113
|
+
* @param {HookPayload | null} [p]
|
|
114
|
+
* @returns {string}
|
|
115
|
+
*/
|
|
116
|
+
export function requireHookCwd(p) {
|
|
117
|
+
if (p?.cwd) return p.cwd;
|
|
118
|
+
throw new Error('hook payload has no cwd — refusing to infer scope for a write');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Debounce markers, and the timestamps in them. Live under $CLAUDE_MEMORY_HOME/cache/, not
|
|
123
|
+
* ~/.cache/claude-* — CLAUDE.md's "all mutable state lives in $CLAUDE_MEMORY_HOME" rule.
|
|
124
|
+
* @param {string} name
|
|
125
|
+
* @returns {string}
|
|
126
|
+
*/
|
|
127
|
+
export function markerPath(name) {
|
|
128
|
+
return path.join(stateDir('cache'), `${name}.ts`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {string} file
|
|
133
|
+
* @returns {number}
|
|
134
|
+
*/
|
|
135
|
+
export function readMarker(file) {
|
|
136
|
+
try {
|
|
137
|
+
const n = Number(fs.readFileSync(file, 'utf8').trim());
|
|
138
|
+
return Number.isFinite(n) ? n : 0;
|
|
139
|
+
} catch {
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {string} file
|
|
146
|
+
* @param {number} seconds
|
|
147
|
+
*/
|
|
148
|
+
export function writeMarker(file, seconds) {
|
|
149
|
+
try {
|
|
150
|
+
fs.writeFileSync(file, `${seconds}\n`);
|
|
151
|
+
} catch {
|
|
152
|
+
/* a marker we cannot write means we run again next session — never a reason to fail the hook */
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Day claims `.retention-<day>` and `.dupes-<day>-<slug>`: written by `claim()`, swept by
|
|
157
|
+
// `pruneDatedLogs()`. Anchored on a DATE — `.startsWith('.retention-')` also matched
|
|
158
|
+
// `.retention-notes.md` and a bare `.retention-`, which are not ours to delete.
|
|
159
|
+
const CLAIM = /^\.(?:retention-(\d{4}-\d{2}-\d{2})|dupes-(\d{4}-\d{2}-\d{2})-.+)$/;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* True once per marker name: `wx` create-if-absent; any error (EEXIST too) means don't run.
|
|
163
|
+
* See CLAUDE.md's retention section and docs/decisions/2026-08-21-log-retention-day-claim.md.
|
|
164
|
+
* @param {string} dir
|
|
165
|
+
* @param {string} name
|
|
166
|
+
* @returns {boolean}
|
|
167
|
+
*/
|
|
168
|
+
function claim(dir, name) {
|
|
169
|
+
try {
|
|
170
|
+
fs.closeSync(fs.openSync(path.join(dir, name), 'wx'));
|
|
171
|
+
return true;
|
|
172
|
+
} catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Per project, not machine-wide: a machine-wide claim would report only the first project opened.
|
|
179
|
+
* @param {string} slug
|
|
180
|
+
* @param {Date} [now]
|
|
181
|
+
*/
|
|
182
|
+
export function claimDupeScan(slug, now = new Date()) {
|
|
183
|
+
return claim(stateDir('logs'), dupeMarker(slug, now));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A read, not a claim: lets a scan skip its work when today's report is already out.
|
|
188
|
+
* @param {string} slug
|
|
189
|
+
* @param {Date} [now]
|
|
190
|
+
*/
|
|
191
|
+
export function dupeScanDone(slug, now = new Date()) {
|
|
192
|
+
return fs.existsSync(path.join(stateDir('logs'), dupeMarker(slug, now)));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const dupeMarker = (/** @type {string} */ slug, /** @type {Date} */ now) =>
|
|
196
|
+
`.dupes-${now.toISOString().slice(0, 10)}-${slug}`;
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Is a run still inside its debounce window? `last === 0` (no marker) must NOT count as recent,
|
|
200
|
+
* or the first run would suppress itself forever.
|
|
201
|
+
* @param {number} last
|
|
202
|
+
* @param {number} windowSeconds
|
|
203
|
+
* @param {number} now
|
|
204
|
+
* @returns {boolean}
|
|
205
|
+
*/
|
|
206
|
+
export function withinDebounce(last, windowSeconds, now) {
|
|
207
|
+
return last > 0 && now - last < windowSeconds;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Whole seconds since the epoch — the unit every marker file is written in.
|
|
212
|
+
* @param {number} [d]
|
|
213
|
+
* @returns {number}
|
|
214
|
+
*/
|
|
215
|
+
export function nowSeconds(d = Date.now()) {
|
|
216
|
+
return Math.floor(d / 1000);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Exported since 2026-08-19 — kept here, not copied locally, after a local copy in
|
|
220
|
+
// distill-session.mjs silently broke distillation (ReferenceError, caught before any release
|
|
221
|
+
// shipped it). Full incident: CHANGELOG.md's 0.4.0 entry ("reindex() called a bare `which`").
|
|
222
|
+
/**
|
|
223
|
+
* @param {string} cmd
|
|
224
|
+
* @returns {string|null}
|
|
225
|
+
*/
|
|
226
|
+
export const which = (cmd) => {
|
|
227
|
+
for (const dir of (process.env.PATH || '').split(path.delimiter)) {
|
|
228
|
+
if (!dir) continue;
|
|
229
|
+
const p = path.join(dir, cmd);
|
|
230
|
+
try {
|
|
231
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
232
|
+
return p;
|
|
233
|
+
} catch {
|
|
234
|
+
/* not here */
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* A machine-wide lock for background work too heavy to run twice at once. Ownership is a LIVE
|
|
242
|
+
* PID, not a release call — a detached child cannot be trusted to clean up after itself, so the
|
|
243
|
+
* lock frees itself once its process is gone. `maxSeconds` backstops a recycled pid or a wedged
|
|
244
|
+
* child, the two cases a pid check alone can't see.
|
|
245
|
+
* @param {number} pid
|
|
246
|
+
*/
|
|
247
|
+
const alive = (pid) => {
|
|
248
|
+
try {
|
|
249
|
+
process.kill(pid, 0);
|
|
250
|
+
return true;
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The pid holding `file`, or null when the lock is free, stale or unreadable.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} file
|
|
260
|
+
* @param {number} maxSeconds
|
|
261
|
+
* @param {number} [now]
|
|
262
|
+
* @returns {number|null}
|
|
263
|
+
*/
|
|
264
|
+
export function lockHolder(file, maxSeconds, now = nowSeconds()) {
|
|
265
|
+
try {
|
|
266
|
+
const [pid, at] = fs.readFileSync(file, 'utf8').trim().split(/\s+/).map(Number);
|
|
267
|
+
// pid 0 is the one value the finite check lets through and `kill(0, 0)` accepts: POSIX reads
|
|
268
|
+
// it as "my own process group", so a lock truncated to `0 <ts>` would read as held for an hour.
|
|
269
|
+
if (!Number.isFinite(pid) || pid <= 0 || !Number.isFinite(at)) return null;
|
|
270
|
+
if (now - at >= maxSeconds) return null;
|
|
271
|
+
return alive(pid) ? pid : null;
|
|
272
|
+
} catch {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* `wx` claims a lock that must not already exist; the default `w` hands an existing one over.
|
|
279
|
+
* `at` names lockHolder's destructured `at` — a TIMESTAMP, not the `maxSeconds` duration beside it.
|
|
280
|
+
* @param {string} file
|
|
281
|
+
* @param {number} pid
|
|
282
|
+
* @param {number} at
|
|
283
|
+
* @param {string} [flag]
|
|
284
|
+
* @returns {boolean}
|
|
285
|
+
*/
|
|
286
|
+
export function writeLock(file, pid, at, flag = 'w') {
|
|
287
|
+
try {
|
|
288
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
289
|
+
fs.writeFileSync(file, `${pid} ${at}\n`, { flag });
|
|
290
|
+
return true;
|
|
291
|
+
} catch {
|
|
292
|
+
return false; // a lock we cannot write degrades to the old behaviour: another run may start
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** @param {string} file */
|
|
297
|
+
export function releaseLock(file) {
|
|
298
|
+
try {
|
|
299
|
+
fs.unlinkSync(file);
|
|
300
|
+
} catch {
|
|
301
|
+
/* already gone, or never ours */
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* @param {string} file
|
|
307
|
+
* @returns {number|null}
|
|
308
|
+
*/
|
|
309
|
+
const inode = (file) => {
|
|
310
|
+
try {
|
|
311
|
+
return fs.statSync(file).ino;
|
|
312
|
+
} catch {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Claim the lock. True only for the caller that created the file. The inode is captured before
|
|
319
|
+
* the staleness verdict and re-checked after it, narrowing (not closing) a reclaim race — full
|
|
320
|
+
* reasoning and the unlink-then-create bug it replaced: docs/architecture.md, "H16".
|
|
321
|
+
* @param {string} file
|
|
322
|
+
* @param {number} pid
|
|
323
|
+
* @param {number} at
|
|
324
|
+
* @param {number} maxSeconds
|
|
325
|
+
* @param {number} [now]
|
|
326
|
+
* @returns {boolean}
|
|
327
|
+
*/
|
|
328
|
+
export function takeLock(file, pid, at, maxSeconds, now = nowSeconds()) {
|
|
329
|
+
const claim = () => writeLock(file, pid, at, 'wx');
|
|
330
|
+
if (claim()) return true;
|
|
331
|
+
|
|
332
|
+
const stale = inode(file);
|
|
333
|
+
if (lockHolder(file, maxSeconds, now)) return false;
|
|
334
|
+
// Vanished between the failed claim and here — released by its owner, not a rival. Retry via
|
|
335
|
+
// `wx` rather than unlinking first: the file it would remove could be a lock created since.
|
|
336
|
+
if (stale === null) return claim();
|
|
337
|
+
if (inode(file) !== stale) return false; // replaced: the lock we judged is somebody else's now
|
|
338
|
+
|
|
339
|
+
releaseLock(file);
|
|
340
|
+
return claim();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Locate the `claude` CLI.
|
|
345
|
+
* PATH first, then the install locations a GUI-launched session may not have — one list, because
|
|
346
|
+
* two lists drift and the failure is silent (CHANGELOG.md's `findClaude()` Homebrew/Linux fix).
|
|
347
|
+
*/
|
|
348
|
+
export function findClaude() {
|
|
349
|
+
for (const cand of [
|
|
350
|
+
which('claude'),
|
|
351
|
+
path.join(os.homedir(), '.claude/local/claude'),
|
|
352
|
+
path.join(os.homedir(), '.local/bin/claude'),
|
|
353
|
+
'/opt/homebrew/bin/claude',
|
|
354
|
+
'/home/linuxbrew/.linuxbrew/bin/claude',
|
|
355
|
+
'/usr/local/bin/claude',
|
|
356
|
+
]) {
|
|
357
|
+
if (cand && fs.existsSync(cand)) return cand;
|
|
358
|
+
}
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* The argv of every headless `claude -p` this plugin spawns. Built in one place so no spawn site
|
|
364
|
+
* can forget `--no-session-persistence`: without it each run left a ~400 KB transcript (#201).
|
|
365
|
+
* @param {string[]} rest
|
|
366
|
+
*/
|
|
367
|
+
export const headlessArgv = (...rest) => ['-p', '--no-session-persistence', ...rest];
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Append-open a log file, returning a writable fd or null. Detached children write straight to
|
|
371
|
+
* the fd — piping would keep this process alive to shuttle bytes, the one thing a gate must not
|
|
372
|
+
* do. Trims here too: distill.log/graphgen.log never go through `logBanner()`.
|
|
373
|
+
* @param {string} file
|
|
374
|
+
* @returns {number|null}
|
|
375
|
+
*/
|
|
376
|
+
function openLog(file) {
|
|
377
|
+
try {
|
|
378
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
379
|
+
trimLog(file);
|
|
380
|
+
return fs.openSync(file, 'a');
|
|
381
|
+
} catch {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Spawn background work and forget it. detached + unref + stdio to a file (or /dev/null) is the
|
|
388
|
+
* whole contract — a child that inherited a pipe would hold the event loop open, one that
|
|
389
|
+
* inherited stderr would print into the session transcript. Returns the child pid (a caller's
|
|
390
|
+
* lock-file value), or null.
|
|
391
|
+
*
|
|
392
|
+
* @typedef {object} DetachOptions
|
|
393
|
+
* @property {Record<string, string|undefined>} [env]
|
|
394
|
+
* @property {string} [cwd]
|
|
395
|
+
* @property {string} [logFile]
|
|
396
|
+
*/
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* @param {string} cmd
|
|
400
|
+
* @param {readonly string[]} args
|
|
401
|
+
* @param {DetachOptions} [opts]
|
|
402
|
+
* @returns {number|null}
|
|
403
|
+
*/
|
|
404
|
+
export function detach(cmd, args, { env, cwd, logFile } = {}) {
|
|
405
|
+
const fd = logFile ? openLog(logFile) : null;
|
|
406
|
+
try {
|
|
407
|
+
const child = spawn(cmd, args, {
|
|
408
|
+
cwd,
|
|
409
|
+
detached: true,
|
|
410
|
+
stdio: fd == null ? 'ignore' : ['ignore', fd, fd],
|
|
411
|
+
env: env ? { ...process.env, ...env } : process.env,
|
|
412
|
+
});
|
|
413
|
+
// spawn() reports a missing binary ASYNCHRONOUSLY, so the throw below never sees it — recorded
|
|
414
|
+
// here rather than swallowed, since a pid may already be written into a lock (same reason as
|
|
415
|
+
// the LOCK HANDOVER FAILED banner).
|
|
416
|
+
child.on('error', (e) => {
|
|
417
|
+
if (logFile) logBanner(logFile, `spawn failed: ${e.message}`, new Date().toISOString());
|
|
418
|
+
});
|
|
419
|
+
child.unref();
|
|
420
|
+
return child.pid ?? null;
|
|
421
|
+
} catch {
|
|
422
|
+
return null; // a hook never fails because its background work could not start
|
|
423
|
+
} finally {
|
|
424
|
+
if (fd != null) {
|
|
425
|
+
try {
|
|
426
|
+
fs.closeSync(fd);
|
|
427
|
+
} catch {
|
|
428
|
+
/* the child holds its own copy */
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// The only unbounded appends: semantic-index.log, distill.log, graphgen.log (CLAUDE.md's logging
|
|
435
|
+
// section). Two doors write to them, so both call trimLog() below — neither alone is enough.
|
|
436
|
+
const LOG_MAX_BYTES = 1024 * 1024;
|
|
437
|
+
const LOG_KEEP_BYTES = 256 * 1024;
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Keep only the tail of an oversized log. NOT ATOMIC, deliberately — do not "fix" it with a
|
|
441
|
+
* temp-file rename, that is worse here. Full reasoning: docs/architecture.md, "H15".
|
|
442
|
+
* @param {string} file
|
|
443
|
+
*/
|
|
444
|
+
function trimLog(file) {
|
|
445
|
+
try {
|
|
446
|
+
const size = fs.statSync(file).size;
|
|
447
|
+
if (size <= LOG_MAX_BYTES) return;
|
|
448
|
+
const fd = fs.openSync(file, 'r');
|
|
449
|
+
let tail;
|
|
450
|
+
try {
|
|
451
|
+
const buf = Buffer.allocUnsafe(LOG_KEEP_BYTES);
|
|
452
|
+
const read = fs.readSync(fd, buf, 0, LOG_KEEP_BYTES, size - LOG_KEEP_BYTES);
|
|
453
|
+
tail = buf.subarray(0, read);
|
|
454
|
+
} finally {
|
|
455
|
+
fs.closeSync(fd);
|
|
456
|
+
}
|
|
457
|
+
const nl = tail.indexOf(0x0a);
|
|
458
|
+
fs.writeFileSync(file, nl === -1 ? tail : tail.subarray(nl + 1));
|
|
459
|
+
} catch {
|
|
460
|
+
/* best effort */
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Timestamped log banner, so one log file can be read as a sequence of runs.
|
|
466
|
+
*
|
|
467
|
+
* @param {string} file
|
|
468
|
+
* @param {string} label
|
|
469
|
+
* @param {string} iso
|
|
470
|
+
*/
|
|
471
|
+
export function logBanner(file, label, iso) {
|
|
472
|
+
try {
|
|
473
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
474
|
+
trimLog(file);
|
|
475
|
+
fs.appendFileSync(file, `\n=== ${iso} ${label} ===\n`);
|
|
476
|
+
} catch {
|
|
477
|
+
/* best effort */
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// One JSONL appender, two families — shape, retention and error-swallowing contract are in
|
|
482
|
+
// CLAUDE.md's logging section. The `logHook()` cost sweep (adding this call, six hooks, before
|
|
483
|
+
// and after medians) is in docs/decisions/2026-08-20-hook-startup-cost.md.
|
|
484
|
+
//
|
|
485
|
+
// ponytail: `projectKey()` is left uncached for a checkout whose `.git` is a FILE (worktree or
|
|
486
|
+
// submodule) — measured 14.6 ms per call in a worktree of this repo, 2026-08-21, on every
|
|
487
|
+
// Write/Edit through validate-note. Fixing it means resolving the `.git` file to the real config
|
|
488
|
+
// path and stamping THAT, a change to project identity that belongs in its own commit with its
|
|
489
|
+
// own test.
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Append one record to a daily-dated log family under `$CLAUDE_MEMORY_HOME/logs/`. Stamps `t` and
|
|
493
|
+
* the project slug, then writes the caller's record verbatim after them (CLAUDE.md's "exactly one
|
|
494
|
+
* JSONL appender" note). `slug` is the scoping key: the logs are MACHINE-WIDE, every project
|
|
495
|
+
* appends to the same daily file. An unresolvable key logs `null` rather than throwing.
|
|
496
|
+
*
|
|
497
|
+
* @param {string} family
|
|
498
|
+
* @param {string | undefined} cwd
|
|
499
|
+
* @param {Record<string, unknown>} record
|
|
500
|
+
*/
|
|
501
|
+
export function appendJsonl(family, cwd, record) {
|
|
502
|
+
try {
|
|
503
|
+
const t = new Date().toISOString();
|
|
504
|
+
/** @type {string | null} */
|
|
505
|
+
let slug = null;
|
|
506
|
+
try {
|
|
507
|
+
slug = projectKey(cwd);
|
|
508
|
+
} catch {
|
|
509
|
+
/* no repo, or a key we cannot resolve — the line is still worth writing */
|
|
510
|
+
}
|
|
511
|
+
const dir = stateDir('logs');
|
|
512
|
+
const file = path.join(dir, `${family}-${t.slice(0, 10)}.jsonl`);
|
|
513
|
+
// One atomic wx claim per day, taken BEFORE the pass — CLAUDE.md's retention section and
|
|
514
|
+
// docs/decisions/2026-08-21-log-retention-day-claim.md have the fail-closed reasoning.
|
|
515
|
+
const day = t.slice(0, 10);
|
|
516
|
+
/** @type {number | undefined} */
|
|
517
|
+
let pruned;
|
|
518
|
+
if (claim(dir, `.retention-${day}`)) {
|
|
519
|
+
pruned = pruneDatedLogs(new Date(t)).length;
|
|
520
|
+
}
|
|
521
|
+
// Deleting is work, so it logs itself, AFTER the caller's own fields (CLAUDE.md's "a pass that
|
|
522
|
+
// deleted anything reports it" note) — omitted when nothing was deleted, never zero.
|
|
523
|
+
fs.appendFileSync(
|
|
524
|
+
file,
|
|
525
|
+
JSON.stringify({ t, slug, ...record, harness: harness(), ...(pruned && { pruned }) }) + '\n',
|
|
526
|
+
);
|
|
527
|
+
} catch {
|
|
528
|
+
/* a log that cannot be written must never fail or delay a hook */
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// The dated families, and the only basenames retention may delete. `scripts/doctor.sh` names the
|
|
533
|
+
// same families in a `sed -E` — a shell cannot import this, so keep them in step. A wildcard prefix
|
|
534
|
+
// deleted `backup-2026-01-01.jsonl` here and misread one there (2026-08-21).
|
|
535
|
+
const DATED_LOG = /^(recall|hooks|distill)-(\d{4}-\d{2}-\d{2})\.jsonl$/;
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Retention for the dated JSONL families: keep `logRetentionDays()` days, delete the rest.
|
|
539
|
+
* DELETES, where the vault's log prune only moves — see CLAUDE.md's retention section for why.
|
|
540
|
+
*
|
|
541
|
+
* Cutoff is UTC, from `toISOString()`, the same producer that writes the filenames — the vault
|
|
542
|
+
* pruner's local-by-design `cutoffDate()` was wrong here: `TZ=Pacific/Kiritimati` with retention 0
|
|
543
|
+
* deleted the OTHER family's in-progress file on every append (measured 2026-08-21).
|
|
544
|
+
*
|
|
545
|
+
* First run after a gap is synchronous inside a hook: 150 ms to unlink 1095 stale files, 882 ms
|
|
546
|
+
* for 4686 (macOS/APFS, 2026-08-21), against `hooks.json`'s 10 s timeout. Steady state is free —
|
|
547
|
+
* 5.96 ms/append into an already-pruned dir, inside the noise of `appendFileSync` itself.
|
|
548
|
+
* ponytail: uncapped — cap at N unlinks if a machine ever arrives with a backlog big enough to feel.
|
|
549
|
+
*
|
|
550
|
+
* @param {Date} [now]
|
|
551
|
+
* @returns {string[]} the basenames removed
|
|
552
|
+
*/
|
|
553
|
+
export function pruneDatedLogs(now = new Date()) {
|
|
554
|
+
/** @type {string[]} */
|
|
555
|
+
const removed = [];
|
|
556
|
+
try {
|
|
557
|
+
const dir = stateDir('logs');
|
|
558
|
+
const days = logRetentionDays();
|
|
559
|
+
// Date arithmetic, not `now - days * 86400` — an out-of-range `days` makes an Invalid Date
|
|
560
|
+
// whose toISOString() THROWS, caught below, rather than a `NaN-NaN-NaN` string that sorts
|
|
561
|
+
// above every date and deletes the lot (what cutoffDate()'s own comment records costing it).
|
|
562
|
+
const cutoff = new Date(
|
|
563
|
+
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - days),
|
|
564
|
+
)
|
|
565
|
+
.toISOString()
|
|
566
|
+
.slice(0, 10);
|
|
567
|
+
const today = now.toISOString().slice(0, 10);
|
|
568
|
+
for (const name of fs.readdirSync(dir)) {
|
|
569
|
+
// Anchored on the two families BY NAME, not `[a-z-]+` — that matched and unlinked
|
|
570
|
+
// `backup-*`/`my-notes-export-*` too (measured 2026-08-21); only what we write is ours.
|
|
571
|
+
// Yesterday's day-claim goes with yesterday's logs, so the dotfile doesn't accumulate in
|
|
572
|
+
// the name of not accumulating the log file.
|
|
573
|
+
const c = CLAIM.exec(name);
|
|
574
|
+
if (c) {
|
|
575
|
+
if ((c[1] ?? c[2]) >= today) continue; // today's own claim, or a future one from a wrong clock
|
|
576
|
+
try {
|
|
577
|
+
fs.unlinkSync(path.join(dir, name));
|
|
578
|
+
} catch {
|
|
579
|
+
/* best effort, same as the logs */
|
|
580
|
+
}
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
const m = DATED_LOG.exec(name);
|
|
584
|
+
if (!m || m[2] >= cutoff) continue;
|
|
585
|
+
try {
|
|
586
|
+
fs.unlinkSync(path.join(dir, name));
|
|
587
|
+
removed.push(name);
|
|
588
|
+
} catch {
|
|
589
|
+
/* a log we cannot delete is a log that stays */
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
} catch {
|
|
593
|
+
/* best effort */
|
|
594
|
+
}
|
|
595
|
+
return removed;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The reason every hook logs when it stands down inside a headless child run. */
|
|
599
|
+
export const CHILD_RUN = 'child run';
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* True inside a headless `claude` that one of our heavy hooks spawned. vault-memory-sync.sh reads
|
|
603
|
+
* the same two variables; child-guard.test.mjs runs every entry under each.
|
|
604
|
+
*/
|
|
605
|
+
export const isChildRun = () =>
|
|
606
|
+
Boolean(process.env.CLAUDE_DISTILL_CHILD || process.env.CBM_GRAPHGEN_CHILD);
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Log `child-guard` and return true when this is a child run; the entry then exits before any
|
|
610
|
+
* output (#200).
|
|
611
|
+
*
|
|
612
|
+
* @param {string} hook
|
|
613
|
+
* @param {HookPayload} p
|
|
614
|
+
*/
|
|
615
|
+
export function standDown(hook, p) {
|
|
616
|
+
if (!isChildRun()) return false;
|
|
617
|
+
logHook({
|
|
618
|
+
hook,
|
|
619
|
+
event: String(p.hook_event_name ?? ''),
|
|
620
|
+
cwd: hookCwd(p),
|
|
621
|
+
session: /** @type {string|undefined} */ (p.session_id),
|
|
622
|
+
outcome: 'child-guard',
|
|
623
|
+
reason: CHILD_RUN,
|
|
624
|
+
});
|
|
625
|
+
return true;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** Events that are a cost record for one paid API call, never a hook invocation. */
|
|
629
|
+
export const COST_EVENT = /** @type {const} */ ({ extract: 'extract', judge: 'judge' });
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* The closed set of hook outcomes — a hook that did nothing must be DISTINGUISHABLE from one that
|
|
633
|
+
* ran, since hooks degrade silently by design. `spawned` is a gate line only: the detached child's
|
|
634
|
+
* own line arrives later under the same session id.
|
|
635
|
+
*
|
|
636
|
+
* @typedef {'ran' | 'noop-missing-dep' | 'debounced' | 'child-guard' | 'spawned' | 'error'} HookOutcome
|
|
637
|
+
*/
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* @typedef {{
|
|
641
|
+
* hook: string,
|
|
642
|
+
* event?: string,
|
|
643
|
+
* cwd?: string,
|
|
644
|
+
* session?: string,
|
|
645
|
+
* outcome: HookOutcome,
|
|
646
|
+
* reason?: unknown,
|
|
647
|
+
* extra?: Record<string, unknown>,
|
|
648
|
+
* }} HookLogInput
|
|
649
|
+
*/
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* One line per hook invocation. `extra` is one generic slot, always optional and omitted (never
|
|
653
|
+
* zero) when not measured. `ms` is PROCESS START (CLAUDE.md's "logHook()'s ms" note).
|
|
654
|
+
* @param {HookLogInput} input
|
|
655
|
+
*/
|
|
656
|
+
export function logHook({ hook, event = '', cwd, session, outcome, reason, extra }) {
|
|
657
|
+
const child = isChildRun();
|
|
658
|
+
const machine = Boolean(process.env.MEMORY_MACHINE_RUN);
|
|
659
|
+
appendJsonl('hooks', cwd, {
|
|
660
|
+
// extra FIRST — spread last, a caller could overwrite the four fields the reader judges by.
|
|
661
|
+
...(extra ?? {}),
|
|
662
|
+
hook,
|
|
663
|
+
event,
|
|
664
|
+
ms: +performance.now().toFixed(1),
|
|
665
|
+
outcome,
|
|
666
|
+
...(child ? { child: true } : {}),
|
|
667
|
+
...(machine ? { machine: true } : {}),
|
|
668
|
+
// Omitted rather than null when absent, so a reader can tell "not recorded" from "recorded as
|
|
669
|
+
// empty" — the same omission rule recall's records already follow.
|
|
670
|
+
...(reason == null || reason === '' ? {} : { reason: String(reason).slice(0, 200) }),
|
|
671
|
+
...(session ? { session } : {}),
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Count lines the way `wc -l` does: newline bytes, no string allocation for a large transcript.
|
|
677
|
+
*
|
|
678
|
+
* @param {string} file
|
|
679
|
+
* @returns {number}
|
|
680
|
+
*/
|
|
681
|
+
export function countLines(file) {
|
|
682
|
+
try {
|
|
683
|
+
const buf = fs.readFileSync(file);
|
|
684
|
+
let n = 0;
|
|
685
|
+
for (let i = 0; i < buf.length; i++) if (buf[i] === 0x0a) n++;
|
|
686
|
+
return n;
|
|
687
|
+
} catch {
|
|
688
|
+
return 0;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* A hook's one line of stdout: Claude Code renders `systemMessage` to the user.
|
|
694
|
+
*
|
|
695
|
+
* @param {string} text
|
|
696
|
+
* @returns {string}
|
|
697
|
+
*/
|
|
698
|
+
export function systemMessage(text) {
|
|
699
|
+
return JSON.stringify({ systemMessage: text });
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* SessionStart context: Claude Code reads `hookSpecificOutput`, Copilot CLI only the top-level
|
|
704
|
+
* `additionalContext` and drops plain stdout (#217), and Codex CLI rejects any unknown field, the
|
|
705
|
+
* top-level one included.
|
|
706
|
+
*
|
|
707
|
+
* @param {string} text
|
|
708
|
+
* @returns {string}
|
|
709
|
+
*/
|
|
710
|
+
export function sessionContext(text) {
|
|
711
|
+
return JSON.stringify({
|
|
712
|
+
...(harness() !== 'codex' && { additionalContext: text }),
|
|
713
|
+
hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: text },
|
|
714
|
+
});
|
|
715
|
+
}
|