diff --git a/scripts/hooks/lifecycle-hook-bootstrap.js b/scripts/hooks/lifecycle-hook-bootstrap.js index 3020021f136..b3add2531cc 100644 --- a/scripts/hooks/lifecycle-hook-bootstrap.js +++ b/scripts/hooks/lifecycle-hook-bootstrap.js @@ -4,7 +4,6 @@ const path = require('path'); const { StringDecoder } = require('string_decoder'); 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'); @@ -82,45 +81,68 @@ async function main() { } const timeout = resolveTimeout(timeoutValue); - const result = spawnSync( - process.execPath, - [runner, hookId, relScriptPath, profilesCsv || 'minimal,standard,strict'], - { - input: raw, - encoding: 'utf8', - env: { - ...process.env, - CLAUDE_PLUGIN_ROOT: resolvedRoot, - ECC_PLUGIN_ROOT: resolvedRoot, - ECC_HOOK_INPUT_MAX_BYTES: String(maxStdin), - ECC_HOOK_INPUT_TRUNCATED_UPSTREAM: truncated ? '1' : '0', - ECC_HOOK_CONTEXT_JSON: JSON.stringify(hookContext), - ECC_HOOK_DEADLINE_MS: String(Date.now() + timeout) - }, - cwd: process.cwd(), - timeout, - maxBuffer: 16 * 1024 * 1024, - windowsHide: true - } - ); - const failed = result.error || result.status === null || result.signal; - const stdout = !failed && typeof result.stdout === 'string' && result.stdout !== raw - ? result.stdout - : ''; - let stderr = typeof result.stderr === 'string' ? result.stderr : ''; - let exitCode = Number.isInteger(result.status) ? result.status : 0; - - if (failed) { - const reason = result.error - ? result.error.message - : result.signal - ? `signal ${result.signal}` - : 'missing exit status'; - stderr += `[Hook] lifecycle runner failed for ${hookId}: ${reason}\n`; + // Run run-with-flags.js in this process instead of spawning a second node for it, as + // plugin-hook-bootstrap.js does (#3853). It sees the environment the child used to get: + // run-with-flags reads ECC_HOOK_INPUT_MAX_BYTES and ECC_HOOK_INPUT_TRUNCATED_UPSTREAM when it + // is loaded, and llm-summary and legacy hook spawns read ECC_HOOK_DEADLINE_MS at call time. + const startedAt = Date.now(); + const deadline = startedAt + timeout; + Object.assign(process.env, { + CLAUDE_PLUGIN_ROOT: resolvedRoot, + ECC_PLUGIN_ROOT: resolvedRoot, + ECC_HOOK_INPUT_MAX_BYTES: String(maxStdin), + ECC_HOOK_INPUT_TRUNCATED_UPSTREAM: truncated ? '1' : '0', + ECC_HOOK_CONTEXT_JSON: JSON.stringify(hookContext), + ECC_HOOK_DEADLINE_MS: String(deadline) + }); + + // The child's spawnSync timeout used to stop an overrunning hook. A watchdog at the lifecycle + // deadline now reports an overrun with the same message and exit code. Being a timer, it fires + // only while the event loop runs: a run() hook that blocks synchronously finishes first. + // Legacy hooks stay hard-bounded, because run-with-flags gives their spawnSync a timeout from + // ECC_HOOK_DEADLINE_MS, and the shipped run() hooks bound their own child-process calls. + // Parent loss is left to the cli() watchdog (getPpid 1 turns off this one's parent poll). + // The watchdog ignores a deadline that has already passed, as it must for a stale inherited + // one. Its clock is held just short of this deadline, so the timer gets what is left of the + // budget, and a budget already spent fires it at once instead of after the 330 s default. + const disarmDeadline = installHookWatchdog({ + label: `lifecycle hook ${hookId}`, + env: { ECC_HOOK_DEADLINE_MS: String(deadline) }, + now: () => Math.min(Date.now(), deadline - 1), + getPpid: () => 1, + writeStderr: () => {}, + exit: () => exitAfterFlush('', `[Hook] lifecycle runner failed for ${hookId}: timed out after ${timeout} ms\n`, 1) + }); + + let stdout = ''; + let exitCode = 0; + let stderr = ''; + try { + const { runHook } = require(runner); + const result = await runHook(hookId, relScriptPath, profilesCsv || 'minimal,standard,strict', { + raw, + truncated, + hookContext + }); + stdout = typeof result.stdout === 'string' && result.stdout !== raw ? result.stdout : ''; + exitCode = Number.isInteger(result.exitCode) ? result.exitCode : 0; + } catch (error) { + stderr = `[Hook] lifecycle runner failed for ${hookId}: ${error && error.message ? error.message : error}\n`; exitCode = 1; } + // The hook has finished: an overdue deadline timer must not add a "timed out" line. + disarmDeadline(); + + // A hook that blocked the event loop past the deadline gets here before the timer could fire. + // Its result is still delivered, because the hook may have consumed what it reports: + // plan-canvas-pending empties the feedback queue it turns into its Stop response. Only the + // overrun is noted. + if (Date.now() >= deadline) { + stderr += `[Hook] lifecycle hook ${hookId} finished after its ${timeout} ms deadline\n`; + } + exitAfterFlush(stdout, stderr, exitCode); } diff --git a/scripts/hooks/run-with-flags.js b/scripts/hooks/run-with-flags.js index abbab9e1f83..915da5c9358 100755 --- a/scripts/hooks/run-with-flags.js +++ b/scripts/hooks/run-with-flags.js @@ -200,8 +200,8 @@ function buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw) { /** * Runs one hook and returns { stdout, exitCode } instead of exiting, so - * plugin-hook-bootstrap.js can call it in-process rather than spawning a - * second Node process per hook. + * plugin-hook-bootstrap.js and lifecycle-hook-bootstrap.js can call it + * in-process rather than spawning a second Node process per hook. */ async function runHook(hookId, relScriptPath, profilesCsv, { raw, truncated, hookContext }) { // Oversized payloads: never echo the truncated string — a JSON document diff --git a/tests/hooks/plugin-hook-bootstrap.test.js b/tests/hooks/plugin-hook-bootstrap.test.js index e6f84e1555d..c145fc80131 100644 --- a/tests/hooks/plugin-hook-bootstrap.test.js +++ b/tests/hooks/plugin-hook-bootstrap.test.js @@ -46,6 +46,27 @@ function run(args = [], options = {}) { }); } +// Runs lifecycle-hook-bootstrap.js the way the Stop/SessionEnd entries in hooks.json do: +// . +function runLifecycle(args = [], options = {}) { + return spawnSync(process.execPath, [LIFECYCLE_SCRIPT, ...args], { + input: options.input || '', + encoding: 'utf8', + env: { + ...process.env, + CLAUDE_PLUGIN_ROOT: options.root || '', + ECC_PLUGIN_ROOT: '', + ECC_HOOK_DEADLINE_MS: '', + ECC_HOOK_INPUT_MAX_BYTES: '', + ECC_HOOK_INPUT_TRUNCATED_UPSTREAM: '', + NODE_OPTIONS: '', + ...(options.env || {}), + }, + cwd: options.cwd || process.cwd(), + timeout: 20000, + }); +} + function isolatedBootstrapEnv(root) { return { HOME: root, USERPROFILE: root, ECC_AGENT_DATA_HOME: path.join(root, 'agent-data'), @@ -151,6 +172,195 @@ function runTests() { assert.strictEqual(resolveTimeout('invalid'), 30000); })) passed++; else failed++; + if (test('lifecycle bootstrap runs run-with-flags.js in-process instead of spawning a second node', () => { + const root = createTempDir(); + try { + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = async (hookId, relScriptPath, profilesCsv, input) => ({ + stdout: JSON.stringify({ + pid: process.pid, hookId, relScriptPath, profilesCsv, raw: input.raw, + claudeRoot: process.env.CLAUDE_PLUGIN_ROOT, eccRoot: process.env.ECC_PLUGIN_ROOT, + deadline: Number(process.env.ECC_HOOK_DEADLINE_MS), + }), + exitCode: 2, +}); +`); + const before = Date.now(); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '30000'], { root, input: 'payload' }); + const after = Date.now(); + const parsed = JSON.parse(result.stdout); + + assert.strictEqual(result.status, 2, result.stderr); + assert.strictEqual(parsed.pid, result.pid, 'run-with-flags ran in a child process'); + assert.deepStrictEqual( + [parsed.hookId, parsed.relScriptPath, parsed.profilesCsv, parsed.raw], + ['stop:test', 'scripts/hooks/x.js', 'standard', 'payload'] + ); + assert.strictEqual(path.resolve(parsed.claudeRoot), path.resolve(root)); + assert.strictEqual(path.resolve(parsed.eccRoot), path.resolve(root)); + // The hook still sees the lifecycle deadline (llm-summary and legacy hooks read it). + assert.ok(parsed.deadline >= before + 30000 && parsed.deadline <= after + 30000, `deadline ${parsed.deadline}`); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap sets the input env before loading run-with-flags and forwards truncation', () => { + const root = createTempDir(); + try { + // run-with-flags.js reads ECC_HOOK_INPUT_MAX_BYTES and ECC_HOOK_INPUT_TRUNCATED_UPSTREAM + // when it is loaded, so the stub captures them at module scope too. + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +const loadMax = process.env.ECC_HOOK_INPUT_MAX_BYTES; +const loadTruncated = process.env.ECC_HOOK_INPUT_TRUNCATED_UPSTREAM; +module.exports.runHook = async (hookId, relScriptPath, profilesCsv, input) => ({ + stdout: JSON.stringify({ loadMax, loadTruncated, truncated: input.truncated, + hookEventName: input.hookContext.hookEventName, rawLength: input.raw.length }), + exitCode: 0, +}); +`); + const payload = JSON.stringify({ hook_event_name: 'Stop', padding: 'x'.repeat(400) }); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '30000'], { + root, input: payload, env: { ECC_HOOK_INPUT_MAX_BYTES: '64' }, + }); + const parsed = JSON.parse(result.stdout); + assert.strictEqual(result.status, 0, result.stderr); + assert.deepStrictEqual( + [parsed.loadMax, parsed.loadTruncated, parsed.truncated, parsed.hookEventName], + ['64', '1', true, 'Stop'] + ); + assert.ok(parsed.rawLength <= 64, `raw length ${parsed.rawLength}`); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap still drops stdout that only echoes the hook input', () => { + const root = createTempDir(); + try { + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = async (hookId, relScriptPath, profilesCsv, input) => ({ stdout: input.raw, exitCode: 0 }); +`); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '30000'], { root, input: '{"a":1}' }); + assert.strictEqual(result.status, 0, result.stderr); + assert.strictEqual(result.stdout, ''); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap reports a throwing runner as a failed lifecycle runner', () => { + const root = createTempDir(); + try { + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = async () => { throw new Error('boom'); }; +`); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '30000'], { root, input: 'payload' }); + assert.strictEqual(result.status, 1, result.stderr); + assert.strictEqual(result.stdout, ''); + assert.ok(result.stderr.includes('[Hook] lifecycle runner failed for stop:test: boom'), result.stderr); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap still stops a runner that overruns its timeout', () => { + const root = createTempDir(); + try { + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = () => new Promise(() => { setInterval(() => {}, 1000); }); +`); + const started = Date.now(); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '1000'], { root, input: 'payload' }); + const elapsed = Date.now() - started; + assert.strictEqual(result.status, 1, spawnDiagnostic(result)); + assert.ok(elapsed < 15000, `took ${elapsed} ms`); + assert.ok(result.stderr.includes('[Hook] lifecycle runner failed for stop:test: timed out after 1000 ms'), result.stderr); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap stops a runner whose budget ran out before the watchdog was armed', () => { + const root = createTempDir(); + try { + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = () => new Promise(() => { setInterval(() => {}, 1000); }); +`); + // Every clock read lands 9 s after the last, so the 8 s budget is always spent by the time + // the watchdog is armed, as it is on a slow start. The runner must be stopped at once: + // neither after the 330 s default nor after a fresh 8 s. + const clock = writeFile(root, 'fast-clock.js', ` +const realNow = Date.now; +let skew = 0; +Date.now = () => realNow() + (skew += 9000); +`); + const started = Date.now(); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '8000'], { + root, + input: 'payload', + env: { NODE_OPTIONS: `--require "${clock.replace(/\\/g, '/')}"` } + }); + const elapsed = Date.now() - started; + assert.strictEqual(result.status, 1, spawnDiagnostic(result)); + assert.ok(elapsed < 5000, `took ${elapsed} ms`); + assert.ok(result.stderr.includes('[Hook] lifecycle runner failed for stop:test: timed out after 8000 ms'), result.stderr); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap delivers a late result and notes the overrun', () => { + const root = createTempDir(); + try { + // The deadline timer cannot fire while the runner blocks the event loop, as the shipped + // run() hooks do in their child-process calls, so a late runner gets to return. + writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), ` +module.exports.runHook = async () => { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 600); + return { stdout: 'late', exitCode: 2 }; +}; +`); + const result = runLifecycle(['stop:test', 'scripts/hooks/x.js', 'standard', '200'], { root, input: 'payload' }); + assert.strictEqual(result.status, 2, spawnDiagnostic(result)); + assert.strictEqual(result.stdout, 'late'); + assert.strictEqual(result.stderr, '[Hook] lifecycle hook stop:test finished after its 200 ms deadline\n'); + } finally { + cleanup(root); + } + })) passed++; else failed++; + + if (test('lifecycle bootstrap does not lose feedback that plan-canvas-pending drained after the deadline', () => { + const stateDir = createTempDir(); + const projectDir = createTempDir(); + try { + const key = 'abcdef012345'; + const sessionsFile = writeFile(stateDir, 'sessions.json', JSON.stringify({ + sessions: { + [key]: { + key, file: path.join(projectDir, 'plan.md'), mode: 'plan', status: 'feedback', + updatedAt: '2026-01-01T00:00:00.000Z', pendingFeedback: [{ kind: 'chat', text: 'late feedback' }], + }, + }, + })); + // A 1 ms budget is spent before the real hook runs, so its drain ends after the deadline. + const result = runLifecycle( + ['stop:plan-canvas-pending', 'scripts/hooks/plan-canvas-pending.js', 'minimal,standard,strict', '1'], + { + root: path.join(__dirname, '..', '..'), + input: JSON.stringify({ hook_event_name: 'Stop', cwd: projectDir }), + env: { ECC_PLAN_CANVAS_STATE_DIR: stateDir, ECC_HOOK_PROFILE: 'standard', ECC_DISABLED_HOOKS: '' }, + } + ); + const queued = JSON.parse(fs.readFileSync(sessionsFile, 'utf8')).sessions[key].pendingFeedback.length > 0; + const delivered = result.stdout.includes('late feedback'); + assert.ok(queued || delivered, `feedback neither queued nor delivered: ${spawnDiagnostic(result)}`); + } finally { + cleanup(stateDir); + cleanup(projectDir); + } + })) passed++; else failed++; + if (test('node mode runs target script with plugin root environment', () => { const root = createTempDir(); try {