From 21d651cb8e78f79be278c3a0ca7cdb4ed8a81b09 Mon Sep 17 00:00:00 2001 From: rabbit-collab Date: Fri, 30 Oct 2026 03:08:18 -0700 Subject: [PATCH] fix: exit hook runners whose parent process is gone On Windows, Claude Code kills an overrunning hook by killing the bash.exe wrapper; the node.exe runner underneath survives. If another process still holds the write end of the runner's stdin (a handle inherited by a process spawned at the same moment), the runner never sees EOF and waits forever. Orphaned runners were observed living 3-18 hours. Add scripts/hooks/hook-watchdog.js and start it from the four hook entry points (plugin-hook-bootstrap, run-with-flags, posttooluse-dispatcher, lifecycle-hook-bootstrap). It exits the process when the parent PID is gone (Windows) or the process was re-parented (POSIX), polled every 2s, or when a hard deadline passes (330s, above the longest hooks.json timeout, or an earlier inherited ECC_HOOK_DEADLINE_MS). Timers are unref'd so a finished hook is never kept alive. The regression test reproduces the leak with a detached runner whose stdin write end is held by an unrelated process; it fails without the watchdog (runner still alive after 8s) and passes with it. Co-Authored-By: Claude Opus 5.5 --- scripts/hooks/hook-watchdog.js | 103 +++++++++++ scripts/hooks/lifecycle-hook-bootstrap.js | 2 + scripts/hooks/plugin-hook-bootstrap.js | 2 + scripts/hooks/posttooluse-dispatcher.js | 2 + scripts/hooks/run-with-flags.js | 2 + tests/hooks/hook-watchdog.test.js | 215 ++++++++++++++++++++++ 6 files changed, 326 insertions(+) create mode 100644 scripts/hooks/hook-watchdog.js create mode 100644 tests/hooks/hook-watchdog.test.js diff --git a/scripts/hooks/hook-watchdog.js b/scripts/hooks/hook-watchdog.js new file mode 100644 index 00000000000..401f9809946 --- /dev/null +++ b/scripts/hooks/hook-watchdog.js @@ -0,0 +1,103 @@ +'use strict'; + +/** + * Keeps a hook process from outliving the harness that started it. + * + * When Claude Code kills a hook that overran its timeout, it kills the + * process it spawned. On Windows that is the bash.exe wrapper, and the + * node.exe runner underneath survives. The runner then waits on stdin or on a + * stdout flush that never completes, and lingers for hours or days. + * + * The watchdog exits the process when either: + * - the parent that spawned it is gone (Windows: the PID no longer exists; + * POSIX: the process was re-parented), checked every few seconds, or + * - a hard deadline passes. The default sits above the longest hook timeout + * in hooks.json (300s). An earlier ECC_HOOK_DEADLINE_MS from an upstream + * bootstrap takes precedence. + * + * Timers are unref'd, so the watchdog never keeps a finished hook alive. + */ + +const DEFAULT_HARD_DEADLINE_MS = 330000; +const PARENT_POLL_MS = 2000; + +function isProcessAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM: the process exists but belongs to someone else. + return error.code === 'EPERM'; + } +} + +function resolveDeadline(nowMs, env = process.env) { + const hardDeadline = nowMs + DEFAULT_HARD_DEADLINE_MS; + const inherited = Number(env.ECC_HOOK_DEADLINE_MS); + if (Number.isSafeInteger(inherited) && inherited > nowMs) { + return Math.min(hardDeadline, inherited); + } + return hardDeadline; +} + +function installHookWatchdog(options = {}) { + const { + label = 'hook', + env = process.env, + now = Date.now, + getPpid = () => process.ppid, + isAlive = isProcessAlive, + exit = code => process.exit(code), + writeStderr = message => process.stderr.write(message), + pollMs = PARENT_POLL_MS, + setTimer = setTimeout, + setRepeating = setInterval, + clearTimer = clearTimeout, + clearRepeating = clearInterval, + } = options; + + const startPpid = getPpid(); + let disarmed = false; + let deadlineTimer = null; + let parentTimer = null; + + const disarm = () => { + disarmed = true; + if (deadlineTimer) clearTimer(deadlineTimer); + if (parentTimer) clearRepeating(parentTimer); + }; + + const fire = reason => { + if (disarmed) return; + disarm(); + try { + writeStderr(`[Hook] watchdog: ${reason}; exiting ${label}\n`); + } catch { + // stderr may be the broken pipe that got us here + } + exit(0); + }; + + const parentGone = () => getPpid() !== startPpid || !isAlive(startPpid); + + const delay = Math.max(0, resolveDeadline(now(), env) - now()); + deadlineTimer = setTimer(() => fire(`deadline of ${delay}ms passed`), delay); + if (deadlineTimer && typeof deadlineTimer.unref === 'function') deadlineTimer.unref(); + + if (Number.isInteger(startPpid) && startPpid > 1) { + parentTimer = setRepeating(() => { + if (parentGone()) fire(`parent process ${startPpid} is gone`); + }, pollMs); + if (parentTimer && typeof parentTimer.unref === 'function') parentTimer.unref(); + } + + return disarm; +} + +module.exports = { + DEFAULT_HARD_DEADLINE_MS, + PARENT_POLL_MS, + installHookWatchdog, + isProcessAlive, + resolveDeadline, +}; diff --git a/scripts/hooks/lifecycle-hook-bootstrap.js b/scripts/hooks/lifecycle-hook-bootstrap.js index 629e031c94c..3020021f136 100644 --- a/scripts/hooks/lifecycle-hook-bootstrap.js +++ b/scripts/hooks/lifecycle-hook-bootstrap.js @@ -7,6 +7,7 @@ const fs = require('fs'); const { spawnSync } = require('child_process'); const { normalizePluginRootForPlatform } = require('../lib/resolve-ecc-root'); const { readStdinRaw, resolveMaxStdin } = require('./hook-input'); +const { installHookWatchdog } = require('./hook-watchdog'); const { createHookContextScanner } = require('./hook-input-limits'); const DEFAULT_TIMEOUT_MS = 30000; @@ -124,6 +125,7 @@ async function main() { } function cli() { + installHookWatchdog({ label: 'lifecycle hook bootstrap' }); main().catch(error => { writeStderr(`[Hook] lifecycle bootstrap failed: ${error.message}`); process.exitCode = 0; diff --git a/scripts/hooks/plugin-hook-bootstrap.js b/scripts/hooks/plugin-hook-bootstrap.js index 5f05a0aa588..0088a91ed87 100644 --- a/scripts/hooks/plugin-hook-bootstrap.js +++ b/scripts/hooks/plugin-hook-bootstrap.js @@ -10,6 +10,7 @@ const { resolveWindowsBashCandidates } = require('../lib/windows-bash'); const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input'); const { createHookContextScanner } = require('./hook-input-limits'); +const { installHookWatchdog } = require('./hook-watchdog'); const SHELL_PROBE_TIMEOUT_MS = 2000; @@ -323,6 +324,7 @@ async function main() { // exports (tests), require.main is a real, different module, so main() stays // dormant. if (require.main === module || require.main === undefined) { + installHookWatchdog({ label: 'plugin hook bootstrap' }); main().catch(error => { writeStderr(`[Hook] bootstrap failed: ${error.message}\n`); process.exitCode = 0; diff --git a/scripts/hooks/posttooluse-dispatcher.js b/scripts/hooks/posttooluse-dispatcher.js index e81d1fb3717..c72cf239e22 100644 --- a/scripts/hooks/posttooluse-dispatcher.js +++ b/scripts/hooks/posttooluse-dispatcher.js @@ -10,6 +10,7 @@ const path = require('path'); const { StringDecoder } = require('string_decoder'); const { isHookEnabled } = require('../lib/hook-flags'); const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input'); +const { installHookWatchdog } = require('./hook-watchdog'); const { runPostBash } = require('./bash-hook-dispatcher'); const { run: runQualityGate } = require('./quality-gate'); const { run: runDesignQualityCheck } = require('./design-quality-check'); @@ -325,6 +326,7 @@ async function main(options = {}) { } function cli(options = {}) { + installHookWatchdog({ label: 'PostToolUse dispatcher' }); main(options).catch(error => { process.stderr.write(`[Hook] PostToolUse dispatcher failed: ${error.message}\n`); process.exitCode = 0; diff --git a/scripts/hooks/run-with-flags.js b/scripts/hooks/run-with-flags.js index 00c66630896..35efc10206f 100755 --- a/scripts/hooks/run-with-flags.js +++ b/scripts/hooks/run-with-flags.js @@ -14,6 +14,7 @@ const { spawnSync } = require('child_process'); const { StringDecoder } = require('string_decoder'); const { isHookEnabled, isDryRun } = require('../lib/hook-flags'); const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input'); +const { installHookWatchdog } = require('./hook-watchdog'); const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output'); const { createHookContextScanner } = require('./hook-input-limits'); @@ -343,6 +344,7 @@ async function main() { exitWithStdout(legacyStdout, Number.isInteger(result.status) ? result.status : 0); } +installHookWatchdog({ label: 'run-with-flags' }); main().catch(err => { process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`); process.exit(0); diff --git a/tests/hooks/hook-watchdog.test.js b/tests/hooks/hook-watchdog.test.js new file mode 100644 index 00000000000..b583990e6a6 --- /dev/null +++ b/tests/hooks/hook-watchdog.test.js @@ -0,0 +1,215 @@ +/** + * Tests for the hook watchdog: hook runners must not outlive the harness + * process that spawned them. + */ + +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawn } = require('child_process'); +const { + DEFAULT_HARD_DEADLINE_MS, + installHookWatchdog, + isProcessAlive, + resolveDeadline, +} = require('../../scripts/hooks/hook-watchdog'); + +const RUNNER = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'run-with-flags.js'); +const ORPHAN_EXIT_BUDGET_MS = 8000; + +async function test(name, fn) { + try { + await fn(); + console.log(` ✓ ${name}`); + return true; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.message}`); + return false; + } +} + +function fakeClock() { + const timers = []; + return { + timers, + setTimer: (fn, ms) => { const t = { fn, ms, kind: 'once', unref() {} }; timers.push(t); return t; }, + setRepeating: (fn, ms) => { const t = { fn, ms, kind: 'repeat', unref() {} }; timers.push(t); return t; }, + clearTimer: t => { t.cleared = true; }, + clearRepeating: t => { t.cleared = true; }, + }; +} + +function harness(overrides = {}) { + const clock = fakeClock(); + const exits = []; + const messages = []; + let ppid = overrides.ppid === undefined ? 4242 : overrides.ppid; + const alive = new Set([4242]); + const disarm = installHookWatchdog({ + label: 'test hook', + env: overrides.env || {}, + now: () => 1000, + getPpid: () => ppid, + isAlive: pid => alive.has(pid), + exit: code => exits.push(code), + writeStderr: message => messages.push(message), + ...clock, + }); + return { + clock, exits, messages, disarm, alive, + setPpid: value => { ppid = value; }, + deadline: () => clock.timers.find(t => t.kind === 'once'), + poll: () => clock.timers.find(t => t.kind === 'repeat'), + }; +} + +function waitForExit(pid, budgetMs) { + const started = Date.now(); + return new Promise(resolve => { + const check = () => { + if (!isProcessAlive(pid)) return resolve(Date.now() - started); + if (Date.now() - started > budgetMs) return resolve(null); + setTimeout(check, 100); + }; + check(); + }); +} + +async function runTests() { + console.log('\n=== Testing hook-watchdog ===\n'); + let passed = 0; + let failed = 0; + const record = ok => (ok ? passed++ : failed++); + + record(await test('default deadline sits above the longest hook timeout (300s)', () => { + assert.ok(DEFAULT_HARD_DEADLINE_MS > 300000); + assert.strictEqual(resolveDeadline(0, {}), DEFAULT_HARD_DEADLINE_MS); + })); + + record(await test('an earlier inherited ECC_HOOK_DEADLINE_MS wins', () => { + assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: '6000' }), 6000); + })); + + record(await test('a later, past or malformed inherited deadline is ignored', () => { + const hard = 1000 + DEFAULT_HARD_DEADLINE_MS; + assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: String(hard + 5) }), hard); + assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: '500' }), hard); + assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: 'soon' }), hard); + })); + + record(await test('stays quiet while the parent is alive', () => { + const h = harness(); + h.poll().fn(); + h.poll().fn(); + assert.deepStrictEqual(h.exits, []); + })); + + record(await test('exits 0 when the parent PID disappears (Windows orphan)', () => { + const h = harness(); + h.alive.delete(4242); + h.poll().fn(); + assert.deepStrictEqual(h.exits, [0]); + assert.match(h.messages.join(''), /parent process 4242 is gone; exiting test hook/); + })); + + record(await test('exits 0 when the process is re-parented (POSIX orphan)', () => { + const h = harness(); + h.setPpid(1); + h.poll().fn(); + assert.deepStrictEqual(h.exits, [0]); + })); + + record(await test('exits 0 when the hard deadline fires', () => { + const h = harness(); + assert.strictEqual(h.deadline().ms, DEFAULT_HARD_DEADLINE_MS); + h.deadline().fn(); + assert.deepStrictEqual(h.exits, [0]); + assert.match(h.messages.join(''), /deadline/); + })); + + record(await test('fires at most once', () => { + const h = harness(); + h.alive.delete(4242); + h.poll().fn(); + h.deadline().fn(); + assert.deepStrictEqual(h.exits, [0]); + })); + + record(await test('disarm clears both timers and suppresses exits', () => { + const h = harness(); + h.disarm(); + assert.ok(h.deadline().cleared && h.poll().cleared); + h.deadline().fn(); + assert.deepStrictEqual(h.exits, []); + })); + + record(await test('no parent polling when started without a real parent', () => { + const h = harness({ ppid: 1 }); + assert.strictEqual(h.poll(), undefined); + })); + + record(await test('a throwing stderr write still exits', () => { + const clock = fakeClock(); + const exits = []; + installHookWatchdog({ + env: {}, now: () => 0, getPpid: () => 1, exit: code => exits.push(code), + writeStderr: () => { throw new Error('EPIPE'); }, ...clock, + }); + clock.timers[0].fn(); + assert.deepStrictEqual(exits, [0]); + })); + + record(await test('isProcessAlive sees this process and not a dead one', async () => { + assert.strictEqual(isProcessAlive(process.pid), true); + const child = spawn(process.execPath, ['-e', '']); + await new Promise(resolve => child.on('exit', resolve)); + assert.strictEqual(isProcessAlive(child.pid), false); + })); + + record(await test('regression: runner waiting on stdin exits after its parent is killed', async () => { + // The wrapper plays the bash.exe that Claude Code kills on timeout. It + // starts the runner detached, because bash.exe (unlike node) does not take + // its children down with it. The runner inherits the wrapper's stdin, and a + // holder process keeps a copy of that pipe's write end, as a sibling process + // that inherited the handle would. So the runner never sees EOF, and without + // the watchdog it would wait on stdin forever. + const wrapperFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-watchdog-')), 'wrapper.js'); + fs.writeFileSync(wrapperFile, [ + "const { spawn } = require('child_process');", + "const runner = spawn(process.execPath, [process.argv[2], 'pre:test:watchdog', 'scripts/hooks/none.js', 'minimal'],", + " { stdio: ['inherit', 'ignore', 'ignore'], detached: true });", + "process.stdout.write(runner.pid + '\\n');", + "setInterval(() => {}, 1000);", + ].join('\n')); + const wrapper = spawn(process.execPath, [wrapperFile, RUNNER], { stdio: ['pipe', 'pipe', 'pipe'] }); + const holder = spawn(process.execPath, ['-e', `setTimeout(() => {}, ${ORPHAN_EXIT_BUDGET_MS * 2})`], + { stdio: [wrapper.stdin, 'ignore', 'ignore'] }); + let wrapperStderr = ''; + wrapper.stderr.on('data', chunk => { wrapperStderr += chunk; }); + const runnerPid = await new Promise((resolve, reject) => { + wrapper.stdout.once('data', chunk => resolve(Number(String(chunk).trim()))); + wrapper.once('error', reject); + wrapper.once('exit', code => reject(new Error(`wrapper exited early (${code}): ${wrapperStderr.trim()}`))); + }); + try { + assert.ok(isProcessAlive(runnerPid), 'runner should be running before the wrapper is killed'); + wrapper.kill('SIGKILL'); + const exitedAfter = await waitForExit(runnerPid, ORPHAN_EXIT_BUDGET_MS); + assert.notStrictEqual(exitedAfter, null, `orphaned runner ${runnerPid} still alive after ${ORPHAN_EXIT_BUDGET_MS}ms`); + } finally { + try { process.kill(runnerPid, 'SIGKILL'); } catch { /* already gone */ } + holder.kill('SIGKILL'); + wrapper.stdin.destroy(); + fs.rmSync(path.dirname(wrapperFile), { recursive: true, force: true }); + } + })); + + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); + process.exit(failed > 0 ? 1 : 0); +} + +runTests();