@empirical-gauzza/cli 1.0.13 → 1.0.15

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.
@@ -1,550 +1,1068 @@
1
- 'use strict';
2
-
3
- const os = require('os');
4
- const path = require('path');
5
- const { log } = require('../ui');
6
- const { ensureDir, writeFile, readJsonIfExists } = require('../fsUtils');
7
- const { normalizePluginNames } = require('./nativePlugin');
8
-
9
- const CLAUDE_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
10
- 'use strict';
11
-
12
- var spawnSync = require('child_process').spawnSync;
13
- var fs = require('fs');
14
- var os = require('os');
15
- var path = require('path');
16
-
17
- // Diagnostic breadcrumb log: this hook's own stdout is only visible to Claude Code's SessionStart
18
- // machinery, not to a human debugging "did this actually fire" after the fact. Every run appends
19
- // one line here (bounded — see trimLogIfLarge) regardless of success/failure, so firing can be
20
- // verified by checking file growth/timestamps after starting or resuming a session, without
21
- // depending on server-side analytics that don't currently tag hook-originated calls.
22
- var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
23
- var MAX_LOG_BYTES = 200 * 1024;
24
-
25
- function appendLog(line) {
26
- try {
27
- fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
28
- fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
29
- var stat = fs.statSync(LOG_PATH);
30
- if (stat.size > MAX_LOG_BYTES) {
31
- var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
32
- fs.writeFileSync(LOG_PATH, tail);
33
- }
34
- } catch (e) {
35
- // Diagnostics must never break session start.
36
- }
37
- }
38
-
39
- // On Windows, npm's global "empirical" command is a .cmd shim, and .cmd/.bat files can only be
40
- // executed via the OS shell (cmd.exe), never as a native process — this is an OS constraint, not
41
- // a Node quirk. But spawnSync's shell:true path joins argv into a single command-line string for
42
- // cmd.exe to reparse, and Node does not escape special shell characters (spaces, commas, etc.) in
43
- // that join for you. A --match value like "project context, conventions, recent decisions, user
44
- // preferences" gets mangled by that reparse, silently truncating the search query and returning
45
- // far fewer/worse matches than the same query run without a shell in between. The fix: resolve
46
- // the shim's REAL target (a plain .js file) and invoke that directly via node.exe with shell:false
47
- // — node.exe is a true native executable, so no shell/reparsing step exists to mangle args.
48
- function resolveEmpiricalEntryPoint() {
49
- if (process.platform !== 'win32') {
50
- // POSIX global installs are usually a symlink straight to the JS entry (or a shebang script)
51
- // — spawnSync already runs these directly without a shell, so no mangling risk exists there.
52
- return null;
53
- }
54
- try {
55
- // Parse the .cmd shim itself rather than hardcoding an npm package scope: the published
56
- // package has already been renamed once (was the empirical scope, now a different scope
57
- // entirely - the old one is 404 on the registry), so hardcoding either name is a guaranteed
58
- // future break. npm-generated shims all reference their target relative to dp0 (the shim's
59
- // own directory) as a node_modules-rooted path ending in bin then a .js file - extracting
60
- // that pattern works regardless of what the package is scoped or renamed to.
61
- var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
62
- if (where.status !== 0 || !where.stdout) return null;
63
- var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
64
- if (!cmdPath || !fs.existsSync(cmdPath)) return null;
65
- var cmdContent = fs.readFileSync(cmdPath, 'utf8');
66
- var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
67
- if (!match) return null;
68
- var candidate = path.join(path.dirname(cmdPath), match[1]);
69
- return fs.existsSync(candidate) ? candidate : null;
70
- } catch (e) {
71
- return null;
72
- }
73
- }
74
-
75
- function commandExists(cmd) {
76
- var probe = process.platform === 'win32'
77
- ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
78
- : spawnSync('which', [cmd], { stdio: 'ignore' });
79
- return probe.status === 0;
80
- }
81
-
82
- function runMemoryQuery(args) {
83
- var entryPoint = resolveEmpiricalEntryPoint();
84
- if (entryPoint) {
85
- appendLog('resolved direct entry point: ' + entryPoint);
86
- return spawnSync(process.execPath, [entryPoint].concat(args), {
87
- encoding: 'utf8',
88
- timeout: 10000,
89
- shell: false
90
- });
91
- }
92
-
93
- // Fallback: could not resolve a direct entry point (non-Windows, or resolution failed) — run
94
- // the "empirical" command as before. On POSIX this is shell:false and safe. On Windows this is
95
- // shell:true and CAN still mangle args as described above; it only triggers if the direct-entry
96
- // resolution above failed, so degraded (not absent) results are the acceptable worst case here.
97
- appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
98
- return spawnSync('empirical', args, {
99
- encoding: 'utf8',
100
- timeout: 10000,
101
- shell: process.platform === 'win32'
102
- });
103
- }
104
-
105
- function main() {
106
- appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
107
-
108
- if (!commandExists('empirical')) {
109
- appendLog('empirical CLI not found on PATH, exiting');
110
- process.exit(0);
111
- }
112
-
113
- var result = runMemoryQuery([
114
- 'memory', 'query',
115
- '--match', 'project context, conventions, recent decisions, user preferences',
116
- '--top-k', '8'
117
- ]);
118
-
119
- if (!result || result.status !== 0 || !result.stdout) {
120
- appendLog('memory query failed or returned no stdout (status=' + (result && result.status) + ', stderr=' + (result && result.stderr ? String(result.stderr).slice(0, 300) : '') + ')');
121
- process.exit(0);
122
- }
123
-
124
- var results;
125
- try {
126
- results = JSON.parse(result.stdout);
127
- } catch (e) {
128
- appendLog('failed to parse memory query stdout as JSON: ' + e.message);
129
- process.exit(0);
130
- }
131
-
132
- if (!Array.isArray(results) || results.length === 0) {
133
- appendLog('memory query returned zero results');
134
- process.exit(0);
135
- }
136
-
137
- appendLog('memory query returned ' + results.length + ' result(s), injecting into session context');
138
-
139
- var lines = results.slice(0, 8).map(function (r) {
140
- var category = r && r.category ? r.category : 'memory';
141
- var summary = r && r.summary ? r.summary : '';
142
- return '- [' + category + '] ' + summary;
143
- });
144
-
145
- console.log('Empirical memory context for this session:\\n' + lines.join('\\n'));
146
- process.exit(0);
147
- }
148
-
149
- main();
150
- `;
151
-
152
- // EMPIRICAL_HOOK_STOP_SOURCE: fires once per assistant turn (Claude: Stop; Codex: Stop, turn-
153
- // scoped per codex-rs/hooks/src/engine/dispatcher.rs; Copilot: agentStop, "the main agent
154
- // finishes a turn" per GitHub's own hooks reference). This is the write-side counterpart to the
155
- // SessionStart hook above (which only covers recall, once per session boundary) - deliberately
156
- // simple: it does NOT parse the transcript to detect whether memory-worthy activity happened
157
- // this turn (transcript formats differ across all three platforms and getting that heuristic
158
- // wrong silently - the exact class of bug this session spent hours finding - is worse than an
159
- // unconditional reminder). It never calls the empirical CLI and makes no network call, so the
160
- // "wasteful per-turn hook" concern that killed the old per-turn UserPromptSubmit hook (see
161
- // installClaudeHooks below) does not apply here - this is a single static stdout write.
162
- // ALWAYS exits 0: per Claude Code's documented Stop hook contract, exit 2 forces the agent to
163
- // keep responding (a blocking decision) - a bug in a hook that's supposed to be an informational
164
- // nudge must never be able to trap a session in a forced-continuation loop, so this is
165
- // unconditional regardless of any error encountered.
166
- const EMPIRICAL_HOOK_STOP_SOURCE = `#!/usr/bin/env node
167
- 'use strict';
168
-
169
- var fs = require('fs');
170
- var os = require('os');
171
- var path = require('path');
172
-
173
- var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
174
- var MAX_LOG_BYTES = 200 * 1024;
175
-
176
- function appendLog(line) {
177
- try {
178
- fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
179
- fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
180
- var stat = fs.statSync(LOG_PATH);
181
- if (stat.size > MAX_LOG_BYTES) {
182
- var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
183
- fs.writeFileSync(LOG_PATH, tail);
184
- }
185
- } catch (e) {
186
- // Diagnostics must never break the hook.
187
- }
188
- }
189
-
190
- function readStdinPayload() {
191
- try {
192
- var raw = fs.readFileSync(0, 'utf8');
193
- return raw ? JSON.parse(raw) : {};
194
- } catch (e) {
195
- return {};
196
- }
197
- }
198
-
199
- function main() {
200
- var payload = readStdinPayload();
201
-
202
- // Defensive loop guard: if a Stop hook's own forced-continuation output somehow triggers
203
- // another Stop event before the agent produces new output, stop_hook_active (Claude's documented
204
- // field name for this) prevents a reminder-print-loop. This hook never sets decision:block
205
- // itself, but checking costs nothing and protects against any future change that does.
206
- if (payload && payload.stop_hook_active === true) {
207
- appendLog('stop_hook_active=true, skipping reminder');
208
- process.exit(0);
209
- }
210
-
211
- appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
212
-
213
- console.log('[Empirical reminder] Before finishing: if this turn included a completed decision, a corrected mistake, or meaningful work worth remembering, record it now via the empirical-memory skill or \`empirical memory record\` - do not wait to be asked.');
214
- process.exit(0);
215
- }
216
-
217
- main();
218
- `;
219
-
220
- // Claude-only variant of the Stop reminder above. hookSpecificOutput.additionalContext (stdout,
221
- // exit 0) is Claude Code's non-blocking Stop-hook feedback channel: the text is fed into context
222
- // and the conversation continues, same outcome the earlier exit-2 approach achieved, but the
223
- // transcript UI renders it as a plain system reminder instead of a red "Stop hook error" line.
224
- // EMPIRICAL_HOOK_STOP_SOURCE above still uses plain console.log + exit 0, which Claude Code treats
225
- // as non-blocking output that's logged but never reaches the model - that was this hook's original
226
- // bug (fixed for Claude here, unconfirmed/unfixed for Codex/Copilot's own Stop/agentStop semantics).
227
- const CLAUDE_HOOK_STOP_SOURCE = `#!/usr/bin/env node
228
- 'use strict';
229
-
230
- var fs = require('fs');
231
- var os = require('os');
232
- var path = require('path');
233
-
234
- var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
235
- var MAX_LOG_BYTES = 200 * 1024;
236
-
237
- function appendLog(line) {
238
- try {
239
- fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
240
- fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
241
- var stat = fs.statSync(LOG_PATH);
242
- if (stat.size > MAX_LOG_BYTES) {
243
- var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
244
- fs.writeFileSync(LOG_PATH, tail);
245
- }
246
- } catch (e) {
247
- // Diagnostics must never break the hook.
248
- }
249
- }
250
-
251
- function readStdinPayload() {
252
- try {
253
- var raw = fs.readFileSync(0, 'utf8');
254
- return raw ? JSON.parse(raw) : {};
255
- } catch (e) {
256
- return {};
257
- }
258
- }
259
-
260
- function main() {
261
- var payload = readStdinPayload();
262
-
263
- // stop_hook_active === true means Claude is re-invoking this hook because a PRIOR Stop hook
264
- // (possibly this same one) already surfaced additionalContext and forced a continuation this
265
- // turn. additionalContext causes the same forced-continuation behavior decision:block does -
266
- // confirmed empirically: without this guard the hook re-fired every ~2-3s in an infinite loop,
267
- // since each additionalContext output triggers another Stop event. Must exit 0 with no output
268
- // here, unconditionally, or the loop continues.
269
- if (payload && payload.stop_hook_active === true) {
270
- appendLog('stop_hook_active=true, skipping reminder (already surfaced once this turn)');
271
- process.exit(0);
272
- }
273
-
274
- appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + '), surfacing reminder via additionalContext');
275
-
276
- process.stdout.write(JSON.stringify({
277
- hookSpecificOutput: {
278
- hookEventName: 'Stop',
279
- additionalContext: '[Empirical] Record memory-worthy work now via empirical-memory skill.'
280
- }
281
- }) + '\\n');
282
- process.exit(0);
283
- }
284
-
285
- main();
286
- `;
287
-
288
- // UserPromptSubmit: fires before each turn is processed (Claude, Codex, and Copilot all support
289
- // this event under the same name per each platform's docs/source). This is the recall-side
290
- // counterpart to Stop's write-side reminder - deliberately a STATIC message, not a live
291
- // `empirical memory query` call: a prior per-turn hook in this codebase was removed for making an
292
- // unconditional network call on every single prompt (see the comment above installClaudeHooks),
293
- // and re-adding that cost here on three platforms at once was an explicit no per product decision.
294
- // The message itself is generated per-install from the actual plugin set being installed, not one
295
- // fixed string for everyone - e.g. someone who declined empirical-scar-tissue at install time
296
- // never sees a scar-tissue reminder, since that capability isn't actually available to them.
297
- function buildPromptReminderMessage(pluginNames) {
298
- const names = normalizePluginNames(pluginNames);
299
- const lines = [
300
- 'Before responding: if this task needs prior context (research, debugging, a spec or status update, a handoff), query Empirical memory first via the empirical-memory skill or empirical memory query - do not assume you already have enough context.'
301
- ];
302
- if (names.includes('empirical-work-history')) {
303
- lines.push('If you are picking up previously completed work, check for a recent work-history entry before assuming there is none.');
304
- }
305
- if (names.includes('empirical-scar-tissue')) {
306
- lines.push('Check for scar tissue before repeating a past mistake in this area.');
307
- }
308
- if (names.includes('empirical-todo')) {
309
- lines.push('If there is an open todo for this project, check it before starting new work.');
310
- }
311
- return '[Empirical reminder] ' + lines.join(' ');
312
- }
313
-
314
- // Builds the full UserPromptSubmit hook script source with the tailored message baked in at
315
- // generation time (via JSON.stringify, so the message is embedded as a single already-escaped
316
- // string literal - substituted through `${}`, not written as raw template-literal source text,
317
- // which is what caused the earlier comment-escaping bug in this same file. Never do the latter).
318
- function buildUserPromptSubmitHookSource(pluginNames) {
319
- const messageLiteral = JSON.stringify(buildPromptReminderMessage(pluginNames));
320
- return `#!/usr/bin/env node
321
- 'use strict';
322
-
323
- var fs = require('fs');
324
- var os = require('os');
325
- var path = require('path');
326
-
327
- var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'user-prompt-submit.log');
328
- var MAX_LOG_BYTES = 200 * 1024;
329
-
330
- function appendLog(line) {
331
- try {
332
- fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
333
- fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
334
- var stat = fs.statSync(LOG_PATH);
335
- if (stat.size > MAX_LOG_BYTES) {
336
- var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
337
- fs.writeFileSync(LOG_PATH, tail);
338
- }
339
- } catch (e) {
340
- // Diagnostics must never break the hook.
341
- }
342
- }
343
-
344
- appendLog('user-prompt-submit hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
345
- console.log(${messageLiteral});
346
- process.exit(0);
347
- `;
348
- }
349
-
350
- function getEmpiricalHooksDir() {
351
- return path.join(os.homedir(), '.empirical', 'hooks');
352
- }
353
-
354
- function buildHookCommand(scriptPath) {
355
- return `"${process.execPath}" "${scriptPath}"`;
356
- }
357
-
358
- function removeEmpiricalHookEntries(entries, scriptPath) {
359
- if (!Array.isArray(entries)) return [];
360
- return entries
361
- .map((entry) => {
362
- if (!entry || !Array.isArray(entry.hooks)) return entry;
363
- const filteredHooks = entry.hooks.filter(
364
- (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
365
- );
366
- return { ...entry, hooks: filteredHooks };
367
- })
368
- .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
369
- }
370
-
371
- function installClaudeHooks(pluginNames) {
372
- const hooksDir = getEmpiricalHooksDir();
373
- ensureDir(hooksDir);
374
-
375
- // A prior version of this hook made an unconditional `empirical memory query` network call on
376
- // every single prompt and was removed for being wasteful (see git history). This is a
377
- // deliberate reintroduction at the SAME script path, but with fundamentally different content:
378
- // a static, install-time-generated reminder with no network call at all - the cost concern that
379
- // killed the old version does not apply to a plain stdout write.
380
- const userPromptScriptPath = path.join(hooksDir, 'claude-user-prompt-submit.js');
381
- const sessionStartScriptPath = path.join(hooksDir, 'claude-session-start.js');
382
- const stopScriptPath = path.join(hooksDir, 'claude-stop.js');
383
- writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
384
- writeFile(stopScriptPath, CLAUDE_HOOK_STOP_SOURCE);
385
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
386
-
387
- const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
388
- const settings = readJsonIfExists(settingsPath) || {};
389
- if (!settings.hooks || typeof settings.hooks !== 'object') {
390
- settings.hooks = {};
391
- }
392
-
393
- settings.hooks.UserPromptSubmit = removeEmpiricalHookEntries(settings.hooks.UserPromptSubmit, userPromptScriptPath);
394
- settings.hooks.UserPromptSubmit.push({
395
- hooks: [{ type: 'command', command: buildHookCommand(userPromptScriptPath), timeout: 10 }]
396
- });
397
-
398
- settings.hooks.SessionStart = removeEmpiricalHookEntries(settings.hooks.SessionStart, sessionStartScriptPath);
399
- for (const matcher of ['startup', 'resume', 'compact']) {
400
- settings.hooks.SessionStart.push({
401
- matcher,
402
- hooks: [{ type: 'command', command: buildHookCommand(sessionStartScriptPath), timeout: 15 }]
403
- });
404
- }
405
-
406
- settings.hooks.Stop = removeEmpiricalHookEntries(settings.hooks.Stop, stopScriptPath);
407
- settings.hooks.Stop.push({
408
- hooks: [{ type: 'command', command: buildHookCommand(stopScriptPath), timeout: 10 }]
409
- });
410
-
411
- writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
412
- log(' - Claude SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
413
- }
414
-
415
- // Codex CLI ships a real hooks system (confirmed against openai/codex source — codex-rs/hooks,
416
- // codex-rs/config/src/hook_config.rs — not assumed from docs alone, since third-party writeups
417
- // disagreed on Windows support). It reads <CODEX_HOME>/hooks.json (JSON, not the config.toml
418
- // used for MCP/model settings — a separate file, so this never touches config.toml) shaped as
419
- // { hooks: { SessionStart: [{ matcher, hooks: [{ type: 'command', command, commandWindows,
420
- // timeout }] }], ... } }. CODEX_HOME defaults to ~/.codex when unset, same convention as
421
- // ~/.claude for Claude Code.
422
- function getCodexHomeDir() {
423
- return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
424
- }
425
-
426
- function removeEmpiricalHooksJsonEntries(entries, scriptPath) {
427
- if (!Array.isArray(entries)) return [];
428
- return entries
429
- .map((entry) => {
430
- if (!entry || !Array.isArray(entry.hooks)) return entry;
431
- const filteredHooks = entry.hooks.filter(
432
- (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
433
- );
434
- return { ...entry, hooks: filteredHooks };
435
- })
436
- .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
437
- }
438
-
439
- function installCodexHooks(pluginNames) {
440
- const hooksDir = getEmpiricalHooksDir();
441
- ensureDir(hooksDir);
442
-
443
- const sessionStartScriptPath = path.join(hooksDir, 'codex-session-start.js');
444
- const stopScriptPath = path.join(hooksDir, 'codex-stop.js');
445
- const userPromptScriptPath = path.join(hooksDir, 'codex-user-prompt-submit.js');
446
- writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
447
- writeFile(stopScriptPath, EMPIRICAL_HOOK_STOP_SOURCE);
448
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
449
-
450
- const hooksJsonPath = path.join(getCodexHomeDir(), 'hooks.json');
451
- const hooksFile = readJsonIfExists(hooksJsonPath) || {};
452
- if (!hooksFile.hooks || typeof hooksFile.hooks !== 'object') {
453
- hooksFile.hooks = {};
454
- }
455
-
456
- hooksFile.hooks.SessionStart = removeEmpiricalHooksJsonEntries(hooksFile.hooks.SessionStart, sessionStartScriptPath);
457
- const sessionStartCommand = buildHookCommand(sessionStartScriptPath);
458
- for (const matcher of ['startup', 'resume']) {
459
- hooksFile.hooks.SessionStart.push({
460
- matcher,
461
- hooks: [{ type: 'command', command: sessionStartCommand, commandWindows: sessionStartCommand, timeout: 15 }]
462
- });
463
- }
464
-
465
- hooksFile.hooks.Stop = removeEmpiricalHooksJsonEntries(hooksFile.hooks.Stop, stopScriptPath);
466
- const stopCommand = buildHookCommand(stopScriptPath);
467
- hooksFile.hooks.Stop.push({
468
- hooks: [{ type: 'command', command: stopCommand, commandWindows: stopCommand, timeout: 10 }]
469
- });
470
-
471
- // Confirmed against codex-rs/config/src/hook_config.rs's HookEventsToml serde renames: the
472
- // config-file key is PascalCase "UserPromptSubmit", same casing convention as SessionStart/Stop.
473
- hooksFile.hooks.UserPromptSubmit = removeEmpiricalHooksJsonEntries(hooksFile.hooks.UserPromptSubmit, userPromptScriptPath);
474
- const userPromptCommand = buildHookCommand(userPromptScriptPath);
475
- hooksFile.hooks.UserPromptSubmit.push({
476
- hooks: [{ type: 'command', command: userPromptCommand, commandWindows: userPromptCommand, timeout: 10 }]
477
- });
478
-
479
- writeFile(hooksJsonPath, `${JSON.stringify(hooksFile, null, 2)}\n`);
480
- log(' - Codex SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
481
- }
482
-
483
- // GitHub Copilot CLI's hook config is one JSON file per hook under ~/.copilot/hooks/ (any
484
- // filename — confirmed via GitHub's own docs at docs.github.com/en/copilot/reference/hooks-
485
- // reference), so unlike Claude/Codex this never needs to merge into a shared file: Empirical
486
- // owns this file outright and can just overwrite it. Event key for turn-end is "agentStop"
487
- // ("the main agent finishes a turn" per the same docs) — not "stop"/"Stop" like Claude/Codex.
488
- // Schema: { version: 1, hooks: { sessionStart: [...], agentStop: [...] } }.
489
- function installCopilotHooks(pluginNames) {
490
- const hooksDir = getEmpiricalHooksDir();
491
- ensureDir(hooksDir);
492
-
493
- const sessionStartScriptPath = path.join(hooksDir, 'copilot-session-start.js');
494
- const stopScriptPath = path.join(hooksDir, 'copilot-stop.js');
495
- const userPromptScriptPath = path.join(hooksDir, 'copilot-user-prompt-submit.js');
496
- writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
497
- writeFile(stopScriptPath, EMPIRICAL_HOOK_STOP_SOURCE);
498
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
499
-
500
- const copilotHooksDir = path.join(os.homedir(), '.copilot', 'hooks');
501
- ensureDir(copilotHooksDir);
502
-
503
- // Prior versions of this installer wrote a single-purpose "empirical-session-start.json" —
504
- // remove it now that both events live in one unified file, so a stale duplicate registration
505
- // never lingers alongside the new one.
506
- const legacyHookFilePath = path.join(copilotHooksDir, 'empirical-session-start.json');
507
- try {
508
- const fs = require('fs');
509
- if (fs.existsSync(legacyHookFilePath)) fs.unlinkSync(legacyHookFilePath);
510
- } catch (_error) {
511
- // best-effort cleanup only
512
- }
513
-
514
- const hookFilePath = path.join(copilotHooksDir, 'empirical-hooks.json');
515
- const hookFileContent = {
516
- version: 1,
517
- hooks: {
518
- sessionStart: [
519
- { type: 'command', command: buildHookCommand(sessionStartScriptPath), timeoutSec: 15 }
520
- ],
521
- // "userPromptSubmitted" per GitHub's hooks reference ("The user submits a prompt") - not
522
- // "userPromptSubmit" (that camelCase spelling is Claude/Codex's convention, not Copilot's).
523
- userPromptSubmitted: [
524
- { type: 'command', command: buildHookCommand(userPromptScriptPath), timeoutSec: 10 }
525
- ],
526
- agentStop: [
527
- { type: 'command', command: buildHookCommand(stopScriptPath), timeoutSec: 10 }
528
- ]
529
- }
530
- };
531
-
532
- writeFile(hookFilePath, `${JSON.stringify(hookFileContent, null, 2)}\n`);
533
- log(' - Copilot SessionStart + userPromptSubmitted + agentStop hooks installed for deterministic memory lookups and reminders.');
534
- }
535
-
536
- module.exports = {
537
- CLAUDE_HOOK_SESSION_START_SOURCE,
538
- EMPIRICAL_HOOK_STOP_SOURCE,
539
- CLAUDE_HOOK_STOP_SOURCE,
540
- buildPromptReminderMessage,
541
- buildUserPromptSubmitHookSource,
542
- getEmpiricalHooksDir,
543
- buildHookCommand,
544
- removeEmpiricalHookEntries,
545
- installClaudeHooks,
546
- getCodexHomeDir,
547
- removeEmpiricalHooksJsonEntries,
548
- installCodexHooks,
549
- installCopilotHooks
550
- };
1
+ 'use strict';
2
+
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const { log } = require('../ui');
6
+ const { ensureDir, writeFile, readJsonIfExists } = require('../fsUtils');
7
+ const { normalizePluginNames } = require('./nativePlugin');
8
+
9
+ const CLAUDE_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
10
+ 'use strict';
11
+
12
+ var spawnSync = require('child_process').spawnSync;
13
+ var fs = require('fs');
14
+ var os = require('os');
15
+ var path = require('path');
16
+
17
+ // Diagnostic breadcrumb log: this hook's own stdout is only visible to Claude Code's SessionStart
18
+ // machinery, not to a human debugging "did this actually fire" after the fact. Every run appends
19
+ // one line here (bounded — see trimLogIfLarge) regardless of success/failure, so firing can be
20
+ // verified by checking file growth/timestamps after starting or resuming a session, without
21
+ // depending on server-side analytics that don't currently tag hook-originated calls.
22
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
23
+ var MAX_LOG_BYTES = 200 * 1024;
24
+
25
+ function appendLog(line) {
26
+ try {
27
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
28
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
29
+ var stat = fs.statSync(LOG_PATH);
30
+ if (stat.size > MAX_LOG_BYTES) {
31
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
32
+ fs.writeFileSync(LOG_PATH, tail);
33
+ }
34
+ } catch (e) {
35
+ // Diagnostics must never break session start.
36
+ }
37
+ }
38
+
39
+ // On Windows, npm's global "empirical" command is a .cmd shim, and .cmd/.bat files can only be
40
+ // executed via the OS shell (cmd.exe), never as a native process — this is an OS constraint, not
41
+ // a Node quirk. But spawnSync's shell:true path joins argv into a single command-line string for
42
+ // cmd.exe to reparse, and Node does not escape special shell characters (spaces, commas, etc.) in
43
+ // that join for you. A --match value like "project context, conventions, recent decisions, user
44
+ // preferences" gets mangled by that reparse, silently truncating the search query and returning
45
+ // far fewer/worse matches than the same query run without a shell in between. The fix: resolve
46
+ // the shim's REAL target (a plain .js file) and invoke that directly via node.exe with shell:false
47
+ // — node.exe is a true native executable, so no shell/reparsing step exists to mangle args.
48
+ function resolveEmpiricalEntryPoint() {
49
+ if (process.platform !== 'win32') {
50
+ // POSIX global installs are usually a symlink straight to the JS entry (or a shebang script)
51
+ // — spawnSync already runs these directly without a shell, so no mangling risk exists there.
52
+ return null;
53
+ }
54
+ try {
55
+ // Parse the .cmd shim itself rather than hardcoding an npm package scope: the published
56
+ // package has already been renamed once (was the empirical scope, now a different scope
57
+ // entirely - the old one is 404 on the registry), so hardcoding either name is a guaranteed
58
+ // future break. npm-generated shims all reference their target relative to dp0 (the shim's
59
+ // own directory) as a node_modules-rooted path ending in bin then a .js file - extracting
60
+ // that pattern works regardless of what the package is scoped or renamed to.
61
+ var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
62
+ if (where.status !== 0 || !where.stdout) return null;
63
+ var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
64
+ if (!cmdPath || !fs.existsSync(cmdPath)) return null;
65
+ var cmdContent = fs.readFileSync(cmdPath, 'utf8');
66
+ var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
67
+ if (!match) return null;
68
+ var candidate = path.join(path.dirname(cmdPath), match[1]);
69
+ return fs.existsSync(candidate) ? candidate : null;
70
+ } catch (e) {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ function commandExists(cmd) {
76
+ var probe = process.platform === 'win32'
77
+ ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
78
+ : spawnSync('which', [cmd], { stdio: 'ignore' });
79
+ return probe.status === 0;
80
+ }
81
+
82
+ function runMemoryQuery(args) {
83
+ var entryPoint = resolveEmpiricalEntryPoint();
84
+ if (entryPoint) {
85
+ appendLog('resolved direct entry point: ' + entryPoint);
86
+ return spawnSync(process.execPath, [entryPoint].concat(args), {
87
+ encoding: 'utf8',
88
+ timeout: 10000,
89
+ shell: false
90
+ });
91
+ }
92
+
93
+ // Fallback: could not resolve a direct entry point (non-Windows, or resolution failed) — run
94
+ // the "empirical" command as before. On POSIX this is shell:false and safe. On Windows this is
95
+ // shell:true and CAN still mangle args as described above; it only triggers if the direct-entry
96
+ // resolution above failed, so degraded (not absent) results are the acceptable worst case here.
97
+ appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
98
+ return spawnSync('empirical', args, {
99
+ encoding: 'utf8',
100
+ timeout: 10000,
101
+ shell: process.platform === 'win32'
102
+ });
103
+ }
104
+
105
+ function main() {
106
+ appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
107
+
108
+ if (!commandExists('empirical')) {
109
+ appendLog('empirical CLI not found on PATH, exiting');
110
+ process.exit(0);
111
+ }
112
+
113
+ var result = runMemoryQuery([
114
+ 'memory', 'query',
115
+ '--match', 'project context, conventions, recent decisions, user preferences',
116
+ '--top-k', '8'
117
+ ]);
118
+
119
+ if (!result || result.status !== 0 || !result.stdout) {
120
+ appendLog('memory query failed or returned no stdout (status=' + (result && result.status) + ', stderr=' + (result && result.stderr ? String(result.stderr).slice(0, 300) : '') + ')');
121
+ process.exit(0);
122
+ }
123
+
124
+ var results;
125
+ try {
126
+ results = JSON.parse(result.stdout);
127
+ } catch (e) {
128
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
129
+ process.exit(0);
130
+ }
131
+
132
+ if (!Array.isArray(results) || results.length === 0) {
133
+ appendLog('memory query returned zero results');
134
+ process.exit(0);
135
+ }
136
+
137
+ appendLog('memory query returned ' + results.length + ' result(s), injecting into session context');
138
+
139
+ var lines = results.slice(0, 8).map(function (r) {
140
+ var category = r && r.category ? r.category : 'memory';
141
+ var summary = r && r.summary ? r.summary : '';
142
+ return '- [' + category + '] ' + summary;
143
+ });
144
+
145
+ console.log('Empirical memory context for this session:\\n' + lines.join('\\n'));
146
+ process.exit(0);
147
+ }
148
+
149
+ // Hooks must never surface as a hard failure to the host CLI (Codex/Claude/Copilot all render a
150
+ // nonzero exit as a red "hook failed" error) - an uncaught exception anywhere above (e.g. an
151
+ // environment that denies process spawn or fs access, such as Codex's experimental Windows
152
+ // sandbox) must degrade to a silent no-op, not a visible crash.
153
+ try {
154
+ main();
155
+ } catch (e) {
156
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
157
+ process.exit(0);
158
+ }
159
+ `;
160
+
161
+ // Codex-only variant of the SessionStart hook above. Confirmed live (2026-08-08, via a real
162
+ // `codex exec` run) that Codex requires valid JSON on stdout for a hook's output to actually
163
+ // register/display - plain text (what CLAUDE_HOOK_SESSION_START_SOURCE emits, which Claude Code
164
+ // handles fine) makes Codex report the hook as failed. Uses the same hookSpecificOutput.
165
+ // additionalContext shape Claude's own JSON-output hooks use (see CLAUDE_HOOK_STOP_SOURCE below) -
166
+ // confirmed accepted by Codex's SessionStart handler specifically. Otherwise byte-identical to
167
+ // CLAUDE_HOOK_SESSION_START_SOURCE; keep any future logic changes in sync between the two.
168
+ const CODEX_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
169
+ 'use strict';
170
+
171
+ var spawnSync = require('child_process').spawnSync;
172
+ var fs = require('fs');
173
+ var os = require('os');
174
+ var path = require('path');
175
+
176
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
177
+ var MAX_LOG_BYTES = 200 * 1024;
178
+
179
+ function appendLog(line) {
180
+ try {
181
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
182
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
183
+ var stat = fs.statSync(LOG_PATH);
184
+ if (stat.size > MAX_LOG_BYTES) {
185
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
186
+ fs.writeFileSync(LOG_PATH, tail);
187
+ }
188
+ } catch (e) {
189
+ // Diagnostics must never break session start.
190
+ }
191
+ }
192
+
193
+ function resolveEmpiricalEntryPoint() {
194
+ if (process.platform !== 'win32') {
195
+ return null;
196
+ }
197
+ try {
198
+ var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
199
+ if (where.status !== 0 || !where.stdout) return null;
200
+ var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
201
+ if (!cmdPath || !fs.existsSync(cmdPath)) return null;
202
+ var cmdContent = fs.readFileSync(cmdPath, 'utf8');
203
+ var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
204
+ if (!match) return null;
205
+ var candidate = path.join(path.dirname(cmdPath), match[1]);
206
+ return fs.existsSync(candidate) ? candidate : null;
207
+ } catch (e) {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ function commandExists(cmd) {
213
+ var probe = process.platform === 'win32'
214
+ ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
215
+ : spawnSync('which', [cmd], { stdio: 'ignore' });
216
+ return probe.status === 0;
217
+ }
218
+
219
+ function runMemoryQuery(args) {
220
+ var entryPoint = resolveEmpiricalEntryPoint();
221
+ if (entryPoint) {
222
+ appendLog('resolved direct entry point: ' + entryPoint);
223
+ return spawnSync(process.execPath, [entryPoint].concat(args), {
224
+ encoding: 'utf8',
225
+ timeout: 10000,
226
+ shell: false
227
+ });
228
+ }
229
+
230
+ appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
231
+ return spawnSync('empirical', args, {
232
+ encoding: 'utf8',
233
+ timeout: 10000,
234
+ shell: process.platform === 'win32'
235
+ });
236
+ }
237
+
238
+ function main() {
239
+ appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
240
+
241
+ if (!commandExists('empirical')) {
242
+ appendLog('empirical CLI not found on PATH, exiting');
243
+ process.exit(0);
244
+ }
245
+
246
+ var result = runMemoryQuery([
247
+ 'memory', 'query',
248
+ '--match', 'project context, conventions, recent decisions, user preferences',
249
+ '--top-k', '8'
250
+ ]);
251
+
252
+ if (!result || result.status !== 0 || !result.stdout) {
253
+ appendLog('memory query failed or returned no stdout (status=' + (result && result.status) + ', stderr=' + (result && result.stderr ? String(result.stderr).slice(0, 300) : '') + ')');
254
+ process.exit(0);
255
+ }
256
+
257
+ var results;
258
+ try {
259
+ results = JSON.parse(result.stdout);
260
+ } catch (e) {
261
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
262
+ process.exit(0);
263
+ }
264
+
265
+ if (!Array.isArray(results) || results.length === 0) {
266
+ appendLog('memory query returned zero results');
267
+ process.exit(0);
268
+ }
269
+
270
+ appendLog('memory query returned ' + results.length + ' result(s), injecting into session context');
271
+
272
+ var lines = results.slice(0, 8).map(function (r) {
273
+ var category = r && r.category ? r.category : 'memory';
274
+ var summary = r && r.summary ? r.summary : '';
275
+ return '- [' + category + '] ' + summary;
276
+ });
277
+
278
+ console.log(JSON.stringify({
279
+ hookSpecificOutput: {
280
+ hookEventName: 'SessionStart',
281
+ additionalContext: 'Empirical memory context for this session:\\n' + lines.join('\\n')
282
+ }
283
+ }));
284
+ process.exit(0);
285
+ }
286
+
287
+ try {
288
+ main();
289
+ } catch (e) {
290
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
291
+ process.exit(0);
292
+ }
293
+ `;
294
+
295
+ // Copilot-only variant of the SessionStart hook. Per GitHub's own hooks reference (fetched
296
+ // 2026-08-08): unlike Claude/Codex, Copilot's sessionStart event has NO output mechanism at all
297
+ // - there is no additionalContext-equivalent field, so a hook cannot inject memory context into
298
+ // the session this way, full stop (this is a genuine platform limitation, not a bug to work
299
+ // around). Separately, Copilot requires ALL hook stdout to be valid JSON parsed via a single
300
+ // JSON.parse call - plain text (fine for Claude, and previously assumed fine here too) is
301
+ // invalid and makes Copilot log a hook execution failure. So this variant still runs the memory
302
+ // query and logs the result for diagnostic/audit purposes, but emits {} (empty, valid JSON,
303
+ // explicitly documented as "use defaults") instead of attempting to inject anything.
304
+ const COPILOT_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
305
+ 'use strict';
306
+
307
+ var spawnSync = require('child_process').spawnSync;
308
+ var fs = require('fs');
309
+ var os = require('os');
310
+ var path = require('path');
311
+
312
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
313
+ var MAX_LOG_BYTES = 200 * 1024;
314
+
315
+ function appendLog(line) {
316
+ try {
317
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
318
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
319
+ var stat = fs.statSync(LOG_PATH);
320
+ if (stat.size > MAX_LOG_BYTES) {
321
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
322
+ fs.writeFileSync(LOG_PATH, tail);
323
+ }
324
+ } catch (e) {
325
+ // Diagnostics must never break session start.
326
+ }
327
+ }
328
+
329
+ function resolveEmpiricalEntryPoint() {
330
+ if (process.platform !== 'win32') {
331
+ return null;
332
+ }
333
+ try {
334
+ var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
335
+ if (where.status !== 0 || !where.stdout) return null;
336
+ var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
337
+ if (!cmdPath || !fs.existsSync(cmdPath)) return null;
338
+ var cmdContent = fs.readFileSync(cmdPath, 'utf8');
339
+ var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
340
+ if (!match) return null;
341
+ var candidate = path.join(path.dirname(cmdPath), match[1]);
342
+ return fs.existsSync(candidate) ? candidate : null;
343
+ } catch (e) {
344
+ return null;
345
+ }
346
+ }
347
+
348
+ function commandExists(cmd) {
349
+ var probe = process.platform === 'win32'
350
+ ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
351
+ : spawnSync('which', [cmd], { stdio: 'ignore' });
352
+ return probe.status === 0;
353
+ }
354
+
355
+ function runMemoryQuery(args) {
356
+ var entryPoint = resolveEmpiricalEntryPoint();
357
+ if (entryPoint) {
358
+ appendLog('resolved direct entry point: ' + entryPoint);
359
+ return spawnSync(process.execPath, [entryPoint].concat(args), {
360
+ encoding: 'utf8',
361
+ timeout: 10000,
362
+ shell: false
363
+ });
364
+ }
365
+
366
+ appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
367
+ return spawnSync('empirical', args, {
368
+ encoding: 'utf8',
369
+ timeout: 10000,
370
+ shell: process.platform === 'win32'
371
+ });
372
+ }
373
+
374
+ function main() {
375
+ appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
376
+
377
+ if (!commandExists('empirical')) {
378
+ appendLog('empirical CLI not found on PATH, exiting');
379
+ console.log('{}');
380
+ process.exit(0);
381
+ }
382
+
383
+ var result = runMemoryQuery([
384
+ 'memory', 'query',
385
+ '--match', 'project context, conventions, recent decisions, user preferences',
386
+ '--top-k', '8'
387
+ ]);
388
+
389
+ if (!result || result.status !== 0 || !result.stdout) {
390
+ appendLog('memory query failed or returned no stdout (status=' + (result && result.status) + ', stderr=' + (result && result.stderr ? String(result.stderr).slice(0, 300) : '') + ')');
391
+ console.log('{}');
392
+ process.exit(0);
393
+ }
394
+
395
+ var results;
396
+ try {
397
+ results = JSON.parse(result.stdout);
398
+ } catch (e) {
399
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
400
+ console.log('{}');
401
+ process.exit(0);
402
+ }
403
+
404
+ if (!Array.isArray(results) || results.length === 0) {
405
+ appendLog('memory query returned zero results');
406
+ console.log('{}');
407
+ process.exit(0);
408
+ }
409
+
410
+ var lines = results.slice(0, 8).map(function (r) {
411
+ var category = r && r.category ? r.category : 'memory';
412
+ var summary = r && r.summary ? r.summary : '';
413
+ return '- [' + category + '] ' + summary;
414
+ });
415
+
416
+ // Logged only - Copilot's sessionStart event has no field that surfaces this to the model.
417
+ appendLog('memory query returned ' + results.length + ' result(s) (session-start has no output channel to inject them, logged only): ' + lines.join(' | '));
418
+ console.log('{}');
419
+ process.exit(0);
420
+ }
421
+
422
+ try {
423
+ main();
424
+ } catch (e) {
425
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
426
+ console.log('{}');
427
+ process.exit(0);
428
+ }
429
+ `;
430
+
431
+ // Codex-only variant of the Stop reminder. Confirmed live (2026-08-08, via a real `codex
432
+ // exec` run) that Codex's Stop hook specifically requires a { systemMessage: "..." } JSON shape
433
+ // on stdout - plain text makes Codex report the hook as failed. Distinct from Claude's own JSON
434
+ // shape (hookSpecificOutput.additionalContext, see CLAUDE_HOOK_STOP_SOURCE below) and Copilot's
435
+ // (decision/reason, see COPILOT_HOOK_STOP_SOURCE) - each host has its own schema here.
436
+ const CODEX_HOOK_STOP_SOURCE = `#!/usr/bin/env node
437
+ 'use strict';
438
+
439
+ var fs = require('fs');
440
+ var os = require('os');
441
+ var path = require('path');
442
+
443
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
444
+ var MAX_LOG_BYTES = 200 * 1024;
445
+
446
+ function appendLog(line) {
447
+ try {
448
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
449
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
450
+ var stat = fs.statSync(LOG_PATH);
451
+ if (stat.size > MAX_LOG_BYTES) {
452
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
453
+ fs.writeFileSync(LOG_PATH, tail);
454
+ }
455
+ } catch (e) {
456
+ // Diagnostics must never break the hook.
457
+ }
458
+ }
459
+
460
+ function readStdinPayload() {
461
+ try {
462
+ var raw = fs.readFileSync(0, 'utf8');
463
+ return raw ? JSON.parse(raw) : {};
464
+ } catch (e) {
465
+ return {};
466
+ }
467
+ }
468
+
469
+ function main() {
470
+ var payload = readStdinPayload();
471
+
472
+ if (payload && payload.stop_hook_active === true) {
473
+ appendLog('stop_hook_active=true, skipping reminder');
474
+ process.exit(0);
475
+ }
476
+
477
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
478
+
479
+ console.log(JSON.stringify({
480
+ systemMessage: '[Empirical reminder] Before finishing: if this turn included a completed decision, a corrected mistake, or meaningful work worth remembering, record it now via the empirical-memory skill or \`empirical memory record\` - do not wait to be asked.'
481
+ }));
482
+ process.exit(0);
483
+ }
484
+
485
+ try {
486
+ main();
487
+ } catch (e) {
488
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
489
+ process.exit(0);
490
+ }
491
+ `;
492
+
493
+ // Copilot-only variant of the Stop reminder above. Per GitHub's own hooks reference (fetched
494
+ // 2026-08-08): agentStop's output schema is { decision: "block"|"allow", reason, modifiedResponse }
495
+ // - there is no plain message field, so surfacing a reminder means returning decision:"block"
496
+ // with reason as the forced-continuation prompt text. Confirmed this has the same loop-prevention
497
+ // contract Claude Code uses: the input payload includes stop_hook_active ("true when this turn
498
+ // was already forced to continue by a prior 'block' decision" - same semantics, same field name
499
+ // as Claude's), and Copilot has its own hard backstop besides ("After 8 consecutive block
500
+ // continuations, the CLI overrides the hook and ends the turn anyway"). Checking stop_hook_active
501
+ // here means this hook only ever forces one continuation, never chains into that backstop.
502
+ const COPILOT_HOOK_STOP_SOURCE = `#!/usr/bin/env node
503
+ 'use strict';
504
+
505
+ var fs = require('fs');
506
+ var os = require('os');
507
+ var path = require('path');
508
+
509
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
510
+ var MAX_LOG_BYTES = 200 * 1024;
511
+
512
+ function appendLog(line) {
513
+ try {
514
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
515
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
516
+ var stat = fs.statSync(LOG_PATH);
517
+ if (stat.size > MAX_LOG_BYTES) {
518
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
519
+ fs.writeFileSync(LOG_PATH, tail);
520
+ }
521
+ } catch (e) {
522
+ // Diagnostics must never break the hook.
523
+ }
524
+ }
525
+
526
+ function readStdinPayload() {
527
+ try {
528
+ var raw = fs.readFileSync(0, 'utf8');
529
+ return raw ? JSON.parse(raw) : {};
530
+ } catch (e) {
531
+ return {};
532
+ }
533
+ }
534
+
535
+ function main() {
536
+ var payload = readStdinPayload();
537
+
538
+ if (payload && payload.stop_hook_active === true) {
539
+ appendLog('stop_hook_active=true, skipping reminder (already forced one continuation this turn)');
540
+ console.log('{}');
541
+ process.exit(0);
542
+ }
543
+
544
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + '), forcing one continuation to surface reminder');
545
+
546
+ console.log(JSON.stringify({
547
+ decision: 'block',
548
+ reason: '[Empirical reminder] Before finishing: if this turn included a completed decision, a corrected mistake, or meaningful work worth remembering, record it now via the empirical-memory skill or \`empirical memory record\` - do not wait to be asked.'
549
+ }));
550
+ process.exit(0);
551
+ }
552
+
553
+ try {
554
+ main();
555
+ } catch (e) {
556
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
557
+ console.log('{}');
558
+ process.exit(0);
559
+ }
560
+ `;
561
+
562
+ // Claude-only variant of the Stop reminder above. hookSpecificOutput.additionalContext (stdout,
563
+ // exit 0) is Claude Code's non-blocking Stop-hook feedback channel: the text is fed into context
564
+ // and the conversation continues, same outcome the earlier exit-2 approach achieved, but the
565
+ // transcript UI renders it as a plain system reminder instead of a red "Stop hook error" line.
566
+ // Codex needs its own systemMessage shape (CODEX_HOOK_STOP_SOURCE) and Copilot its own
567
+ // decision/reason shape (COPILOT_HOOK_STOP_SOURCE) - plain console.log output (what this hook
568
+ // used before the additionalContext fix) never reaches the model on any of the three hosts.
569
+ const CLAUDE_HOOK_STOP_SOURCE = `#!/usr/bin/env node
570
+ 'use strict';
571
+
572
+ var fs = require('fs');
573
+ var os = require('os');
574
+ var path = require('path');
575
+
576
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
577
+ var MAX_LOG_BYTES = 200 * 1024;
578
+
579
+ function appendLog(line) {
580
+ try {
581
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
582
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
583
+ var stat = fs.statSync(LOG_PATH);
584
+ if (stat.size > MAX_LOG_BYTES) {
585
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
586
+ fs.writeFileSync(LOG_PATH, tail);
587
+ }
588
+ } catch (e) {
589
+ // Diagnostics must never break the hook.
590
+ }
591
+ }
592
+
593
+ function readStdinPayload() {
594
+ try {
595
+ var raw = fs.readFileSync(0, 'utf8');
596
+ return raw ? JSON.parse(raw) : {};
597
+ } catch (e) {
598
+ return {};
599
+ }
600
+ }
601
+
602
+ function main() {
603
+ var payload = readStdinPayload();
604
+
605
+ // stop_hook_active === true means Claude is re-invoking this hook because a PRIOR Stop hook
606
+ // (possibly this same one) already surfaced additionalContext and forced a continuation this
607
+ // turn. additionalContext causes the same forced-continuation behavior decision:block does -
608
+ // confirmed empirically: without this guard the hook re-fired every ~2-3s in an infinite loop,
609
+ // since each additionalContext output triggers another Stop event. Must exit 0 with no output
610
+ // here, unconditionally, or the loop continues.
611
+ if (payload && payload.stop_hook_active === true) {
612
+ appendLog('stop_hook_active=true, skipping reminder (already surfaced once this turn)');
613
+ process.exit(0);
614
+ }
615
+
616
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + '), surfacing reminder via additionalContext');
617
+
618
+ process.stdout.write(JSON.stringify({
619
+ hookSpecificOutput: {
620
+ hookEventName: 'Stop',
621
+ additionalContext: '[Empirical] Record memory-worthy work now via empirical-memory skill.'
622
+ }
623
+ }) + '\\n');
624
+ process.exit(0);
625
+ }
626
+
627
+ // See EMPIRICAL_HOOK_SESSION_START_SOURCE's identical guard: a crash here must degrade to a
628
+ // silent no-op, never a visible "hook failed" error in the host CLI.
629
+ try {
630
+ main();
631
+ } catch (e) {
632
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
633
+ process.exit(0);
634
+ }
635
+ `;
636
+
637
+ // UserPromptSubmit: fires before each turn is processed (Claude, Codex, and Copilot all support
638
+ // this event under the same name per each platform's docs/source). This is the recall-side
639
+ // counterpart to Stop's write-side reminder - deliberately a STATIC message, not a live
640
+ // `empirical memory query` call: a prior per-turn hook in this codebase was removed for making an
641
+ // unconditional network call on every single prompt (see the comment above installClaudeHooks),
642
+ // and re-adding that cost here on three platforms at once was an explicit no per product decision.
643
+ // The message itself is generated per-install from the actual plugin set being installed, not one
644
+ // fixed string for everyone - e.g. someone who declined empirical-scar-tissue at install time
645
+ // never sees a scar-tissue reminder, since that capability isn't actually available to them.
646
+ function buildPromptReminderMessage(pluginNames) {
647
+ const names = normalizePluginNames(pluginNames);
648
+ const lines = [
649
+ 'Before responding: if this task needs prior context (research, debugging, a spec or status update, a handoff), query Empirical memory first via the empirical-memory skill or empirical memory query - do not assume you already have enough context.'
650
+ ];
651
+ if (names.includes('empirical-work-history')) {
652
+ lines.push('If you are picking up previously completed work, check for a recent work-history entry before assuming there is none.');
653
+ }
654
+ if (names.includes('empirical-scar-tissue')) {
655
+ lines.push('Check for scar tissue before repeating a past mistake in this area.');
656
+ }
657
+ if (names.includes('empirical-todo')) {
658
+ lines.push('If there is an open todo for this project, check it before starting new work.');
659
+ }
660
+ return '[Empirical reminder] ' + lines.join(' ');
661
+ }
662
+
663
+ // Builds the full UserPromptSubmit hook script source with the tailored message baked in at
664
+ // generation time (via JSON.stringify, so the message is embedded as a single already-escaped
665
+ // string literal - substituted through `${}`, not written as raw template-literal source text,
666
+ // which is what caused the earlier comment-escaping bug in this same file. Never do the latter).
667
+ // `platform`:
668
+ // - 'codex': Codex's required hookSpecificOutput.additionalContext JSON shape (confirmed live
669
+ // 2026-08-08 via a real `codex exec` run - plain text made Codex report the hook as failed).
670
+ // - 'copilot': Copilot's userPromptSubmitted event has NO additionalContext-equivalent field at
671
+ // all (confirmed via GitHub's own hooks reference, fetched 2026-08-08) - the only output field
672
+ // is modifiedPrompt, which REPLACES the prompt for the rest of the turn. So this reads the
673
+ // real prompt text from stdin's `prompt` field and returns it with the reminder appended -
674
+ // more invasive than Claude/Codex's side-channel injection (it's now part of the visible
675
+ // prompt), but it's the only mechanism this event actually has. Falls back to {} (leave
676
+ // unchanged) if stdin can't be read/parsed or has no prompt field, so a parsing edge case can
677
+ // never corrupt or blank out the user's actual prompt.
678
+ // - default (Claude/Copilot's plain console.log was the old assumption for both - WRONG for
679
+ // Copilot, which requires valid JSON on stdout for every event, confirmed via the same fetch
680
+ // above): plain console.log, confirmed correct for Claude only.
681
+ function buildUserPromptSubmitHookSource(pluginNames, platform) {
682
+ const messageLiteral = JSON.stringify(buildPromptReminderMessage(pluginNames));
683
+
684
+ let stdinHelper = '';
685
+ let outputStatement;
686
+ if (platform === 'codex') {
687
+ outputStatement = `console.log(JSON.stringify({
688
+ hookSpecificOutput: {
689
+ hookEventName: 'UserPromptSubmit',
690
+ additionalContext: ${messageLiteral}
691
+ }
692
+ }));`;
693
+ } else if (platform === 'copilot') {
694
+ stdinHelper = `
695
+ function readStdinPayload() {
696
+ try {
697
+ var raw = fs.readFileSync(0, 'utf8');
698
+ return raw ? JSON.parse(raw) : {};
699
+ } catch (e) {
700
+ return {};
701
+ }
702
+ }
703
+ `;
704
+ outputStatement = `var payload = readStdinPayload();
705
+ if (payload && typeof payload.prompt === 'string' && payload.prompt.length > 0) {
706
+ console.log(JSON.stringify({
707
+ modifiedPrompt: payload.prompt + '\\n\\n' + ${messageLiteral}
708
+ }));
709
+ } else {
710
+ appendLog('no usable prompt field on stdin payload, leaving prompt unchanged');
711
+ console.log('{}');
712
+ }`;
713
+ } else {
714
+ outputStatement = `console.log(${messageLiteral});`;
715
+ }
716
+
717
+ return `#!/usr/bin/env node
718
+ 'use strict';
719
+
720
+ var fs = require('fs');
721
+ var os = require('os');
722
+ var path = require('path');
723
+
724
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'user-prompt-submit.log');
725
+ var MAX_LOG_BYTES = 200 * 1024;
726
+
727
+ function appendLog(line) {
728
+ try {
729
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
730
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
731
+ var stat = fs.statSync(LOG_PATH);
732
+ if (stat.size > MAX_LOG_BYTES) {
733
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
734
+ fs.writeFileSync(LOG_PATH, tail);
735
+ }
736
+ } catch (e) {
737
+ // Diagnostics must never break the hook.
738
+ }
739
+ }
740
+ ${stdinHelper}
741
+ // A crash here must degrade to a silent no-op, never a visible "hook failed" error in the host CLI.
742
+ try {
743
+ appendLog('user-prompt-submit hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
744
+ ${outputStatement}
745
+ } catch (e) {
746
+ try { appendLog('uncaught error: ' + (e && e.message)); } catch (_e) { /* best effort */ }
747
+ }
748
+ process.exit(0);
749
+ `;
750
+ }
751
+
752
+ function getEmpiricalHooksDir() {
753
+ return path.join(os.homedir(), '.empirical', 'hooks');
754
+ }
755
+
756
+ function buildHookCommand(scriptPath) {
757
+ return `"${process.execPath}" "${scriptPath}"`;
758
+ }
759
+
760
+ // Confirmed live (2026-08-08, via a real `copilot -p` run with debug logging): Copilot runs a
761
+ // hook's "command"/"powershell" field through powershell.exe on Windows, and a bare
762
+ // `"path" "arg"` string is not valid PowerShell syntax without the call operator (&) - two
763
+ // adjacent quoted string literals with nothing between them is a ParserError
764
+ // ("Unexpected token '...' in expression or statement"), not a "file not found"-style failure.
765
+ // This is a completely different bug from Codex's (which needed 8.3 short paths to avoid
766
+ // quoting) - no short-path workaround is needed here, just the operator PowerShell requires
767
+ // before an executable path.
768
+ function buildPowershellHookCommand(scriptPath) {
769
+ return `& "${process.execPath}" "${scriptPath}"`;
770
+ }
771
+
772
+ function removeEmpiricalHookEntries(entries, scriptPath) {
773
+ if (!Array.isArray(entries)) return [];
774
+ return entries
775
+ .map((entry) => {
776
+ if (!entry || !Array.isArray(entry.hooks)) return entry;
777
+ const filteredHooks = entry.hooks.filter(
778
+ (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
779
+ );
780
+ return { ...entry, hooks: filteredHooks };
781
+ })
782
+ .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
783
+ }
784
+
785
+ function installClaudeHooks(pluginNames) {
786
+ const hooksDir = getEmpiricalHooksDir();
787
+ ensureDir(hooksDir);
788
+
789
+ // A prior version of this hook made an unconditional `empirical memory query` network call on
790
+ // every single prompt and was removed for being wasteful (see git history). This is a
791
+ // deliberate reintroduction at the SAME script path, but with fundamentally different content:
792
+ // a static, install-time-generated reminder with no network call at all - the cost concern that
793
+ // killed the old version does not apply to a plain stdout write.
794
+ const userPromptScriptPath = path.join(hooksDir, 'claude-user-prompt-submit.js');
795
+ const sessionStartScriptPath = path.join(hooksDir, 'claude-session-start.js');
796
+ const stopScriptPath = path.join(hooksDir, 'claude-stop.js');
797
+ writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
798
+ writeFile(stopScriptPath, CLAUDE_HOOK_STOP_SOURCE);
799
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
800
+
801
+ const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
802
+ const settings = readJsonIfExists(settingsPath) || {};
803
+ if (!settings.hooks || typeof settings.hooks !== 'object') {
804
+ settings.hooks = {};
805
+ }
806
+
807
+ settings.hooks.UserPromptSubmit = removeEmpiricalHookEntries(settings.hooks.UserPromptSubmit, userPromptScriptPath);
808
+ settings.hooks.UserPromptSubmit.push({
809
+ hooks: [{ type: 'command', command: buildHookCommand(userPromptScriptPath), timeout: 10 }]
810
+ });
811
+
812
+ settings.hooks.SessionStart = removeEmpiricalHookEntries(settings.hooks.SessionStart, sessionStartScriptPath);
813
+ for (const matcher of ['startup', 'resume', 'compact']) {
814
+ settings.hooks.SessionStart.push({
815
+ matcher,
816
+ hooks: [{ type: 'command', command: buildHookCommand(sessionStartScriptPath), timeout: 15 }]
817
+ });
818
+ }
819
+
820
+ settings.hooks.Stop = removeEmpiricalHookEntries(settings.hooks.Stop, stopScriptPath);
821
+ settings.hooks.Stop.push({
822
+ hooks: [{ type: 'command', command: buildHookCommand(stopScriptPath), timeout: 10 }]
823
+ });
824
+
825
+ writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
826
+ log(' - Claude SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
827
+ }
828
+
829
+ // Codex CLI ships a real hooks system (confirmed against openai/codex source — codex-rs/hooks,
830
+ // codex-rs/config/src/hook_config.rs — not assumed from docs alone, since third-party writeups
831
+ // disagreed on Windows support). It reads <CODEX_HOME>/hooks.json (JSON, not the config.toml
832
+ // used for MCP/model settings — a separate file, so this never touches config.toml) shaped as
833
+ // { hooks: { SessionStart: [{ matcher, hooks: [{ type: 'command', command, commandWindows,
834
+ // timeout }] }], ... } }. CODEX_HOME defaults to ~/.codex when unset, same convention as
835
+ // ~/.claude for Claude Code.
836
+ function getCodexHomeDir() {
837
+ return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
838
+ }
839
+
840
+ function removeEmpiricalHooksJsonEntries(entries, scriptPath) {
841
+ if (!Array.isArray(entries)) return [];
842
+ return entries
843
+ .map((entry) => {
844
+ if (!entry || !Array.isArray(entry.hooks)) return entry;
845
+ const filteredHooks = entry.hooks.filter(
846
+ (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
847
+ );
848
+ return { ...entry, hooks: filteredHooks };
849
+ })
850
+ .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
851
+ }
852
+
853
+ // Codex's Windows sandbox (confirmed via `codex doctor` -> "filesystem sandbox: restricted" and
854
+ // ~/.codex/.sandbox/sandbox.*.log's "processed N write roots (read roots delegated)" / "applying
855
+ // read ACLs" at session start) scopes filesystem access per-session to project-specific roots
856
+ // plus, necessarily, CODEX_HOME itself (Codex reads hooks.json, its state db, and its plugin
857
+ // cache from there on every session regardless of project). The shared `~/.empirical/hooks`
858
+ // directory used by Claude/Copilot is neither - so under this sandbox, node.exe most likely
859
+ // cannot even read a hook script living there, which is why hooks fail identically (exit 1)
860
+ // across SessionStart/UserPromptSubmit/Stop regardless of what each script actually does,
861
+ // including the trivial UserPromptSubmit script that spawns no subprocess at all. Claude Code
862
+ // hooks are unaffected (confirmed working from the shared dir) and Copilot has shown no such
863
+ // failure, so only Codex's copies are relocated here - Claude/Copilot keep using
864
+ // getEmpiricalHooksDir() unchanged.
865
+ function getCodexHooksScriptsDir() {
866
+ return path.join(getCodexHomeDir(), 'empirical-hooks');
867
+ }
868
+
869
+ // Confirmed live (2026-08-08, via a real `codex exec` run): Codex's Windows hook launcher fails
870
+ // to parse a quoted executable path (e.g. `"C:\Program Files\nodejs\node.exe" "<script>"`,
871
+ // otherwise a perfectly standard Windows command line - Claude Code and every direct shell/
872
+ // spawnSync invocation handle it fine) and reports the hook as a nonzero-exit failure before any
873
+ // of the script's own JS ever runs. Windows 8.3 short path names never contain spaces, so
874
+ // resolving both the node executable and the script path to their short form and joining them
875
+ // unquoted sidesteps the parser entirely. Computed once at install time (not per hook
876
+ // invocation), so a synchronous shell call here is an acceptable cost.
877
+ function getWindowsShortPath(longPath) {
878
+ if (process.platform !== 'win32') return null;
879
+ try {
880
+ const { execSync } = require('child_process');
881
+ const out = execSync(`cmd /c for %I in ("${longPath}") do @echo %~sI`, { encoding: 'utf8', timeout: 5000 });
882
+ const short = out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
883
+ const fs = require('fs');
884
+ return short && fs.existsSync(short) ? short : null;
885
+ } catch (e) {
886
+ return null;
887
+ }
888
+ }
889
+
890
+ // Builds Codex's commandWindows value using short paths so neither the executable nor the script
891
+ // path ever needs quoting. Falls back to the normal quoted buildHookCommand() form if short-path
892
+ // resolution fails for any reason (e.g. 8.3 name generation disabled on that volume) - degraded
893
+ // (same behavior as before this fix) rather than broken.
894
+ function buildCodexWindowsHookCommand(scriptPath) {
895
+ const shortNode = getWindowsShortPath(process.execPath);
896
+ const shortScript = getWindowsShortPath(scriptPath);
897
+ if (shortNode && shortScript) {
898
+ return `${shortNode} ${shortScript}`;
899
+ }
900
+ return buildHookCommand(scriptPath);
901
+ }
902
+
903
+ function installCodexHooks(pluginNames) {
904
+ const fs = require('fs');
905
+ const legacyHooksDir = getEmpiricalHooksDir();
906
+ const hooksDir = getCodexHooksScriptsDir();
907
+ ensureDir(hooksDir);
908
+
909
+ const sessionStartScriptPath = path.join(hooksDir, 'codex-session-start.js');
910
+ const stopScriptPath = path.join(hooksDir, 'codex-stop.js');
911
+ const userPromptScriptPath = path.join(hooksDir, 'codex-user-prompt-submit.js');
912
+ writeFile(sessionStartScriptPath, CODEX_HOOK_SESSION_START_SOURCE);
913
+ writeFile(stopScriptPath, CODEX_HOOK_STOP_SOURCE);
914
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'codex'));
915
+
916
+ // Best-effort cleanup of the pre-relocation script files/entries at the old shared path, so a
917
+ // machine that already had Codex hooks installed doesn't end up with both the old (broken
918
+ // under the sandbox) and new registration firing redundantly.
919
+ const legacySessionStartScriptPath = path.join(legacyHooksDir, 'codex-session-start.js');
920
+ const legacyStopScriptPath = path.join(legacyHooksDir, 'codex-stop.js');
921
+ const legacyUserPromptScriptPath = path.join(legacyHooksDir, 'codex-user-prompt-submit.js');
922
+ for (const legacyPath of [legacySessionStartScriptPath, legacyStopScriptPath, legacyUserPromptScriptPath]) {
923
+ try {
924
+ if (fs.existsSync(legacyPath)) fs.unlinkSync(legacyPath);
925
+ } catch (_error) {
926
+ // best-effort cleanup only
927
+ }
928
+ }
929
+
930
+ const hooksJsonPath = path.join(getCodexHomeDir(), 'hooks.json');
931
+ const hooksFile = readJsonIfExists(hooksJsonPath) || {};
932
+ if (!hooksFile.hooks || typeof hooksFile.hooks !== 'object') {
933
+ hooksFile.hooks = {};
934
+ }
935
+
936
+ hooksFile.hooks.SessionStart = removeEmpiricalHooksJsonEntries(
937
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.SessionStart, sessionStartScriptPath),
938
+ legacySessionStartScriptPath
939
+ );
940
+ const sessionStartCommand = buildHookCommand(sessionStartScriptPath);
941
+ const sessionStartCommandWindows = buildCodexWindowsHookCommand(sessionStartScriptPath);
942
+ for (const matcher of ['startup', 'resume']) {
943
+ hooksFile.hooks.SessionStart.push({
944
+ matcher,
945
+ hooks: [{ type: 'command', command: sessionStartCommand, commandWindows: sessionStartCommandWindows, timeout: 15 }]
946
+ });
947
+ }
948
+
949
+ hooksFile.hooks.Stop = removeEmpiricalHooksJsonEntries(
950
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.Stop, stopScriptPath),
951
+ legacyStopScriptPath
952
+ );
953
+ const stopCommand = buildHookCommand(stopScriptPath);
954
+ const stopCommandWindows = buildCodexWindowsHookCommand(stopScriptPath);
955
+ hooksFile.hooks.Stop.push({
956
+ hooks: [{ type: 'command', command: stopCommand, commandWindows: stopCommandWindows, timeout: 10 }]
957
+ });
958
+
959
+ // Confirmed against codex-rs/config/src/hook_config.rs's HookEventsToml serde renames: the
960
+ // config-file key is PascalCase "UserPromptSubmit", same casing convention as SessionStart/Stop.
961
+ hooksFile.hooks.UserPromptSubmit = removeEmpiricalHooksJsonEntries(
962
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.UserPromptSubmit, userPromptScriptPath),
963
+ legacyUserPromptScriptPath
964
+ );
965
+ const userPromptCommand = buildHookCommand(userPromptScriptPath);
966
+ const userPromptCommandWindows = buildCodexWindowsHookCommand(userPromptScriptPath);
967
+ hooksFile.hooks.UserPromptSubmit.push({
968
+ hooks: [{ type: 'command', command: userPromptCommand, commandWindows: userPromptCommandWindows, timeout: 10 }]
969
+ });
970
+
971
+ writeFile(hooksJsonPath, `${JSON.stringify(hooksFile, null, 2)}\n`);
972
+ log(' - Codex SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
973
+ }
974
+
975
+ // GitHub Copilot CLI's hook config is one JSON file per hook under ~/.copilot/hooks/ (any
976
+ // filename — confirmed via GitHub's own docs at docs.github.com/en/copilot/reference/hooks-
977
+ // reference), so unlike Claude/Codex this never needs to merge into a shared file: Empirical
978
+ // owns this file outright and can just overwrite it. Event key for turn-end is "agentStop"
979
+ // ("the main agent finishes a turn" per the same docs) — not "stop"/"Stop" like Claude/Codex.
980
+ // Schema: { version: 1, hooks: { sessionStart: [...], agentStop: [...] } }.
981
+ function installCopilotHooks(pluginNames) {
982
+ const hooksDir = getEmpiricalHooksDir();
983
+ ensureDir(hooksDir);
984
+
985
+ const sessionStartScriptPath = path.join(hooksDir, 'copilot-session-start.js');
986
+ const stopScriptPath = path.join(hooksDir, 'copilot-stop.js');
987
+ const userPromptScriptPath = path.join(hooksDir, 'copilot-user-prompt-submit.js');
988
+ writeFile(sessionStartScriptPath, COPILOT_HOOK_SESSION_START_SOURCE);
989
+ writeFile(stopScriptPath, COPILOT_HOOK_STOP_SOURCE);
990
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'copilot'));
991
+
992
+ const copilotHooksDir = path.join(os.homedir(), '.copilot', 'hooks');
993
+ ensureDir(copilotHooksDir);
994
+
995
+ // Prior versions of this installer wrote a single-purpose "empirical-session-start.json" —
996
+ // remove it now that both events live in one unified file, so a stale duplicate registration
997
+ // never lingers alongside the new one.
998
+ const legacyHookFilePath = path.join(copilotHooksDir, 'empirical-session-start.json');
999
+ try {
1000
+ const fs = require('fs');
1001
+ if (fs.existsSync(legacyHookFilePath)) fs.unlinkSync(legacyHookFilePath);
1002
+ } catch (_error) {
1003
+ // best-effort cleanup only
1004
+ }
1005
+
1006
+ const hookFilePath = path.join(copilotHooksDir, 'empirical-hooks.json');
1007
+ // Both `command` (POSIX fallback) and `powershell` (Windows-explicit, with the & call operator
1008
+ // PowerShell requires - see buildPowershellHookCommand) are always set: per GitHub's hooks
1009
+ // reference, an explicit `powershell` entry takes precedence over `command` on Windows, so this
1010
+ // is correct on both platforms without needing to detect the install-time OS here.
1011
+ const hookFileContent = {
1012
+ version: 1,
1013
+ hooks: {
1014
+ sessionStart: [
1015
+ {
1016
+ type: 'command',
1017
+ command: buildHookCommand(sessionStartScriptPath),
1018
+ powershell: buildPowershellHookCommand(sessionStartScriptPath),
1019
+ timeoutSec: 15
1020
+ }
1021
+ ],
1022
+ // "userPromptSubmitted" per GitHub's hooks reference ("The user submits a prompt") - not
1023
+ // "userPromptSubmit" (that camelCase spelling is Claude/Codex's convention, not Copilot's).
1024
+ userPromptSubmitted: [
1025
+ {
1026
+ type: 'command',
1027
+ command: buildHookCommand(userPromptScriptPath),
1028
+ powershell: buildPowershellHookCommand(userPromptScriptPath),
1029
+ timeoutSec: 10
1030
+ }
1031
+ ],
1032
+ agentStop: [
1033
+ {
1034
+ type: 'command',
1035
+ command: buildHookCommand(stopScriptPath),
1036
+ powershell: buildPowershellHookCommand(stopScriptPath),
1037
+ timeoutSec: 10
1038
+ }
1039
+ ]
1040
+ }
1041
+ };
1042
+
1043
+ writeFile(hookFilePath, `${JSON.stringify(hookFileContent, null, 2)}\n`);
1044
+ log(' - Copilot SessionStart + userPromptSubmitted + agentStop hooks installed for deterministic memory lookups and reminders.');
1045
+ }
1046
+
1047
+ module.exports = {
1048
+ CLAUDE_HOOK_SESSION_START_SOURCE,
1049
+ CODEX_HOOK_SESSION_START_SOURCE,
1050
+ COPILOT_HOOK_SESSION_START_SOURCE,
1051
+ CODEX_HOOK_STOP_SOURCE,
1052
+ COPILOT_HOOK_STOP_SOURCE,
1053
+ CLAUDE_HOOK_STOP_SOURCE,
1054
+ buildPromptReminderMessage,
1055
+ buildUserPromptSubmitHookSource,
1056
+ getEmpiricalHooksDir,
1057
+ buildHookCommand,
1058
+ buildPowershellHookCommand,
1059
+ removeEmpiricalHookEntries,
1060
+ installClaudeHooks,
1061
+ getCodexHomeDir,
1062
+ removeEmpiricalHooksJsonEntries,
1063
+ getCodexHooksScriptsDir,
1064
+ getWindowsShortPath,
1065
+ buildCodexWindowsHookCommand,
1066
+ installCodexHooks,
1067
+ installCopilotHooks
1068
+ };