@empirical-gauzza/cli 1.0.27 → 1.0.29

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,1075 +1,1355 @@
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, one memory per finding (a fix, a root cause, a decision, a lesson), via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill or \`empirical memory record\`. Local notes are not recorded. 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, one memory per finding (a fix, a root cause, a decision, a lesson), via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill or \`empirical memory record\`. Local notes are not recorded. 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: one memory per finding (a fix, a root cause, a decision, a lesson) via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill. Local notes are not recorded.'
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, platform) {
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
- // Codex Stop runs after its final response has already been emitted, so it can only be an
654
- // advisory reminder. Put the completion gate into the pre-response context instead, where
655
- // Codex can still act on it. Keep this Codex-specific: Claude and Copilot have their own
656
- // stop-hook control flows and should not receive a changed prompt contract here.
657
- if (platform === 'codex') {
658
- lines.push('If this turn results in meaningful completed work, BEFORE sending your final response you MUST use the empirical-work-history skill or record it via Empirical. The entry must carry tag work-history and mass 1; verify the create receipt. CLI fallback must use --json-file with data.session and data.git; do not use the shorthand record command for coding work. Do not wait for the Stop hook.');
659
- }
660
- }
661
- if (names.includes('empirical-scar-tissue')) {
662
- lines.push('Check for scar tissue before repeating a past mistake in this area.');
663
- }
664
- if (names.includes('empirical-todo')) {
665
- lines.push('If there is an open todo for this project, check it before starting new work.');
666
- }
667
- return '[Empirical reminder] ' + lines.join(' ');
668
- }
669
-
670
- // Builds the full UserPromptSubmit hook script source with the tailored message baked in at
671
- // generation time (via JSON.stringify, so the message is embedded as a single already-escaped
672
- // string literal - substituted through `${}`, not written as raw template-literal source text,
673
- // which is what caused the earlier comment-escaping bug in this same file. Never do the latter).
674
- // `platform`:
675
- // - 'codex': Codex's required hookSpecificOutput.additionalContext JSON shape (confirmed live
676
- // 2026-08-08 via a real `codex exec` run - plain text made Codex report the hook as failed).
677
- // - 'copilot': Copilot's userPromptSubmitted event has NO additionalContext-equivalent field at
678
- // all (confirmed via GitHub's own hooks reference, fetched 2026-08-08) - the only output field
679
- // is modifiedPrompt, which REPLACES the prompt for the rest of the turn. So this reads the
680
- // real prompt text from stdin's `prompt` field and returns it with the reminder appended -
681
- // more invasive than Claude/Codex's side-channel injection (it's now part of the visible
682
- // prompt), but it's the only mechanism this event actually has. Falls back to {} (leave
683
- // unchanged) if stdin can't be read/parsed or has no prompt field, so a parsing edge case can
684
- // never corrupt or blank out the user's actual prompt.
685
- // - default (Claude/Copilot's plain console.log was the old assumption for both - WRONG for
686
- // Copilot, which requires valid JSON on stdout for every event, confirmed via the same fetch
687
- // above): plain console.log, confirmed correct for Claude only.
688
- function buildUserPromptSubmitHookSource(pluginNames, platform) {
689
- const messageLiteral = JSON.stringify(buildPromptReminderMessage(pluginNames, platform));
690
-
691
- let stdinHelper = '';
692
- let outputStatement;
693
- if (platform === 'codex') {
694
- outputStatement = `console.log(JSON.stringify({
695
- hookSpecificOutput: {
696
- hookEventName: 'UserPromptSubmit',
697
- additionalContext: ${messageLiteral}
698
- }
699
- }));`;
700
- } else if (platform === 'copilot') {
701
- stdinHelper = `
702
- function readStdinPayload() {
703
- try {
704
- var raw = fs.readFileSync(0, 'utf8');
705
- return raw ? JSON.parse(raw) : {};
706
- } catch (e) {
707
- return {};
708
- }
709
- }
710
- `;
711
- outputStatement = `var payload = readStdinPayload();
712
- if (payload && typeof payload.prompt === 'string' && payload.prompt.length > 0) {
713
- console.log(JSON.stringify({
714
- modifiedPrompt: payload.prompt + '\\n\\n' + ${messageLiteral}
715
- }));
716
- } else {
717
- appendLog('no usable prompt field on stdin payload, leaving prompt unchanged');
718
- console.log('{}');
719
- }`;
720
- } else {
721
- outputStatement = `console.log(${messageLiteral});`;
722
- }
723
-
724
- return `#!/usr/bin/env node
725
- 'use strict';
726
-
727
- var fs = require('fs');
728
- var os = require('os');
729
- var path = require('path');
730
-
731
- var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'user-prompt-submit.log');
732
- var MAX_LOG_BYTES = 200 * 1024;
733
-
734
- function appendLog(line) {
735
- try {
736
- fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
737
- fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
738
- var stat = fs.statSync(LOG_PATH);
739
- if (stat.size > MAX_LOG_BYTES) {
740
- var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
741
- fs.writeFileSync(LOG_PATH, tail);
742
- }
743
- } catch (e) {
744
- // Diagnostics must never break the hook.
745
- }
746
- }
747
- ${stdinHelper}
748
- // A crash here must degrade to a silent no-op, never a visible "hook failed" error in the host CLI.
749
- try {
750
- appendLog('user-prompt-submit hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
751
- ${outputStatement}
752
- } catch (e) {
753
- try { appendLog('uncaught error: ' + (e && e.message)); } catch (_e) { /* best effort */ }
754
- }
755
- process.exit(0);
756
- `;
757
- }
758
-
759
- function getEmpiricalHooksDir() {
760
- return path.join(os.homedir(), '.empirical', 'hooks');
761
- }
762
-
763
- function buildHookCommand(scriptPath) {
764
- return `"${process.execPath}" "${scriptPath}"`;
765
- }
766
-
767
- // Confirmed live (2026-08-08, via a real `copilot -p` run with debug logging): Copilot runs a
768
- // hook's "command"/"powershell" field through powershell.exe on Windows, and a bare
769
- // `"path" "arg"` string is not valid PowerShell syntax without the call operator (&) - two
770
- // adjacent quoted string literals with nothing between them is a ParserError
771
- // ("Unexpected token '...' in expression or statement"), not a "file not found"-style failure.
772
- // This is a completely different bug from Codex's (which needed 8.3 short paths to avoid
773
- // quoting) - no short-path workaround is needed here, just the operator PowerShell requires
774
- // before an executable path.
775
- function buildPowershellHookCommand(scriptPath) {
776
- return `& "${process.execPath}" "${scriptPath}"`;
777
- }
778
-
779
- function removeEmpiricalHookEntries(entries, scriptPath) {
780
- if (!Array.isArray(entries)) return [];
781
- return entries
782
- .map((entry) => {
783
- if (!entry || !Array.isArray(entry.hooks)) return entry;
784
- const filteredHooks = entry.hooks.filter(
785
- (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
786
- );
787
- return { ...entry, hooks: filteredHooks };
788
- })
789
- .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
790
- }
791
-
792
- function installClaudeHooks(pluginNames) {
793
- const hooksDir = getEmpiricalHooksDir();
794
- ensureDir(hooksDir);
795
-
796
- // A prior version of this hook made an unconditional `empirical memory query` network call on
797
- // every single prompt and was removed for being wasteful (see git history). This is a
798
- // deliberate reintroduction at the SAME script path, but with fundamentally different content:
799
- // a static, install-time-generated reminder with no network call at all - the cost concern that
800
- // killed the old version does not apply to a plain stdout write.
801
- const userPromptScriptPath = path.join(hooksDir, 'claude-user-prompt-submit.js');
802
- const sessionStartScriptPath = path.join(hooksDir, 'claude-session-start.js');
803
- const stopScriptPath = path.join(hooksDir, 'claude-stop.js');
804
- writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
805
- writeFile(stopScriptPath, CLAUDE_HOOK_STOP_SOURCE);
806
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
807
-
808
- const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
809
- const settings = readJsonIfExists(settingsPath) || {};
810
- if (!settings.hooks || typeof settings.hooks !== 'object') {
811
- settings.hooks = {};
812
- }
813
-
814
- settings.hooks.UserPromptSubmit = removeEmpiricalHookEntries(settings.hooks.UserPromptSubmit, userPromptScriptPath);
815
- settings.hooks.UserPromptSubmit.push({
816
- hooks: [{ type: 'command', command: buildHookCommand(userPromptScriptPath), timeout: 10 }]
817
- });
818
-
819
- settings.hooks.SessionStart = removeEmpiricalHookEntries(settings.hooks.SessionStart, sessionStartScriptPath);
820
- for (const matcher of ['startup', 'resume', 'compact']) {
821
- settings.hooks.SessionStart.push({
822
- matcher,
823
- hooks: [{ type: 'command', command: buildHookCommand(sessionStartScriptPath), timeout: 15 }]
824
- });
825
- }
826
-
827
- settings.hooks.Stop = removeEmpiricalHookEntries(settings.hooks.Stop, stopScriptPath);
828
- settings.hooks.Stop.push({
829
- hooks: [{ type: 'command', command: buildHookCommand(stopScriptPath), timeout: 10 }]
830
- });
831
-
832
- writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
833
- log(' - Claude SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
834
- }
835
-
836
- // Codex CLI ships a real hooks system (confirmed against openai/codex source — codex-rs/hooks,
837
- // codex-rs/config/src/hook_config.rs — not assumed from docs alone, since third-party writeups
838
- // disagreed on Windows support). It reads <CODEX_HOME>/hooks.json (JSON, not the config.toml
839
- // used for MCP/model settings — a separate file, so this never touches config.toml) shaped as
840
- // { hooks: { SessionStart: [{ matcher, hooks: [{ type: 'command', command, commandWindows,
841
- // timeout }] }], ... } }. CODEX_HOME defaults to ~/.codex when unset, same convention as
842
- // ~/.claude for Claude Code.
843
- function getCodexHomeDir() {
844
- return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
845
- }
846
-
847
- function removeEmpiricalHooksJsonEntries(entries, scriptPath) {
848
- if (!Array.isArray(entries)) return [];
849
- return entries
850
- .map((entry) => {
851
- if (!entry || !Array.isArray(entry.hooks)) return entry;
852
- const filteredHooks = entry.hooks.filter(
853
- (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
854
- );
855
- return { ...entry, hooks: filteredHooks };
856
- })
857
- .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
858
- }
859
-
860
- // Codex's Windows sandbox (confirmed via `codex doctor` -> "filesystem sandbox: restricted" and
861
- // ~/.codex/.sandbox/sandbox.*.log's "processed N write roots (read roots delegated)" / "applying
862
- // read ACLs" at session start) scopes filesystem access per-session to project-specific roots
863
- // plus, necessarily, CODEX_HOME itself (Codex reads hooks.json, its state db, and its plugin
864
- // cache from there on every session regardless of project). The shared `~/.empirical/hooks`
865
- // directory used by Claude/Copilot is neither - so under this sandbox, node.exe most likely
866
- // cannot even read a hook script living there, which is why hooks fail identically (exit 1)
867
- // across SessionStart/UserPromptSubmit/Stop regardless of what each script actually does,
868
- // including the trivial UserPromptSubmit script that spawns no subprocess at all. Claude Code
869
- // hooks are unaffected (confirmed working from the shared dir) and Copilot has shown no such
870
- // failure, so only Codex's copies are relocated here - Claude/Copilot keep using
871
- // getEmpiricalHooksDir() unchanged.
872
- function getCodexHooksScriptsDir() {
873
- return path.join(getCodexHomeDir(), 'empirical-hooks');
874
- }
875
-
876
- // Confirmed live (2026-08-08, via a real `codex exec` run): Codex's Windows hook launcher fails
877
- // to parse a quoted executable path (e.g. `"C:\Program Files\nodejs\node.exe" "<script>"`,
878
- // otherwise a perfectly standard Windows command line - Claude Code and every direct shell/
879
- // spawnSync invocation handle it fine) and reports the hook as a nonzero-exit failure before any
880
- // of the script's own JS ever runs. Windows 8.3 short path names never contain spaces, so
881
- // resolving both the node executable and the script path to their short form and joining them
882
- // unquoted sidesteps the parser entirely. Computed once at install time (not per hook
883
- // invocation), so a synchronous shell call here is an acceptable cost.
884
- function getWindowsShortPath(longPath) {
885
- if (process.platform !== 'win32') return null;
886
- try {
887
- const { execSync } = require('child_process');
888
- const out = execSync(`cmd /c for %I in ("${longPath}") do @echo %~sI`, { encoding: 'utf8', timeout: 5000 });
889
- const short = out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
890
- const fs = require('fs');
891
- return short && fs.existsSync(short) ? short : null;
892
- } catch (e) {
893
- return null;
894
- }
895
- }
896
-
897
- // Builds Codex's commandWindows value using short paths so neither the executable nor the script
898
- // path ever needs quoting. Falls back to the normal quoted buildHookCommand() form if short-path
899
- // resolution fails for any reason (e.g. 8.3 name generation disabled on that volume) - degraded
900
- // (same behavior as before this fix) rather than broken.
901
- function buildCodexWindowsHookCommand(scriptPath) {
902
- const shortNode = getWindowsShortPath(process.execPath);
903
- const shortScript = getWindowsShortPath(scriptPath);
904
- if (shortNode && shortScript) {
905
- return `${shortNode} ${shortScript}`;
906
- }
907
- return buildHookCommand(scriptPath);
908
- }
909
-
910
- function installCodexHooks(pluginNames) {
911
- const fs = require('fs');
912
- const legacyHooksDir = getEmpiricalHooksDir();
913
- const hooksDir = getCodexHooksScriptsDir();
914
- ensureDir(hooksDir);
915
-
916
- const sessionStartScriptPath = path.join(hooksDir, 'codex-session-start.js');
917
- const stopScriptPath = path.join(hooksDir, 'codex-stop.js');
918
- const userPromptScriptPath = path.join(hooksDir, 'codex-user-prompt-submit.js');
919
- writeFile(sessionStartScriptPath, CODEX_HOOK_SESSION_START_SOURCE);
920
- writeFile(stopScriptPath, CODEX_HOOK_STOP_SOURCE);
921
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'codex'));
922
-
923
- // Best-effort cleanup of the pre-relocation script files/entries at the old shared path, so a
924
- // machine that already had Codex hooks installed doesn't end up with both the old (broken
925
- // under the sandbox) and new registration firing redundantly.
926
- const legacySessionStartScriptPath = path.join(legacyHooksDir, 'codex-session-start.js');
927
- const legacyStopScriptPath = path.join(legacyHooksDir, 'codex-stop.js');
928
- const legacyUserPromptScriptPath = path.join(legacyHooksDir, 'codex-user-prompt-submit.js');
929
- for (const legacyPath of [legacySessionStartScriptPath, legacyStopScriptPath, legacyUserPromptScriptPath]) {
930
- try {
931
- if (fs.existsSync(legacyPath)) fs.unlinkSync(legacyPath);
932
- } catch (_error) {
933
- // best-effort cleanup only
934
- }
935
- }
936
-
937
- const hooksJsonPath = path.join(getCodexHomeDir(), 'hooks.json');
938
- const hooksFile = readJsonIfExists(hooksJsonPath) || {};
939
- if (!hooksFile.hooks || typeof hooksFile.hooks !== 'object') {
940
- hooksFile.hooks = {};
941
- }
942
-
943
- hooksFile.hooks.SessionStart = removeEmpiricalHooksJsonEntries(
944
- removeEmpiricalHooksJsonEntries(hooksFile.hooks.SessionStart, sessionStartScriptPath),
945
- legacySessionStartScriptPath
946
- );
947
- const sessionStartCommand = buildHookCommand(sessionStartScriptPath);
948
- const sessionStartCommandWindows = buildCodexWindowsHookCommand(sessionStartScriptPath);
949
- for (const matcher of ['startup', 'resume']) {
950
- hooksFile.hooks.SessionStart.push({
951
- matcher,
952
- hooks: [{ type: 'command', command: sessionStartCommand, commandWindows: sessionStartCommandWindows, timeout: 15 }]
953
- });
954
- }
955
-
956
- hooksFile.hooks.Stop = removeEmpiricalHooksJsonEntries(
957
- removeEmpiricalHooksJsonEntries(hooksFile.hooks.Stop, stopScriptPath),
958
- legacyStopScriptPath
959
- );
960
- const stopCommand = buildHookCommand(stopScriptPath);
961
- const stopCommandWindows = buildCodexWindowsHookCommand(stopScriptPath);
962
- hooksFile.hooks.Stop.push({
963
- hooks: [{ type: 'command', command: stopCommand, commandWindows: stopCommandWindows, timeout: 10 }]
964
- });
965
-
966
- // Confirmed against codex-rs/config/src/hook_config.rs's HookEventsToml serde renames: the
967
- // config-file key is PascalCase "UserPromptSubmit", same casing convention as SessionStart/Stop.
968
- hooksFile.hooks.UserPromptSubmit = removeEmpiricalHooksJsonEntries(
969
- removeEmpiricalHooksJsonEntries(hooksFile.hooks.UserPromptSubmit, userPromptScriptPath),
970
- legacyUserPromptScriptPath
971
- );
972
- const userPromptCommand = buildHookCommand(userPromptScriptPath);
973
- const userPromptCommandWindows = buildCodexWindowsHookCommand(userPromptScriptPath);
974
- hooksFile.hooks.UserPromptSubmit.push({
975
- hooks: [{ type: 'command', command: userPromptCommand, commandWindows: userPromptCommandWindows, timeout: 10 }]
976
- });
977
-
978
- writeFile(hooksJsonPath, `${JSON.stringify(hooksFile, null, 2)}\n`);
979
- log(' - Codex SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
980
- }
981
-
982
- // GitHub Copilot CLI's hook config is one JSON file per hook under ~/.copilot/hooks/ (any
983
- // filename — confirmed via GitHub's own docs at docs.github.com/en/copilot/reference/hooks-
984
- // reference), so unlike Claude/Codex this never needs to merge into a shared file: Empirical
985
- // owns this file outright and can just overwrite it. Event key for turn-end is "agentStop"
986
- // ("the main agent finishes a turn" per the same docs) — not "stop"/"Stop" like Claude/Codex.
987
- // Schema: { version: 1, hooks: { sessionStart: [...], agentStop: [...] } }.
988
- function installCopilotHooks(pluginNames) {
989
- const hooksDir = getEmpiricalHooksDir();
990
- ensureDir(hooksDir);
991
-
992
- const sessionStartScriptPath = path.join(hooksDir, 'copilot-session-start.js');
993
- const stopScriptPath = path.join(hooksDir, 'copilot-stop.js');
994
- const userPromptScriptPath = path.join(hooksDir, 'copilot-user-prompt-submit.js');
995
- writeFile(sessionStartScriptPath, COPILOT_HOOK_SESSION_START_SOURCE);
996
- writeFile(stopScriptPath, COPILOT_HOOK_STOP_SOURCE);
997
- writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'copilot'));
998
-
999
- const copilotHooksDir = path.join(os.homedir(), '.copilot', 'hooks');
1000
- ensureDir(copilotHooksDir);
1001
-
1002
- // Prior versions of this installer wrote a single-purpose "empirical-session-start.json" —
1003
- // remove it now that both events live in one unified file, so a stale duplicate registration
1004
- // never lingers alongside the new one.
1005
- const legacyHookFilePath = path.join(copilotHooksDir, 'empirical-session-start.json');
1006
- try {
1007
- const fs = require('fs');
1008
- if (fs.existsSync(legacyHookFilePath)) fs.unlinkSync(legacyHookFilePath);
1009
- } catch (_error) {
1010
- // best-effort cleanup only
1011
- }
1012
-
1013
- const hookFilePath = path.join(copilotHooksDir, 'empirical-hooks.json');
1014
- // Both `command` (POSIX fallback) and `powershell` (Windows-explicit, with the & call operator
1015
- // PowerShell requires - see buildPowershellHookCommand) are always set: per GitHub's hooks
1016
- // reference, an explicit `powershell` entry takes precedence over `command` on Windows, so this
1017
- // is correct on both platforms without needing to detect the install-time OS here.
1018
- const hookFileContent = {
1019
- version: 1,
1020
- hooks: {
1021
- sessionStart: [
1022
- {
1023
- type: 'command',
1024
- command: buildHookCommand(sessionStartScriptPath),
1025
- powershell: buildPowershellHookCommand(sessionStartScriptPath),
1026
- timeoutSec: 15
1027
- }
1028
- ],
1029
- // "userPromptSubmitted" per GitHub's hooks reference ("The user submits a prompt") - not
1030
- // "userPromptSubmit" (that camelCase spelling is Claude/Codex's convention, not Copilot's).
1031
- userPromptSubmitted: [
1032
- {
1033
- type: 'command',
1034
- command: buildHookCommand(userPromptScriptPath),
1035
- powershell: buildPowershellHookCommand(userPromptScriptPath),
1036
- timeoutSec: 10
1037
- }
1038
- ],
1039
- agentStop: [
1040
- {
1041
- type: 'command',
1042
- command: buildHookCommand(stopScriptPath),
1043
- powershell: buildPowershellHookCommand(stopScriptPath),
1044
- timeoutSec: 10
1045
- }
1046
- ]
1047
- }
1048
- };
1049
-
1050
- writeFile(hookFilePath, `${JSON.stringify(hookFileContent, null, 2)}\n`);
1051
- log(' - Copilot SessionStart + userPromptSubmitted + agentStop hooks installed for deterministic memory lookups and reminders.');
1052
- }
1053
-
1054
- module.exports = {
1055
- CLAUDE_HOOK_SESSION_START_SOURCE,
1056
- CODEX_HOOK_SESSION_START_SOURCE,
1057
- COPILOT_HOOK_SESSION_START_SOURCE,
1058
- CODEX_HOOK_STOP_SOURCE,
1059
- COPILOT_HOOK_STOP_SOURCE,
1060
- CLAUDE_HOOK_STOP_SOURCE,
1061
- buildPromptReminderMessage,
1062
- buildUserPromptSubmitHookSource,
1063
- getEmpiricalHooksDir,
1064
- buildHookCommand,
1065
- buildPowershellHookCommand,
1066
- removeEmpiricalHookEntries,
1067
- installClaudeHooks,
1068
- getCodexHomeDir,
1069
- removeEmpiricalHooksJsonEntries,
1070
- getCodexHooksScriptsDir,
1071
- getWindowsShortPath,
1072
- buildCodexWindowsHookCommand,
1073
- installCodexHooks,
1074
- installCopilotHooks
1075
- };
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
+ // Declared inside main() on purpose: function declarations hoist, and other hook templates in
114
+ // this file have their own main() without the memory-query plumbing.
115
+
116
+ // WHAT PROJECT IS THIS, in priority order. Guessing from the directory name is the last resort,
117
+ // not the contract: a repo folder is not always what the corpus tags memories with.
118
+ // 1. EMPIRICAL_PROJECT_TAG / EMPIRICAL_TOPICS environment variables
119
+ // 2. .empirical.json in the working directory or any ancestor, up to 6 levels:
120
+ // { "project": "empirical_v2", "topics": ["search ranking", "deploy"] }
121
+ // 3. the working directory name, lowercased
122
+ function readProjectConfig() {
123
+ var config = { project: '', topics: [] };
124
+ try {
125
+ var dir = process.cwd();
126
+ for (var depth = 0; depth < 6; depth += 1) {
127
+ var candidate = path.join(dir, '.empirical.json');
128
+ if (fs.existsSync(candidate)) {
129
+ var parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
130
+ config.project = String(parsed && parsed.project ? parsed.project : '').trim().toLowerCase();
131
+ if (parsed && Array.isArray(parsed.topics)) {
132
+ config.topics = parsed.topics.map(function (t) { return String(t || '').trim(); }).filter(Boolean);
133
+ }
134
+ appendLog('loaded project config from ' + candidate);
135
+ return config;
136
+ }
137
+ var parent = path.dirname(dir);
138
+ if (!parent || parent === dir) { break; }
139
+ dir = parent;
140
+ }
141
+ } catch (e) {
142
+ appendLog('project config unreadable, continuing without it: ' + e.message);
143
+ }
144
+ return config;
145
+ }
146
+
147
+ // requireAll selects --tags-all (AND) over --tags (OR). This matters: --tags is an OR match, so
148
+ // asking for 'empirical_v2,todo' returns every project's todos, which put a wellnessonbalance
149
+ // item into an empirical_v2 session during testing on 2026-09-16.
150
+ function fetchMemories(matchText, tags, topK, requireAll) {
151
+ var args = ['memory', 'query', '--match', matchText, '--top-k', String(topK)];
152
+ if (tags) { args.push(requireAll ? '--tags-all' : '--tags', tags); }
153
+ var queryResult = runMemoryQuery(args);
154
+ if (!queryResult || queryResult.status !== 0 || !queryResult.stdout) {
155
+ appendLog('memory query failed (tags=' + (tags || 'none') + ', status=' + (queryResult && queryResult.status) + ', stderr=' + (queryResult && queryResult.stderr ? String(queryResult.stderr).slice(0, 200) : '') + ')');
156
+ return [];
157
+ }
158
+ try {
159
+ var parsed = JSON.parse(queryResult.stdout);
160
+ return Array.isArray(parsed) ? parsed : [];
161
+ } catch (e) {
162
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
163
+ return [];
164
+ }
165
+ }
166
+
167
+ var fileConfig = readProjectConfig();
168
+ var envTag = String(process.env.EMPIRICAL_PROJECT_TAG || '').trim().toLowerCase();
169
+ var envTopics = String(process.env.EMPIRICAL_TOPICS || '').split(',').map(function (t) { return t.trim(); }).filter(Boolean);
170
+
171
+ var tag = envTag || fileConfig.project;
172
+ var tagSource = envTag ? 'env' : (fileConfig.project ? 'config' : 'cwd');
173
+ if (!tag) {
174
+ try {
175
+ tag = String(path.basename(process.cwd() || '') || '').trim().toLowerCase();
176
+ } catch (e) {
177
+ tag = '';
178
+ }
179
+ }
180
+
181
+ var topics = envTopics.length ? envTopics : fileConfig.topics;
182
+ var contextMatch = topics.length
183
+ ? topics.join(', ')
184
+ : 'project context, conventions, recent decisions, user preferences';
185
+
186
+ appendLog('project tag=' + (tag || '(none)') + ' (source=' + tagSource + '), topics=' + (topics.length ? topics.join('|') : '(default)'));
187
+
188
+ // Scope every query to the project. Measured 2026-09-16: with no tag filter all 8 slots went to
189
+ // one unrelated project during a full session in a different repo, so the only automatic context
190
+ // rail in the product was spending every slot on the wrong thing. A tag filter also disables the
191
+ // server's agent-process-note exclusion, which is what makes a project's own scar tissue and
192
+ // work history reachable here at all.
193
+ //
194
+ // Open items get their OWN query instead of competing for rank. Tested 2026-09-16: a due-dated
195
+ // memory did not surface in the generic top-8 with or without a project filter, because dueness
196
+ // is not a semantic property. Anything that must be seen needs a reserved slot.
197
+ // AND, not OR: this must be THIS project's todos. No --status filter on purpose, because todos
198
+ // written without a data.status would silently vanish from the one place they get surfaced;
199
+ // the label tells the reader to confirm instead.
200
+ var todos = tag ? fetchMemories('open todo, next action, follow-up, due', tag + ',todo', 3, true) : [];
201
+ var context = tag ? fetchMemories(contextMatch, tag, 6) : [];
202
+
203
+ // A corpus whose tags do not match the resolved project must never end up worse off than before
204
+ // this change, so fall back to the original unscoped query.
205
+ if (context.length === 0) {
206
+ appendLog('project-scoped query returned nothing, falling back to unscoped');
207
+ context = fetchMemories(contextMatch, '', 8);
208
+ }
209
+
210
+ if (todos.length === 0 && context.length === 0) {
211
+ appendLog('memory query returned zero results');
212
+ process.exit(0);
213
+ }
214
+
215
+ var openCount = todos.length;
216
+ var results = todos.concat(context);
217
+
218
+ appendLog('memory query returned ' + results.length + ' result(s), injecting into session context');
219
+
220
+ // Summaries in a mature corpus run to thousands of characters. Injecting eight in full is a wall
221
+ // of text that gets skimmed past, which fails the same way as never injecting them at all:
222
+ // presence in context is not attention. Truncate hard; the agent can query for the rest.
223
+ var lines = results.slice(0, 9).map(function (r, i) {
224
+ var category = r && r.category ? r.category : 'memory';
225
+ var summary = String(r && r.summary ? r.summary : '');
226
+ summary = summary.split('\\n').join(' ').split('\\r').join(' ').split('\\t').join(' ').trim();
227
+ if (summary.length > 240) { summary = summary.slice(0, 237) + '...'; }
228
+ var prefix = i < openCount ? '- [OPEN ITEM, confirm status] ' : '- [' + category + '] ';
229
+ return prefix + summary;
230
+ });
231
+ lines.push('- Before risky or repeated work, ask first: empirical memory query --match "<what you are about to do>" --tags scar-tissue');
232
+
233
+ console.log('Empirical memory context for this session:\\n' + lines.join('\\n'));
234
+ process.exit(0);
235
+ }
236
+
237
+ // Hooks must never surface as a hard failure to the host CLI (Codex/Claude/Copilot all render a
238
+ // nonzero exit as a red "hook failed" error) - an uncaught exception anywhere above (e.g. an
239
+ // environment that denies process spawn or fs access, such as Codex's experimental Windows
240
+ // sandbox) must degrade to a silent no-op, not a visible crash.
241
+ try {
242
+ main();
243
+ } catch (e) {
244
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
245
+ process.exit(0);
246
+ }
247
+ `;
248
+
249
+ // Codex-only variant of the SessionStart hook above. Confirmed live (2026-08-08, via a real
250
+ // `codex exec` run) that Codex requires valid JSON on stdout for a hook's output to actually
251
+ // register/display - plain text (what CLAUDE_HOOK_SESSION_START_SOURCE emits, which Claude Code
252
+ // handles fine) makes Codex report the hook as failed. Uses the same hookSpecificOutput.
253
+ // additionalContext shape Claude's own JSON-output hooks use (see CLAUDE_HOOK_STOP_SOURCE below) -
254
+ // confirmed accepted by Codex's SessionStart handler specifically. Otherwise byte-identical to
255
+ // CLAUDE_HOOK_SESSION_START_SOURCE; keep any future logic changes in sync between the two.
256
+ const CODEX_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
257
+ 'use strict';
258
+
259
+ var spawnSync = require('child_process').spawnSync;
260
+ var fs = require('fs');
261
+ var os = require('os');
262
+ var path = require('path');
263
+
264
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
265
+ var MAX_LOG_BYTES = 200 * 1024;
266
+
267
+ function appendLog(line) {
268
+ try {
269
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
270
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
271
+ var stat = fs.statSync(LOG_PATH);
272
+ if (stat.size > MAX_LOG_BYTES) {
273
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
274
+ fs.writeFileSync(LOG_PATH, tail);
275
+ }
276
+ } catch (e) {
277
+ // Diagnostics must never break session start.
278
+ }
279
+ }
280
+
281
+ function resolveEmpiricalEntryPoint() {
282
+ if (process.platform !== 'win32') {
283
+ return null;
284
+ }
285
+ try {
286
+ var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
287
+ if (where.status !== 0 || !where.stdout) return null;
288
+ var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
289
+ if (!cmdPath || !fs.existsSync(cmdPath)) return null;
290
+ var cmdContent = fs.readFileSync(cmdPath, 'utf8');
291
+ var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
292
+ if (!match) return null;
293
+ var candidate = path.join(path.dirname(cmdPath), match[1]);
294
+ return fs.existsSync(candidate) ? candidate : null;
295
+ } catch (e) {
296
+ return null;
297
+ }
298
+ }
299
+
300
+ function commandExists(cmd) {
301
+ var probe = process.platform === 'win32'
302
+ ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
303
+ : spawnSync('which', [cmd], { stdio: 'ignore' });
304
+ return probe.status === 0;
305
+ }
306
+
307
+ function runMemoryQuery(args) {
308
+ var entryPoint = resolveEmpiricalEntryPoint();
309
+ if (entryPoint) {
310
+ appendLog('resolved direct entry point: ' + entryPoint);
311
+ return spawnSync(process.execPath, [entryPoint].concat(args), {
312
+ encoding: 'utf8',
313
+ timeout: 10000,
314
+ shell: false
315
+ });
316
+ }
317
+
318
+ appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
319
+ return spawnSync('empirical', args, {
320
+ encoding: 'utf8',
321
+ timeout: 10000,
322
+ shell: process.platform === 'win32'
323
+ });
324
+ }
325
+
326
+ // Codex requires VALID JSON on stdout for every hook run. Emitting nothing is as broken as
327
+ // emitting plain text: both surface to the user as "SessionStart hook (failed)". Every early
328
+ // return below is a legitimate "no memory context to add" outcome (CLI missing, offline,
329
+ // expired token, zero results), so each one now emits a well-formed envelope with an empty
330
+ // context instead of exiting silently. Found 2026-09-09: with the API unreachable this hook
331
+ // printed nothing at all and exited 0.
332
+ function emitContext(context) {
333
+ console.log(JSON.stringify({
334
+ hookSpecificOutput: {
335
+ hookEventName: 'SessionStart',
336
+ additionalContext: context || ''
337
+ }
338
+ }));
339
+ }
340
+
341
+ function main() {
342
+ appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
343
+
344
+ if (!commandExists('empirical')) {
345
+ appendLog('empirical CLI not found on PATH, exiting');
346
+ emitContext('');
347
+ process.exit(0);
348
+ }
349
+
350
+ // Declared inside main() on purpose: function declarations hoist, and other hook templates in
351
+ // this file have their own main() without the memory-query plumbing.
352
+
353
+ // WHAT PROJECT IS THIS, in priority order. Guessing from the directory name is the last resort,
354
+ // not the contract: a repo folder is not always what the corpus tags memories with.
355
+ // 1. EMPIRICAL_PROJECT_TAG / EMPIRICAL_TOPICS environment variables
356
+ // 2. .empirical.json in the working directory or any ancestor, up to 6 levels:
357
+ // { "project": "empirical_v2", "topics": ["search ranking", "deploy"] }
358
+ // 3. the working directory name, lowercased
359
+ function readProjectConfig() {
360
+ var config = { project: '', topics: [] };
361
+ try {
362
+ var dir = process.cwd();
363
+ for (var depth = 0; depth < 6; depth += 1) {
364
+ var candidate = path.join(dir, '.empirical.json');
365
+ if (fs.existsSync(candidate)) {
366
+ var parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
367
+ config.project = String(parsed && parsed.project ? parsed.project : '').trim().toLowerCase();
368
+ if (parsed && Array.isArray(parsed.topics)) {
369
+ config.topics = parsed.topics.map(function (t) { return String(t || '').trim(); }).filter(Boolean);
370
+ }
371
+ appendLog('loaded project config from ' + candidate);
372
+ return config;
373
+ }
374
+ var parent = path.dirname(dir);
375
+ if (!parent || parent === dir) { break; }
376
+ dir = parent;
377
+ }
378
+ } catch (e) {
379
+ appendLog('project config unreadable, continuing without it: ' + e.message);
380
+ }
381
+ return config;
382
+ }
383
+
384
+ // requireAll selects --tags-all (AND) over --tags (OR). This matters: --tags is an OR match, so
385
+ // asking for 'empirical_v2,todo' returns every project's todos, which put a wellnessonbalance
386
+ // item into an empirical_v2 session during testing on 2026-09-16.
387
+ function fetchMemories(matchText, tags, topK, requireAll) {
388
+ var args = ['memory', 'query', '--match', matchText, '--top-k', String(topK)];
389
+ if (tags) { args.push(requireAll ? '--tags-all' : '--tags', tags); }
390
+ var queryResult = runMemoryQuery(args);
391
+ if (!queryResult || queryResult.status !== 0 || !queryResult.stdout) {
392
+ appendLog('memory query failed (tags=' + (tags || 'none') + ', status=' + (queryResult && queryResult.status) + ', stderr=' + (queryResult && queryResult.stderr ? String(queryResult.stderr).slice(0, 200) : '') + ')');
393
+ return [];
394
+ }
395
+ try {
396
+ var parsed = JSON.parse(queryResult.stdout);
397
+ return Array.isArray(parsed) ? parsed : [];
398
+ } catch (e) {
399
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
400
+ return [];
401
+ }
402
+ }
403
+
404
+ var fileConfig = readProjectConfig();
405
+ var envTag = String(process.env.EMPIRICAL_PROJECT_TAG || '').trim().toLowerCase();
406
+ var envTopics = String(process.env.EMPIRICAL_TOPICS || '').split(',').map(function (t) { return t.trim(); }).filter(Boolean);
407
+
408
+ var tag = envTag || fileConfig.project;
409
+ var tagSource = envTag ? 'env' : (fileConfig.project ? 'config' : 'cwd');
410
+ if (!tag) {
411
+ try {
412
+ tag = String(path.basename(process.cwd() || '') || '').trim().toLowerCase();
413
+ } catch (e) {
414
+ tag = '';
415
+ }
416
+ }
417
+
418
+ var topics = envTopics.length ? envTopics : fileConfig.topics;
419
+ var contextMatch = topics.length
420
+ ? topics.join(', ')
421
+ : 'project context, conventions, recent decisions, user preferences';
422
+
423
+ appendLog('project tag=' + (tag || '(none)') + ' (source=' + tagSource + '), topics=' + (topics.length ? topics.join('|') : '(default)'));
424
+
425
+ // Scope every query to the project. Measured 2026-09-16: with no tag filter all 8 slots went to
426
+ // one unrelated project during a full session in a different repo, so the only automatic context
427
+ // rail in the product was spending every slot on the wrong thing. A tag filter also disables the
428
+ // server's agent-process-note exclusion, which is what makes a project's own scar tissue and
429
+ // work history reachable here at all.
430
+ //
431
+ // Open items get their OWN query instead of competing for rank. Tested 2026-09-16: a due-dated
432
+ // memory did not surface in the generic top-8 with or without a project filter, because dueness
433
+ // is not a semantic property. Anything that must be seen needs a reserved slot.
434
+ // AND, not OR: this must be THIS project's todos. No --status filter on purpose, because todos
435
+ // written without a data.status would silently vanish from the one place they get surfaced;
436
+ // the label tells the reader to confirm instead.
437
+ var todos = tag ? fetchMemories('open todo, next action, follow-up, due', tag + ',todo', 3, true) : [];
438
+ var context = tag ? fetchMemories(contextMatch, tag, 6) : [];
439
+
440
+ // A corpus whose tags do not match the resolved project must never end up worse off than before
441
+ // this change, so fall back to the original unscoped query.
442
+ if (context.length === 0) {
443
+ appendLog('project-scoped query returned nothing, falling back to unscoped');
444
+ context = fetchMemories(contextMatch, '', 8);
445
+ }
446
+
447
+ if (todos.length === 0 && context.length === 0) {
448
+ appendLog('memory query returned zero results');
449
+ emitContext('');
450
+ process.exit(0);
451
+ }
452
+
453
+ var openCount = todos.length;
454
+ var results = todos.concat(context);
455
+
456
+ appendLog('memory query returned ' + results.length + ' result(s), injecting into session context');
457
+
458
+ // Summaries in a mature corpus run to thousands of characters. Injecting eight in full is a wall
459
+ // of text that gets skimmed past, which fails the same way as never injecting them at all:
460
+ // presence in context is not attention. Truncate hard; the agent can query for the rest.
461
+ var lines = results.slice(0, 9).map(function (r, i) {
462
+ var category = r && r.category ? r.category : 'memory';
463
+ var summary = String(r && r.summary ? r.summary : '');
464
+ summary = summary.split('\\n').join(' ').split('\\r').join(' ').split('\\t').join(' ').trim();
465
+ if (summary.length > 240) { summary = summary.slice(0, 237) + '...'; }
466
+ var prefix = i < openCount ? '- [OPEN ITEM, confirm status] ' : '- [' + category + '] ';
467
+ return prefix + summary;
468
+ });
469
+ lines.push('- Before risky or repeated work, ask first: empirical memory query --match "<what you are about to do>" --tags scar-tissue');
470
+
471
+ console.log(JSON.stringify({
472
+ hookSpecificOutput: {
473
+ hookEventName: 'SessionStart',
474
+ additionalContext: 'Empirical memory context for this session:\\n' + lines.join('\\n')
475
+ }
476
+ }));
477
+ process.exit(0);
478
+ }
479
+
480
+ try {
481
+ main();
482
+ } catch (e) {
483
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
484
+ try { emitContext(''); } catch (_e2) { /* stdout already unusable */ }
485
+ process.exit(0);
486
+ }
487
+ `;
488
+
489
+ // Copilot-only variant of the SessionStart hook. Per GitHub's own hooks reference (fetched
490
+ // 2026-08-08): unlike Claude/Codex, Copilot's sessionStart event has NO output mechanism at all
491
+ // - there is no additionalContext-equivalent field, so a hook cannot inject memory context into
492
+ // the session this way, full stop (this is a genuine platform limitation, not a bug to work
493
+ // around). Separately, Copilot requires ALL hook stdout to be valid JSON parsed via a single
494
+ // JSON.parse call - plain text (fine for Claude, and previously assumed fine here too) is
495
+ // invalid and makes Copilot log a hook execution failure. So this variant still runs the memory
496
+ // query and logs the result for diagnostic/audit purposes, but emits {} (empty, valid JSON,
497
+ // explicitly documented as "use defaults") instead of attempting to inject anything.
498
+ const COPILOT_HOOK_SESSION_START_SOURCE = `#!/usr/bin/env node
499
+ 'use strict';
500
+
501
+ var spawnSync = require('child_process').spawnSync;
502
+ var fs = require('fs');
503
+ var os = require('os');
504
+ var path = require('path');
505
+
506
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'session-start.log');
507
+ var MAX_LOG_BYTES = 200 * 1024;
508
+
509
+ function appendLog(line) {
510
+ try {
511
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
512
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
513
+ var stat = fs.statSync(LOG_PATH);
514
+ if (stat.size > MAX_LOG_BYTES) {
515
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
516
+ fs.writeFileSync(LOG_PATH, tail);
517
+ }
518
+ } catch (e) {
519
+ // Diagnostics must never break session start.
520
+ }
521
+ }
522
+
523
+ function resolveEmpiricalEntryPoint() {
524
+ if (process.platform !== 'win32') {
525
+ return null;
526
+ }
527
+ try {
528
+ var where = spawnSync('where', ['empirical.cmd'], { encoding: 'utf8', timeout: 5000, shell: true });
529
+ if (where.status !== 0 || !where.stdout) return null;
530
+ var cmdPath = where.stdout.split(/\\r?\\n/).map(function (s) { return s.trim(); }).filter(Boolean)[0];
531
+ if (!cmdPath || !fs.existsSync(cmdPath)) return null;
532
+ var cmdContent = fs.readFileSync(cmdPath, 'utf8');
533
+ var match = cmdContent.match(/"%dp0%\\\\(node_modules\\\\.+?\\.js)"/);
534
+ if (!match) return null;
535
+ var candidate = path.join(path.dirname(cmdPath), match[1]);
536
+ return fs.existsSync(candidate) ? candidate : null;
537
+ } catch (e) {
538
+ return null;
539
+ }
540
+ }
541
+
542
+ function commandExists(cmd) {
543
+ var probe = process.platform === 'win32'
544
+ ? spawnSync('where', [cmd], { stdio: 'ignore', shell: true })
545
+ : spawnSync('which', [cmd], { stdio: 'ignore' });
546
+ return probe.status === 0;
547
+ }
548
+
549
+ function runMemoryQuery(args) {
550
+ var entryPoint = resolveEmpiricalEntryPoint();
551
+ if (entryPoint) {
552
+ appendLog('resolved direct entry point: ' + entryPoint);
553
+ return spawnSync(process.execPath, [entryPoint].concat(args), {
554
+ encoding: 'utf8',
555
+ timeout: 10000,
556
+ shell: false
557
+ });
558
+ }
559
+
560
+ appendLog('direct entry point not resolved, falling back to shell invocation (shell=' + (process.platform === 'win32') + ')');
561
+ return spawnSync('empirical', args, {
562
+ encoding: 'utf8',
563
+ timeout: 10000,
564
+ shell: process.platform === 'win32'
565
+ });
566
+ }
567
+
568
+ function main() {
569
+ appendLog('hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
570
+
571
+ if (!commandExists('empirical')) {
572
+ appendLog('empirical CLI not found on PATH, exiting');
573
+ console.log('{}');
574
+ process.exit(0);
575
+ }
576
+
577
+ // Declared inside main() on purpose: function declarations hoist, and other hook templates in
578
+ // this file have their own main() without the memory-query plumbing.
579
+
580
+ // WHAT PROJECT IS THIS, in priority order. Guessing from the directory name is the last resort,
581
+ // not the contract: a repo folder is not always what the corpus tags memories with.
582
+ // 1. EMPIRICAL_PROJECT_TAG / EMPIRICAL_TOPICS environment variables
583
+ // 2. .empirical.json in the working directory or any ancestor, up to 6 levels:
584
+ // { "project": "empirical_v2", "topics": ["search ranking", "deploy"] }
585
+ // 3. the working directory name, lowercased
586
+ function readProjectConfig() {
587
+ var config = { project: '', topics: [] };
588
+ try {
589
+ var dir = process.cwd();
590
+ for (var depth = 0; depth < 6; depth += 1) {
591
+ var candidate = path.join(dir, '.empirical.json');
592
+ if (fs.existsSync(candidate)) {
593
+ var parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
594
+ config.project = String(parsed && parsed.project ? parsed.project : '').trim().toLowerCase();
595
+ if (parsed && Array.isArray(parsed.topics)) {
596
+ config.topics = parsed.topics.map(function (t) { return String(t || '').trim(); }).filter(Boolean);
597
+ }
598
+ appendLog('loaded project config from ' + candidate);
599
+ return config;
600
+ }
601
+ var parent = path.dirname(dir);
602
+ if (!parent || parent === dir) { break; }
603
+ dir = parent;
604
+ }
605
+ } catch (e) {
606
+ appendLog('project config unreadable, continuing without it: ' + e.message);
607
+ }
608
+ return config;
609
+ }
610
+
611
+ // requireAll selects --tags-all (AND) over --tags (OR). This matters: --tags is an OR match, so
612
+ // asking for 'empirical_v2,todo' returns every project's todos, which put a wellnessonbalance
613
+ // item into an empirical_v2 session during testing on 2026-09-16.
614
+ function fetchMemories(matchText, tags, topK, requireAll) {
615
+ var args = ['memory', 'query', '--match', matchText, '--top-k', String(topK)];
616
+ if (tags) { args.push(requireAll ? '--tags-all' : '--tags', tags); }
617
+ var queryResult = runMemoryQuery(args);
618
+ if (!queryResult || queryResult.status !== 0 || !queryResult.stdout) {
619
+ appendLog('memory query failed (tags=' + (tags || 'none') + ', status=' + (queryResult && queryResult.status) + ', stderr=' + (queryResult && queryResult.stderr ? String(queryResult.stderr).slice(0, 200) : '') + ')');
620
+ return [];
621
+ }
622
+ try {
623
+ var parsed = JSON.parse(queryResult.stdout);
624
+ return Array.isArray(parsed) ? parsed : [];
625
+ } catch (e) {
626
+ appendLog('failed to parse memory query stdout as JSON: ' + e.message);
627
+ return [];
628
+ }
629
+ }
630
+
631
+ var fileConfig = readProjectConfig();
632
+ var envTag = String(process.env.EMPIRICAL_PROJECT_TAG || '').trim().toLowerCase();
633
+ var envTopics = String(process.env.EMPIRICAL_TOPICS || '').split(',').map(function (t) { return t.trim(); }).filter(Boolean);
634
+
635
+ var tag = envTag || fileConfig.project;
636
+ var tagSource = envTag ? 'env' : (fileConfig.project ? 'config' : 'cwd');
637
+ if (!tag) {
638
+ try {
639
+ tag = String(path.basename(process.cwd() || '') || '').trim().toLowerCase();
640
+ } catch (e) {
641
+ tag = '';
642
+ }
643
+ }
644
+
645
+ var topics = envTopics.length ? envTopics : fileConfig.topics;
646
+ var contextMatch = topics.length
647
+ ? topics.join(', ')
648
+ : 'project context, conventions, recent decisions, user preferences';
649
+
650
+ appendLog('project tag=' + (tag || '(none)') + ' (source=' + tagSource + '), topics=' + (topics.length ? topics.join('|') : '(default)'));
651
+
652
+ // Scope every query to the project. Measured 2026-09-16: with no tag filter all 8 slots went to
653
+ // one unrelated project during a full session in a different repo, so the only automatic context
654
+ // rail in the product was spending every slot on the wrong thing. A tag filter also disables the
655
+ // server's agent-process-note exclusion, which is what makes a project's own scar tissue and
656
+ // work history reachable here at all.
657
+ //
658
+ // Open items get their OWN query instead of competing for rank. Tested 2026-09-16: a due-dated
659
+ // memory did not surface in the generic top-8 with or without a project filter, because dueness
660
+ // is not a semantic property. Anything that must be seen needs a reserved slot.
661
+ // AND, not OR: this must be THIS project's todos. No --status filter on purpose, because todos
662
+ // written without a data.status would silently vanish from the one place they get surfaced;
663
+ // the label tells the reader to confirm instead.
664
+ var todos = tag ? fetchMemories('open todo, next action, follow-up, due', tag + ',todo', 3, true) : [];
665
+ var context = tag ? fetchMemories(contextMatch, tag, 6) : [];
666
+
667
+ // A corpus whose tags do not match the resolved project must never end up worse off than before
668
+ // this change, so fall back to the original unscoped query.
669
+ if (context.length === 0) {
670
+ appendLog('project-scoped query returned nothing, falling back to unscoped');
671
+ context = fetchMemories(contextMatch, '', 8);
672
+ }
673
+
674
+ if (todos.length === 0 && context.length === 0) {
675
+ appendLog('memory query returned zero results');
676
+ console.log('{}');
677
+ process.exit(0);
678
+ }
679
+
680
+ var openCount = todos.length;
681
+ var results = todos.concat(context);
682
+
683
+ // Summaries in a mature corpus run to thousands of characters. Injecting eight in full is a wall
684
+ // of text that gets skimmed past, which fails the same way as never injecting them at all:
685
+ // presence in context is not attention. Truncate hard; the agent can query for the rest.
686
+ var lines = results.slice(0, 9).map(function (r, i) {
687
+ var category = r && r.category ? r.category : 'memory';
688
+ var summary = String(r && r.summary ? r.summary : '');
689
+ summary = summary.split('\\n').join(' ').split('\\r').join(' ').split('\\t').join(' ').trim();
690
+ if (summary.length > 240) { summary = summary.slice(0, 237) + '...'; }
691
+ var prefix = i < openCount ? '- [OPEN ITEM, confirm status] ' : '- [' + category + '] ';
692
+ return prefix + summary;
693
+ });
694
+ lines.push('- Before risky or repeated work, ask first: empirical memory query --match "<what you are about to do>" --tags scar-tissue');
695
+
696
+ // Logged only - Copilot's sessionStart event has no field that surfaces this to the model.
697
+ appendLog('memory query returned ' + results.length + ' result(s) (session-start has no output channel to inject them, logged only): ' + lines.join(' | '));
698
+ console.log('{}');
699
+ process.exit(0);
700
+ }
701
+
702
+ try {
703
+ main();
704
+ } catch (e) {
705
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
706
+ console.log('{}');
707
+ process.exit(0);
708
+ }
709
+ `;
710
+
711
+ // Codex-only variant of the Stop reminder. Confirmed live (2026-08-08, via a real `codex
712
+ // exec` run) that Codex's Stop hook specifically requires a { systemMessage: "..." } JSON shape
713
+ // on stdout - plain text makes Codex report the hook as failed. Distinct from Claude's own JSON
714
+ // shape (hookSpecificOutput.additionalContext, see CLAUDE_HOOK_STOP_SOURCE below) and Copilot's
715
+ // (decision/reason, see COPILOT_HOOK_STOP_SOURCE) - each host has its own schema here.
716
+ const CODEX_HOOK_STOP_SOURCE = `#!/usr/bin/env node
717
+ 'use strict';
718
+
719
+ var fs = require('fs');
720
+ var os = require('os');
721
+ var path = require('path');
722
+
723
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
724
+ var MAX_LOG_BYTES = 200 * 1024;
725
+
726
+ function appendLog(line) {
727
+ try {
728
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
729
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
730
+ var stat = fs.statSync(LOG_PATH);
731
+ if (stat.size > MAX_LOG_BYTES) {
732
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
733
+ fs.writeFileSync(LOG_PATH, tail);
734
+ }
735
+ } catch (e) {
736
+ // Diagnostics must never break the hook.
737
+ }
738
+ }
739
+
740
+ function readStdinPayload() {
741
+ try {
742
+ var raw = fs.readFileSync(0, 'utf8');
743
+ return raw ? JSON.parse(raw) : {};
744
+ } catch (e) {
745
+ return {};
746
+ }
747
+ }
748
+
749
+ function main() {
750
+ var payload = readStdinPayload();
751
+
752
+ if (payload && payload.stop_hook_active === true) {
753
+ appendLog('stop_hook_active=true, skipping reminder');
754
+ process.exit(0);
755
+ }
756
+
757
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
758
+
759
+ console.log(JSON.stringify({
760
+ systemMessage: '[Empirical reminder] Before finishing: if this turn included a completed decision, a corrected mistake, or meaningful work worth remembering, record it now, one memory per finding (a fix, a root cause, a decision, a lesson), via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill or \`empirical memory record\`. Local notes are not recorded. Do not wait to be asked.'
761
+ }));
762
+ process.exit(0);
763
+ }
764
+
765
+ try {
766
+ main();
767
+ } catch (e) {
768
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
769
+ process.exit(0);
770
+ }
771
+ `;
772
+
773
+ // Copilot-only variant of the Stop reminder above. Per GitHub's own hooks reference (fetched
774
+ // 2026-08-08): agentStop's output schema is { decision: "block"|"allow", reason, modifiedResponse }
775
+ // - there is no plain message field, so surfacing a reminder means returning decision:"block"
776
+ // with reason as the forced-continuation prompt text. Confirmed this has the same loop-prevention
777
+ // contract Claude Code uses: the input payload includes stop_hook_active ("true when this turn
778
+ // was already forced to continue by a prior 'block' decision" - same semantics, same field name
779
+ // as Claude's), and Copilot has its own hard backstop besides ("After 8 consecutive block
780
+ // continuations, the CLI overrides the hook and ends the turn anyway"). Checking stop_hook_active
781
+ // here means this hook only ever forces one continuation, never chains into that backstop.
782
+ const COPILOT_HOOK_STOP_SOURCE = `#!/usr/bin/env node
783
+ 'use strict';
784
+
785
+ var fs = require('fs');
786
+ var os = require('os');
787
+ var path = require('path');
788
+
789
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
790
+ var MAX_LOG_BYTES = 200 * 1024;
791
+
792
+ function appendLog(line) {
793
+ try {
794
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
795
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
796
+ var stat = fs.statSync(LOG_PATH);
797
+ if (stat.size > MAX_LOG_BYTES) {
798
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
799
+ fs.writeFileSync(LOG_PATH, tail);
800
+ }
801
+ } catch (e) {
802
+ // Diagnostics must never break the hook.
803
+ }
804
+ }
805
+
806
+ function readStdinPayload() {
807
+ try {
808
+ var raw = fs.readFileSync(0, 'utf8');
809
+ return raw ? JSON.parse(raw) : {};
810
+ } catch (e) {
811
+ return {};
812
+ }
813
+ }
814
+
815
+ function main() {
816
+ var payload = readStdinPayload();
817
+
818
+ if (payload && payload.stop_hook_active === true) {
819
+ appendLog('stop_hook_active=true, skipping reminder (already forced one continuation this turn)');
820
+ console.log('{}');
821
+ process.exit(0);
822
+ }
823
+
824
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + '), forcing one continuation to surface reminder');
825
+
826
+ console.log(JSON.stringify({
827
+ decision: 'block',
828
+ reason: '[Empirical reminder] Before finishing: if this turn included a completed decision, a corrected mistake, or meaningful work worth remembering, record it now, one memory per finding (a fix, a root cause, a decision, a lesson), via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill or \`empirical memory record\`. Local notes are not recorded. Do not wait to be asked.'
829
+ }));
830
+ process.exit(0);
831
+ }
832
+
833
+ try {
834
+ main();
835
+ } catch (e) {
836
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
837
+ console.log('{}');
838
+ process.exit(0);
839
+ }
840
+ `;
841
+
842
+ // Claude-only variant of the Stop reminder above. hookSpecificOutput.additionalContext (stdout,
843
+ // exit 0) is Claude Code's non-blocking Stop-hook feedback channel: the text is fed into context
844
+ // and the conversation continues, same outcome the earlier exit-2 approach achieved, but the
845
+ // transcript UI renders it as a plain system reminder instead of a red "Stop hook error" line.
846
+ // Codex needs its own systemMessage shape (CODEX_HOOK_STOP_SOURCE) and Copilot its own
847
+ // decision/reason shape (COPILOT_HOOK_STOP_SOURCE) - plain console.log output (what this hook
848
+ // used before the additionalContext fix) never reaches the model on any of the three hosts.
849
+ const CLAUDE_HOOK_STOP_SOURCE = `#!/usr/bin/env node
850
+ 'use strict';
851
+
852
+ var fs = require('fs');
853
+ var os = require('os');
854
+ var path = require('path');
855
+
856
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'stop.log');
857
+ var MAX_LOG_BYTES = 200 * 1024;
858
+
859
+ function appendLog(line) {
860
+ try {
861
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
862
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
863
+ var stat = fs.statSync(LOG_PATH);
864
+ if (stat.size > MAX_LOG_BYTES) {
865
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
866
+ fs.writeFileSync(LOG_PATH, tail);
867
+ }
868
+ } catch (e) {
869
+ // Diagnostics must never break the hook.
870
+ }
871
+ }
872
+
873
+ function readStdinPayload() {
874
+ try {
875
+ var raw = fs.readFileSync(0, 'utf8');
876
+ return raw ? JSON.parse(raw) : {};
877
+ } catch (e) {
878
+ return {};
879
+ }
880
+ }
881
+
882
+ function main() {
883
+ var payload = readStdinPayload();
884
+
885
+ // stop_hook_active === true means Claude is re-invoking this hook because a PRIOR Stop hook
886
+ // (possibly this same one) already surfaced additionalContext and forced a continuation this
887
+ // turn. additionalContext causes the same forced-continuation behavior decision:block does -
888
+ // confirmed empirically: without this guard the hook re-fired every ~2-3s in an infinite loop,
889
+ // since each additionalContext output triggers another Stop event. Must exit 0 with no output
890
+ // here, unconditionally, or the loop continues.
891
+ if (payload && payload.stop_hook_active === true) {
892
+ appendLog('stop_hook_active=true, skipping reminder (already surfaced once this turn)');
893
+ process.exit(0);
894
+ }
895
+
896
+ appendLog('stop hook fired (pid=' + process.pid + ', platform=' + process.platform + '), surfacing reminder via additionalContext');
897
+
898
+ process.stdout.write(JSON.stringify({
899
+ hookSpecificOutput: {
900
+ hookEventName: 'Stop',
901
+ additionalContext: '[Empirical] Record memory-worthy work now: one memory per finding (a fix, a root cause, a decision, a lesson) via the empirical-memory, empirical-work-history, or empirical-scar-tissue skill. Local notes are not recorded.'
902
+ }
903
+ }) + '\\n');
904
+ process.exit(0);
905
+ }
906
+
907
+ // See EMPIRICAL_HOOK_SESSION_START_SOURCE's identical guard: a crash here must degrade to a
908
+ // silent no-op, never a visible "hook failed" error in the host CLI.
909
+ try {
910
+ main();
911
+ } catch (e) {
912
+ try { appendLog('uncaught error in main(): ' + (e && e.message)); } catch (_e) { /* best effort */ }
913
+ process.exit(0);
914
+ }
915
+ `;
916
+
917
+ // UserPromptSubmit: fires before each turn is processed (Claude, Codex, and Copilot all support
918
+ // this event under the same name per each platform's docs/source). This is the recall-side
919
+ // counterpart to Stop's write-side reminder - deliberately a STATIC message, not a live
920
+ // `empirical memory query` call: a prior per-turn hook in this codebase was removed for making an
921
+ // unconditional network call on every single prompt (see the comment above installClaudeHooks),
922
+ // and re-adding that cost here on three platforms at once was an explicit no per product decision.
923
+ // The message itself is generated per-install from the actual plugin set being installed, not one
924
+ // fixed string for everyone - e.g. someone who declined empirical-scar-tissue at install time
925
+ // never sees a scar-tissue reminder, since that capability isn't actually available to them.
926
+ function buildPromptReminderMessage(pluginNames, platform) {
927
+ const names = normalizePluginNames(pluginNames);
928
+ const lines = [
929
+ '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.'
930
+ ];
931
+ if (names.includes('empirical-work-history')) {
932
+ lines.push('If you are picking up previously completed work, check for a recent work-history entry before assuming there is none.');
933
+ // Codex Stop runs after its final response has already been emitted, so it can only be an
934
+ // advisory reminder. Put the completion gate into the pre-response context instead, where
935
+ // Codex can still act on it. Keep this Codex-specific: Claude and Copilot have their own
936
+ // stop-hook control flows and should not receive a changed prompt contract here.
937
+ if (platform === 'codex') {
938
+ lines.push('If this turn results in meaningful completed work, BEFORE sending your final response you MUST use the empirical-work-history skill or record it via Empirical. The entry must carry tag work-history and mass 1; verify the create receipt. CLI fallback must use --json-file with data.session and data.git; do not use the shorthand record command for coding work. Do not wait for the Stop hook.');
939
+ }
940
+ }
941
+ if (names.includes('empirical-scar-tissue')) {
942
+ lines.push('Check for scar tissue before repeating a past mistake in this area.');
943
+ }
944
+ if (names.includes('empirical-todo')) {
945
+ lines.push('If there is an open todo for this project, check it before starting new work.');
946
+ }
947
+ return '[Empirical reminder] ' + lines.join(' ');
948
+ }
949
+
950
+ // Builds the full UserPromptSubmit hook script source with the tailored message baked in at
951
+ // generation time (via JSON.stringify, so the message is embedded as a single already-escaped
952
+ // string literal - substituted through `${}`, not written as raw template-literal source text,
953
+ // which is what caused the earlier comment-escaping bug in this same file. Never do the latter).
954
+ // `platform`:
955
+ // - 'codex': Codex's required hookSpecificOutput.additionalContext JSON shape (confirmed live
956
+ // 2026-08-08 via a real `codex exec` run - plain text made Codex report the hook as failed).
957
+ // - 'copilot': Copilot's userPromptSubmitted event has NO additionalContext-equivalent field at
958
+ // all (confirmed via GitHub's own hooks reference, fetched 2026-08-08) - the only output field
959
+ // is modifiedPrompt, which REPLACES the prompt for the rest of the turn. So this reads the
960
+ // real prompt text from stdin's `prompt` field and returns it with the reminder appended -
961
+ // more invasive than Claude/Codex's side-channel injection (it's now part of the visible
962
+ // prompt), but it's the only mechanism this event actually has. Falls back to {} (leave
963
+ // unchanged) if stdin can't be read/parsed or has no prompt field, so a parsing edge case can
964
+ // never corrupt or blank out the user's actual prompt.
965
+ // - default (Claude/Copilot's plain console.log was the old assumption for both - WRONG for
966
+ // Copilot, which requires valid JSON on stdout for every event, confirmed via the same fetch
967
+ // above): plain console.log, confirmed correct for Claude only.
968
+ function buildUserPromptSubmitHookSource(pluginNames, platform) {
969
+ const messageLiteral = JSON.stringify(buildPromptReminderMessage(pluginNames, platform));
970
+
971
+ let stdinHelper = '';
972
+ let outputStatement;
973
+ if (platform === 'codex') {
974
+ outputStatement = `console.log(JSON.stringify({
975
+ hookSpecificOutput: {
976
+ hookEventName: 'UserPromptSubmit',
977
+ additionalContext: ${messageLiteral}
978
+ }
979
+ }));`;
980
+ } else if (platform === 'copilot') {
981
+ stdinHelper = `
982
+ function readStdinPayload() {
983
+ try {
984
+ var raw = fs.readFileSync(0, 'utf8');
985
+ return raw ? JSON.parse(raw) : {};
986
+ } catch (e) {
987
+ return {};
988
+ }
989
+ }
990
+ `;
991
+ outputStatement = `var payload = readStdinPayload();
992
+ if (payload && typeof payload.prompt === 'string' && payload.prompt.length > 0) {
993
+ console.log(JSON.stringify({
994
+ modifiedPrompt: payload.prompt + '\\n\\n' + ${messageLiteral}
995
+ }));
996
+ } else {
997
+ appendLog('no usable prompt field on stdin payload, leaving prompt unchanged');
998
+ console.log('{}');
999
+ }`;
1000
+ } else {
1001
+ outputStatement = `console.log(${messageLiteral});`;
1002
+ }
1003
+
1004
+ return `#!/usr/bin/env node
1005
+ 'use strict';
1006
+
1007
+ var fs = require('fs');
1008
+ var os = require('os');
1009
+ var path = require('path');
1010
+
1011
+ var LOG_PATH = path.join(os.homedir(), '.empirical', 'hooks', 'user-prompt-submit.log');
1012
+ var MAX_LOG_BYTES = 200 * 1024;
1013
+
1014
+ function appendLog(line) {
1015
+ try {
1016
+ fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
1017
+ fs.appendFileSync(LOG_PATH, '[' + new Date().toISOString() + '] ' + line + '\\n');
1018
+ var stat = fs.statSync(LOG_PATH);
1019
+ if (stat.size > MAX_LOG_BYTES) {
1020
+ var tail = fs.readFileSync(LOG_PATH, 'utf8').slice(-MAX_LOG_BYTES / 2);
1021
+ fs.writeFileSync(LOG_PATH, tail);
1022
+ }
1023
+ } catch (e) {
1024
+ // Diagnostics must never break the hook.
1025
+ }
1026
+ }
1027
+ ${stdinHelper}
1028
+ // A crash here must degrade to a silent no-op, never a visible "hook failed" error in the host CLI.
1029
+ try {
1030
+ appendLog('user-prompt-submit hook fired (pid=' + process.pid + ', platform=' + process.platform + ')');
1031
+ ${outputStatement}
1032
+ } catch (e) {
1033
+ try { appendLog('uncaught error: ' + (e && e.message)); } catch (_e) { /* best effort */ }
1034
+ }
1035
+ process.exit(0);
1036
+ `;
1037
+ }
1038
+
1039
+ function getEmpiricalHooksDir() {
1040
+ return path.join(os.homedir(), '.empirical', 'hooks');
1041
+ }
1042
+
1043
+ function buildHookCommand(scriptPath) {
1044
+ return `"${process.execPath}" "${scriptPath}"`;
1045
+ }
1046
+
1047
+ // Confirmed live (2026-08-08, via a real `copilot -p` run with debug logging): Copilot runs a
1048
+ // hook's "command"/"powershell" field through powershell.exe on Windows, and a bare
1049
+ // `"path" "arg"` string is not valid PowerShell syntax without the call operator (&) - two
1050
+ // adjacent quoted string literals with nothing between them is a ParserError
1051
+ // ("Unexpected token '...' in expression or statement"), not a "file not found"-style failure.
1052
+ // This is a completely different bug from Codex's (which needed 8.3 short paths to avoid
1053
+ // quoting) - no short-path workaround is needed here, just the operator PowerShell requires
1054
+ // before an executable path.
1055
+ function buildPowershellHookCommand(scriptPath) {
1056
+ return `& "${process.execPath}" "${scriptPath}"`;
1057
+ }
1058
+
1059
+ function removeEmpiricalHookEntries(entries, scriptPath) {
1060
+ if (!Array.isArray(entries)) return [];
1061
+ return entries
1062
+ .map((entry) => {
1063
+ if (!entry || !Array.isArray(entry.hooks)) return entry;
1064
+ const filteredHooks = entry.hooks.filter(
1065
+ (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
1066
+ );
1067
+ return { ...entry, hooks: filteredHooks };
1068
+ })
1069
+ .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
1070
+ }
1071
+
1072
+ function installClaudeHooks(pluginNames) {
1073
+ const hooksDir = getEmpiricalHooksDir();
1074
+ ensureDir(hooksDir);
1075
+
1076
+ // A prior version of this hook made an unconditional `empirical memory query` network call on
1077
+ // every single prompt and was removed for being wasteful (see git history). This is a
1078
+ // deliberate reintroduction at the SAME script path, but with fundamentally different content:
1079
+ // a static, install-time-generated reminder with no network call at all - the cost concern that
1080
+ // killed the old version does not apply to a plain stdout write.
1081
+ const userPromptScriptPath = path.join(hooksDir, 'claude-user-prompt-submit.js');
1082
+ const sessionStartScriptPath = path.join(hooksDir, 'claude-session-start.js');
1083
+ const stopScriptPath = path.join(hooksDir, 'claude-stop.js');
1084
+ writeFile(sessionStartScriptPath, CLAUDE_HOOK_SESSION_START_SOURCE);
1085
+ writeFile(stopScriptPath, CLAUDE_HOOK_STOP_SOURCE);
1086
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames));
1087
+
1088
+ const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
1089
+ const settings = readJsonIfExists(settingsPath) || {};
1090
+ if (!settings.hooks || typeof settings.hooks !== 'object') {
1091
+ settings.hooks = {};
1092
+ }
1093
+
1094
+ settings.hooks.UserPromptSubmit = removeEmpiricalHookEntries(settings.hooks.UserPromptSubmit, userPromptScriptPath);
1095
+ settings.hooks.UserPromptSubmit.push({
1096
+ hooks: [{ type: 'command', command: buildHookCommand(userPromptScriptPath), timeout: 10 }]
1097
+ });
1098
+
1099
+ settings.hooks.SessionStart = removeEmpiricalHookEntries(settings.hooks.SessionStart, sessionStartScriptPath);
1100
+ for (const matcher of ['startup', 'resume', 'compact']) {
1101
+ settings.hooks.SessionStart.push({
1102
+ matcher,
1103
+ hooks: [{ type: 'command', command: buildHookCommand(sessionStartScriptPath), timeout: 25 }]
1104
+ });
1105
+ }
1106
+
1107
+ settings.hooks.Stop = removeEmpiricalHookEntries(settings.hooks.Stop, stopScriptPath);
1108
+ settings.hooks.Stop.push({
1109
+ hooks: [{ type: 'command', command: buildHookCommand(stopScriptPath), timeout: 10 }]
1110
+ });
1111
+
1112
+ writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
1113
+ log(' - Claude SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
1114
+ }
1115
+
1116
+ // Codex CLI ships a real hooks system (confirmed against openai/codex source — codex-rs/hooks,
1117
+ // codex-rs/config/src/hook_config.rs — not assumed from docs alone, since third-party writeups
1118
+ // disagreed on Windows support). It reads <CODEX_HOME>/hooks.json (JSON, not the config.toml
1119
+ // used for MCP/model settings — a separate file, so this never touches config.toml) shaped as
1120
+ // { hooks: { SessionStart: [{ matcher, hooks: [{ type: 'command', command, commandWindows,
1121
+ // timeout }] }], ... } }. CODEX_HOME defaults to ~/.codex when unset, same convention as
1122
+ // ~/.claude for Claude Code.
1123
+ function getCodexHomeDir() {
1124
+ return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
1125
+ }
1126
+
1127
+ function removeEmpiricalHooksJsonEntries(entries, scriptPath) {
1128
+ if (!Array.isArray(entries)) return [];
1129
+ return entries
1130
+ .map((entry) => {
1131
+ if (!entry || !Array.isArray(entry.hooks)) return entry;
1132
+ const filteredHooks = entry.hooks.filter(
1133
+ (h) => !(h && typeof h.command === 'string' && h.command.includes(scriptPath))
1134
+ );
1135
+ return { ...entry, hooks: filteredHooks };
1136
+ })
1137
+ .filter((entry) => entry && (!Array.isArray(entry.hooks) || entry.hooks.length > 0));
1138
+ }
1139
+
1140
+ // Codex's Windows sandbox (confirmed via `codex doctor` -> "filesystem sandbox: restricted" and
1141
+ // ~/.codex/.sandbox/sandbox.*.log's "processed N write roots (read roots delegated)" / "applying
1142
+ // read ACLs" at session start) scopes filesystem access per-session to project-specific roots
1143
+ // plus, necessarily, CODEX_HOME itself (Codex reads hooks.json, its state db, and its plugin
1144
+ // cache from there on every session regardless of project). The shared `~/.empirical/hooks`
1145
+ // directory used by Claude/Copilot is neither - so under this sandbox, node.exe most likely
1146
+ // cannot even read a hook script living there, which is why hooks fail identically (exit 1)
1147
+ // across SessionStart/UserPromptSubmit/Stop regardless of what each script actually does,
1148
+ // including the trivial UserPromptSubmit script that spawns no subprocess at all. Claude Code
1149
+ // hooks are unaffected (confirmed working from the shared dir) and Copilot has shown no such
1150
+ // failure, so only Codex's copies are relocated here - Claude/Copilot keep using
1151
+ // getEmpiricalHooksDir() unchanged.
1152
+ function getCodexHooksScriptsDir() {
1153
+ return path.join(getCodexHomeDir(), 'empirical-hooks');
1154
+ }
1155
+
1156
+ // Confirmed live (2026-08-08, via a real `codex exec` run): Codex's Windows hook launcher fails
1157
+ // to parse a quoted executable path (e.g. `"C:\Program Files\nodejs\node.exe" "<script>"`,
1158
+ // otherwise a perfectly standard Windows command line - Claude Code and every direct shell/
1159
+ // spawnSync invocation handle it fine) and reports the hook as a nonzero-exit failure before any
1160
+ // of the script's own JS ever runs. Windows 8.3 short path names never contain spaces, so
1161
+ // resolving both the node executable and the script path to their short form and joining them
1162
+ // unquoted sidesteps the parser entirely. Computed once at install time (not per hook
1163
+ // invocation), so a synchronous shell call here is an acceptable cost.
1164
+ function getWindowsShortPath(longPath) {
1165
+ if (process.platform !== 'win32') return null;
1166
+ try {
1167
+ const { execSync } = require('child_process');
1168
+ const out = execSync(`cmd /c for %I in ("${longPath}") do @echo %~sI`, { encoding: 'utf8', timeout: 5000 });
1169
+ const short = out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
1170
+ const fs = require('fs');
1171
+ return short && fs.existsSync(short) ? short : null;
1172
+ } catch (e) {
1173
+ return null;
1174
+ }
1175
+ }
1176
+
1177
+ // Builds Codex's commandWindows value using short paths so neither the executable nor the script
1178
+ // path ever needs quoting. Falls back to the normal quoted buildHookCommand() form if short-path
1179
+ // resolution fails for any reason (e.g. 8.3 name generation disabled on that volume) - degraded
1180
+ // (same behavior as before this fix) rather than broken.
1181
+ function buildCodexWindowsHookCommand(scriptPath) {
1182
+ const shortNode = getWindowsShortPath(process.execPath);
1183
+ const shortScript = getWindowsShortPath(scriptPath);
1184
+ if (shortNode && shortScript) {
1185
+ return `${shortNode} ${shortScript}`;
1186
+ }
1187
+ return buildHookCommand(scriptPath);
1188
+ }
1189
+
1190
+ function installCodexHooks(pluginNames) {
1191
+ const fs = require('fs');
1192
+ const legacyHooksDir = getEmpiricalHooksDir();
1193
+ const hooksDir = getCodexHooksScriptsDir();
1194
+ ensureDir(hooksDir);
1195
+
1196
+ const sessionStartScriptPath = path.join(hooksDir, 'codex-session-start.js');
1197
+ const stopScriptPath = path.join(hooksDir, 'codex-stop.js');
1198
+ const userPromptScriptPath = path.join(hooksDir, 'codex-user-prompt-submit.js');
1199
+ writeFile(sessionStartScriptPath, CODEX_HOOK_SESSION_START_SOURCE);
1200
+ writeFile(stopScriptPath, CODEX_HOOK_STOP_SOURCE);
1201
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'codex'));
1202
+
1203
+ // Best-effort cleanup of the pre-relocation script files/entries at the old shared path, so a
1204
+ // machine that already had Codex hooks installed doesn't end up with both the old (broken
1205
+ // under the sandbox) and new registration firing redundantly.
1206
+ const legacySessionStartScriptPath = path.join(legacyHooksDir, 'codex-session-start.js');
1207
+ const legacyStopScriptPath = path.join(legacyHooksDir, 'codex-stop.js');
1208
+ const legacyUserPromptScriptPath = path.join(legacyHooksDir, 'codex-user-prompt-submit.js');
1209
+ for (const legacyPath of [legacySessionStartScriptPath, legacyStopScriptPath, legacyUserPromptScriptPath]) {
1210
+ try {
1211
+ if (fs.existsSync(legacyPath)) fs.unlinkSync(legacyPath);
1212
+ } catch (_error) {
1213
+ // best-effort cleanup only
1214
+ }
1215
+ }
1216
+
1217
+ const hooksJsonPath = path.join(getCodexHomeDir(), 'hooks.json');
1218
+ const hooksFile = readJsonIfExists(hooksJsonPath) || {};
1219
+ if (!hooksFile.hooks || typeof hooksFile.hooks !== 'object') {
1220
+ hooksFile.hooks = {};
1221
+ }
1222
+
1223
+ hooksFile.hooks.SessionStart = removeEmpiricalHooksJsonEntries(
1224
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.SessionStart, sessionStartScriptPath),
1225
+ legacySessionStartScriptPath
1226
+ );
1227
+ const sessionStartCommand = buildHookCommand(sessionStartScriptPath);
1228
+ const sessionStartCommandWindows = buildCodexWindowsHookCommand(sessionStartScriptPath);
1229
+ for (const matcher of ['startup', 'resume']) {
1230
+ hooksFile.hooks.SessionStart.push({
1231
+ matcher,
1232
+ hooks: [{ type: 'command', command: sessionStartCommand, commandWindows: sessionStartCommandWindows, timeout: 25 }]
1233
+ });
1234
+ }
1235
+
1236
+ hooksFile.hooks.Stop = removeEmpiricalHooksJsonEntries(
1237
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.Stop, stopScriptPath),
1238
+ legacyStopScriptPath
1239
+ );
1240
+ const stopCommand = buildHookCommand(stopScriptPath);
1241
+ const stopCommandWindows = buildCodexWindowsHookCommand(stopScriptPath);
1242
+ hooksFile.hooks.Stop.push({
1243
+ hooks: [{ type: 'command', command: stopCommand, commandWindows: stopCommandWindows, timeout: 10 }]
1244
+ });
1245
+
1246
+ // Confirmed against codex-rs/config/src/hook_config.rs's HookEventsToml serde renames: the
1247
+ // config-file key is PascalCase "UserPromptSubmit", same casing convention as SessionStart/Stop.
1248
+ hooksFile.hooks.UserPromptSubmit = removeEmpiricalHooksJsonEntries(
1249
+ removeEmpiricalHooksJsonEntries(hooksFile.hooks.UserPromptSubmit, userPromptScriptPath),
1250
+ legacyUserPromptScriptPath
1251
+ );
1252
+ const userPromptCommand = buildHookCommand(userPromptScriptPath);
1253
+ const userPromptCommandWindows = buildCodexWindowsHookCommand(userPromptScriptPath);
1254
+ hooksFile.hooks.UserPromptSubmit.push({
1255
+ hooks: [{ type: 'command', command: userPromptCommand, commandWindows: userPromptCommandWindows, timeout: 10 }]
1256
+ });
1257
+
1258
+ writeFile(hooksJsonPath, `${JSON.stringify(hooksFile, null, 2)}\n`);
1259
+ log(' - Codex SessionStart + UserPromptSubmit + Stop hooks installed for deterministic memory lookups and reminders.');
1260
+ }
1261
+
1262
+ // GitHub Copilot CLI's hook config is one JSON file per hook under ~/.copilot/hooks/ (any
1263
+ // filename — confirmed via GitHub's own docs at docs.github.com/en/copilot/reference/hooks-
1264
+ // reference), so unlike Claude/Codex this never needs to merge into a shared file: Empirical
1265
+ // owns this file outright and can just overwrite it. Event key for turn-end is "agentStop"
1266
+ // ("the main agent finishes a turn" per the same docs) — not "stop"/"Stop" like Claude/Codex.
1267
+ // Schema: { version: 1, hooks: { sessionStart: [...], agentStop: [...] } }.
1268
+ function installCopilotHooks(pluginNames) {
1269
+ const hooksDir = getEmpiricalHooksDir();
1270
+ ensureDir(hooksDir);
1271
+
1272
+ const sessionStartScriptPath = path.join(hooksDir, 'copilot-session-start.js');
1273
+ const stopScriptPath = path.join(hooksDir, 'copilot-stop.js');
1274
+ const userPromptScriptPath = path.join(hooksDir, 'copilot-user-prompt-submit.js');
1275
+ writeFile(sessionStartScriptPath, COPILOT_HOOK_SESSION_START_SOURCE);
1276
+ writeFile(stopScriptPath, COPILOT_HOOK_STOP_SOURCE);
1277
+ writeFile(userPromptScriptPath, buildUserPromptSubmitHookSource(pluginNames, 'copilot'));
1278
+
1279
+ const copilotHooksDir = path.join(os.homedir(), '.copilot', 'hooks');
1280
+ ensureDir(copilotHooksDir);
1281
+
1282
+ // Prior versions of this installer wrote a single-purpose "empirical-session-start.json" —
1283
+ // remove it now that both events live in one unified file, so a stale duplicate registration
1284
+ // never lingers alongside the new one.
1285
+ const legacyHookFilePath = path.join(copilotHooksDir, 'empirical-session-start.json');
1286
+ try {
1287
+ const fs = require('fs');
1288
+ if (fs.existsSync(legacyHookFilePath)) fs.unlinkSync(legacyHookFilePath);
1289
+ } catch (_error) {
1290
+ // best-effort cleanup only
1291
+ }
1292
+
1293
+ const hookFilePath = path.join(copilotHooksDir, 'empirical-hooks.json');
1294
+ // Both `command` (POSIX fallback) and `powershell` (Windows-explicit, with the & call operator
1295
+ // PowerShell requires - see buildPowershellHookCommand) are always set: per GitHub's hooks
1296
+ // reference, an explicit `powershell` entry takes precedence over `command` on Windows, so this
1297
+ // is correct on both platforms without needing to detect the install-time OS here.
1298
+ const hookFileContent = {
1299
+ version: 1,
1300
+ hooks: {
1301
+ sessionStart: [
1302
+ {
1303
+ type: 'command',
1304
+ command: buildHookCommand(sessionStartScriptPath),
1305
+ powershell: buildPowershellHookCommand(sessionStartScriptPath),
1306
+ timeoutSec: 15
1307
+ }
1308
+ ],
1309
+ // "userPromptSubmitted" per GitHub's hooks reference ("The user submits a prompt") - not
1310
+ // "userPromptSubmit" (that camelCase spelling is Claude/Codex's convention, not Copilot's).
1311
+ userPromptSubmitted: [
1312
+ {
1313
+ type: 'command',
1314
+ command: buildHookCommand(userPromptScriptPath),
1315
+ powershell: buildPowershellHookCommand(userPromptScriptPath),
1316
+ timeoutSec: 10
1317
+ }
1318
+ ],
1319
+ agentStop: [
1320
+ {
1321
+ type: 'command',
1322
+ command: buildHookCommand(stopScriptPath),
1323
+ powershell: buildPowershellHookCommand(stopScriptPath),
1324
+ timeoutSec: 10
1325
+ }
1326
+ ]
1327
+ }
1328
+ };
1329
+
1330
+ writeFile(hookFilePath, `${JSON.stringify(hookFileContent, null, 2)}\n`);
1331
+ log(' - Copilot SessionStart + userPromptSubmitted + agentStop hooks installed for deterministic memory lookups and reminders.');
1332
+ }
1333
+
1334
+ module.exports = {
1335
+ CLAUDE_HOOK_SESSION_START_SOURCE,
1336
+ CODEX_HOOK_SESSION_START_SOURCE,
1337
+ COPILOT_HOOK_SESSION_START_SOURCE,
1338
+ CODEX_HOOK_STOP_SOURCE,
1339
+ COPILOT_HOOK_STOP_SOURCE,
1340
+ CLAUDE_HOOK_STOP_SOURCE,
1341
+ buildPromptReminderMessage,
1342
+ buildUserPromptSubmitHookSource,
1343
+ getEmpiricalHooksDir,
1344
+ buildHookCommand,
1345
+ buildPowershellHookCommand,
1346
+ removeEmpiricalHookEntries,
1347
+ installClaudeHooks,
1348
+ getCodexHomeDir,
1349
+ removeEmpiricalHooksJsonEntries,
1350
+ getCodexHooksScriptsDir,
1351
+ getWindowsShortPath,
1352
+ buildCodexWindowsHookCommand,
1353
+ installCodexHooks,
1354
+ installCopilotHooks
1355
+ };