Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 45 additions & 36 deletions scripts/hooks/lifecycle-hook-bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -82,45 +81,55 @@ 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 deadline = Date.now() + 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).
const disarmDeadline = installHookWatchdog({
label: `lifecycle hook ${hookId}`,
env: { ECC_HOOK_DEADLINE_MS: String(deadline) },
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

exitAfterFlush(stdout, stderr, exitCode);
}

Expand Down
4 changes: 2 additions & 2 deletions scripts/hooks/run-with-flags.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
130 changes: 130 additions & 0 deletions tests/hooks/plugin-hook-bootstrap.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,27 @@ function run(args = [], options = {}) {
});
}

// Runs lifecycle-hook-bootstrap.js the way the Stop/SessionEnd entries in hooks.json do:
// <hookId> <relScriptPath> <profilesCsv> <timeoutMs>.
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'),
Expand Down Expand Up @@ -151,6 +172,115 @@ 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('node mode runs target script with plugin root environment', () => {
const root = createTempDir();
try {
Expand Down