From 8b2f7ebe074fdfc7c5de6ff6334b4410fe6dc7e5 Mon Sep 17 00:00:00 2001 From: Shaurya <19599684+no-hup@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:20:13 +0530 Subject: [PATCH 1/2] perf(hooks): run run-with-flags in-process from plugin bootstrap plugin-hook-bootstrap.js spawned a second node process just to start run-with-flags.js, for every hook. Call its new runHook() export directly instead. Same env, args, stdout passthrough and exit code. Refs #2834 --- scripts/hooks/plugin-hook-bootstrap.js | 23 ++++++++- scripts/hooks/run-with-flags.js | 60 ++++++++++++----------- tests/hooks/plugin-hook-bootstrap.test.js | 27 ++++++++++ 3 files changed, 81 insertions(+), 29 deletions(-) diff --git a/scripts/hooks/plugin-hook-bootstrap.js b/scripts/hooks/plugin-hook-bootstrap.js index 5f05a0aa5..3eb45b424 100644 --- a/scripts/hooks/plugin-hook-bootstrap.js +++ b/scripts/hooks/plugin-hook-bootstrap.js @@ -189,6 +189,24 @@ function spawnNode(rootDir, relPath, raw, args, options = {}) { return withComparisonInput(result, Buffer.from(raw, 'utf8')); } +// Almost every plugin hook targets run-with-flags.js, which only reads stdin +// and dispatches. Call it in-process instead of paying a second Node startup +// (~50-100 ms) on every hook. Same env and inputs the child would have seen. +async function runWithFlagsInProcess(rootDir, target, raw, args, options) { + ensureAgentDataHomeEnv(); + process.env.CLAUDE_PLUGIN_ROOT = rootDir; + process.env.ECC_PLUGIN_ROOT = rootDir; + process.env.ECC_HOOK_INPUT_MAX_BYTES = String(options.maxStdin); + const [hookId, relScriptPath, profilesCsv] = args; + const { runHook } = require(target); + const { stdout, exitCode } = await runHook(hookId, relScriptPath, profilesCsv, { + raw, + truncated: options.truncated, + hookContext: options.hookContext || {}, + }); + return withComparisonInput({ status: exitCode, stdout }, Buffer.from(raw, 'utf8')); +} + // spawnShell is not used by any hook in the shipped hooks.json configuration // (all hooks use 'node' mode). It is provided for third-party plugins that // register shell-backed hooks. Plugins should supply .ps1 scripts on Windows @@ -283,7 +301,10 @@ async function main() { let result; try { - if (mode === 'node') { + if (mode === 'node' && path.basename(relPath) === 'run-with-flags.js') { + const target = resolveTarget(rootDir, relPath); + result = await runWithFlagsInProcess(rootDir, target, raw, args, { maxStdin, truncated, hookContext }); + } else if (mode === 'node') { result = spawnNode(rootDir, relPath, raw, args, { maxStdin, truncated, hookContext }); } else if (mode === 'shell') { result = spawnShell(rootDir, relPath, raw, args, { maxStdin, truncated, hookContext }); diff --git a/scripts/hooks/run-with-flags.js b/scripts/hooks/run-with-flags.js index d96bdff78..1f0b5aa56 100755 --- a/scripts/hooks/run-with-flags.js +++ b/scripts/hooks/run-with-flags.js @@ -193,10 +193,12 @@ function buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw) { return parts.join(' ') + '\n'; } -async function main() { - const [, , hookId, relScriptPath, profilesCsv] = process.argv; - const { raw, truncated, hookContext } = await readStdinRaw(); - +/** + * 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. + */ +async function runHook(hookId, relScriptPath, profilesCsv, { raw, truncated, hookContext }) { // Oversized payloads: never echo the truncated string — a JSON document // cut mid-stream is treated by the harness as a hook failure, blocking the // tool call (#2222). Empty stdout + exit 0 means "no opinion", so @@ -209,20 +211,17 @@ async function main() { } if (!hookId || !relScriptPath) { - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } if (!isHookEnabled(hookId, { profiles: profilesCsv })) { - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } if (isDryRun()) { const preview = buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw); process.stderr.write(preview); - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } const pluginRoot = getPluginRoot(); @@ -232,21 +231,18 @@ async function main() { // Prevent path traversal outside the plugin root if (!scriptPath.startsWith(resolvedRoot + path.sep)) { process.stderr.write(`[Hook] Path traversal rejected for ${hookId}: ${scriptPath}\n`); - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } if (!fs.existsSync(scriptPath)) { process.stderr.write(`[Hook] Script not found for ${hookId}: ${scriptPath}\n`); - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } const truncationBlock = truncated ? truncatedInputResult(hookId, MAX_STDIN) : null; if (truncationBlock) { writeStderr(truncationBlock.stderr); - exitWithStdout(truncationBlock.stdout, truncationBlock.exitCode); - return; + return { stdout: truncationBlock.stdout, exitCode: truncationBlock.exitCode }; } // Prefer direct require() when the hook exports a run(rawInput) function. @@ -294,12 +290,11 @@ async function main() { ...(truncated ? hookContext : {}) }); const result = resolveHookResult(output); - exitWithStdout(sanitizeEcho(result.stdout), result.exitCode); + return { stdout: sanitizeEcho(result.stdout), exitCode: result.exitCode }; } catch (runErr) { process.stderr.write(`[Hook] run() error for ${hookId}: ${runErr.message}\n`); - exitWithStdout('', 0); + return { stdout: '', exitCode: 0 }; } - return; } // Legacy path: spawn a child Node process for hooks without run() export @@ -315,8 +310,7 @@ async function main() { const remaining = deadline - Date.now(); if (remaining <= 0) { writeStderr(`[Hook] lifecycle time budget exhausted for ${hookId}; skipping legacy hook`); - exitWithStdout('', 0); - return; + return { stdout: '', exitCode: 0 }; } const result = spawnSync(process.execPath, [scriptPath], { input: raw, @@ -340,14 +334,24 @@ async function main() { if (result.error || result.signal || result.status === null) { const failureDetail = result.error ? result.error.message : result.signal ? `terminated by signal ${result.signal}` : 'missing exit status'; writeStderr(`[Hook] legacy hook execution failed for ${hookId}: ${failureDetail}`); - exitWithStdout(legacyStdout, 1); - return; + return { stdout: legacyStdout, exitCode: 1 }; } - exitWithStdout(legacyStdout, Number.isInteger(result.status) ? result.status : 0); + return { stdout: legacyStdout, exitCode: Number.isInteger(result.status) ? result.status : 0 }; } -main().catch(err => { - process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`); - process.exit(0); -}); +async function main() { + const [, , hookId, relScriptPath, profilesCsv] = process.argv; + const input = await readStdinRaw(); + const result = await runHook(hookId, relScriptPath, profilesCsv, input); + exitWithStdout(result.stdout, result.exitCode); +} + +if (require.main === module) { + main().catch(err => { + process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`); + process.exit(0); + }); +} + +module.exports = { runHook }; diff --git a/tests/hooks/plugin-hook-bootstrap.test.js b/tests/hooks/plugin-hook-bootstrap.test.js index 3b3153efb..55d1af505 100644 --- a/tests/hooks/plugin-hook-bootstrap.test.js +++ b/tests/hooks/plugin-hook-bootstrap.test.js @@ -169,6 +169,33 @@ process.stdout.write(JSON.stringify({ } })) passed++; else failed++; + if (test('node mode 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 }), + exitCode: 2, +}); +`); + + const result = run( + ['node', path.join('scripts', 'hooks', 'run-with-flags.js'), 'pre:test', 'scripts/hooks/x.js', 'standard'], + { root, input: 'payload' } + ); + const parsed = JSON.parse(result.stdout); + + assert.strictEqual(result.status, 2, result.stderr); + assert.strictEqual(parsed.pid, result.pid); + assert.deepStrictEqual( + [parsed.hookId, parsed.relScriptPath, parsed.profilesCsv, parsed.raw], + ['pre:test', 'scripts/hooks/x.js', 'standard', 'payload'] + ); + } finally { + cleanup(root); + } + })) passed++; else failed++; + if (test('node mode emits empty stdout when child exits cleanly without stdout', () => { const root = createTempDir(); try { From 1902461a0d78e6ffe37318b8f776b3f44a114bc1 Mon Sep 17 00:00:00 2001 From: Shaurya <19599684+no-hup@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:47:08 +0530 Subject: [PATCH 2/2] fix(hooks): bound in-process run-with-flags hooks with a 30s timeout These hooks set no timeout in hooks.json, so with the second Node process gone they lost the bootstrap's 30s spawnSync cap. Put the same bound back in hooks.json, where the harness enforces it. Fingerprints regenerated. --- hooks/hooks.json | 21 ++++++++++++++------- hooks/hooks.metadata.json | 14 +++++++------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/hooks/hooks.json b/hooks/hooks.json index 80c38a360..a7242463e 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -25,7 +25,8 @@ "hooks": [ { "type": "command", - "command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=(process.env.CLAUDE_CONFIG_DIR||'').trim()||p.join(o.homedir(),'.claude');if(d==='~')d=o.homedir();else if(d.charAt(0)==='~'&&(d.charAt(1)==='/'||d.charCodeAt(1)===92))d=p.join(o.homedir(),d.slice(2));try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var b=String.fromCharCode(92),m=d.match(/^([A-Za-z]):/);if(m&&(d.charAt(2)==='/'||d.charAt(2)===b)){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).split(b).join('/')}}}}catch(_){}d=p.resolve(d);function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i