Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

Merge main into feat/hookify-enforcement-runtime

wellkilo92f53c4c8908
diff --cc hooks/README.md
index 44a1fba1c,548658774..8b0b645be
--- a/hooks/README.md
+++ b/hooks/README.md
@@@ -150,29 -157,12 +162,32 @@@ The Claude plugin exposes the same choi
`hook_profile` settings. Run `ecc setup --mode claude-plugin` to install or
update the plugin and change those preferences.
+### Hookify Rule Runtime
+
+ECC loads enabled `.claude/hookify.*.local.md` files directly; no separate
+Hookify plugin or Python runtime is required. Rules support `bash`, `file`,
+`prompt`, `stop`, and `all` events, plus either a simple regex `pattern` or an
+AND-combined `conditions` list. `warn` adds visible context for Claude while
+allowing the action. `block` denies a matching `PreToolUse` call and uses the
+event's blocking decision contract for prompt, post-tool, and stop events.
+
+Rule loading is project-scoped and bounded. Symlinked, oversized, malformed,
+or unsafe-regex rule files are skipped with a diagnostic instead of breaking
+the entire hook chain. Every regex evaluation also has a 25 ms hard timeout.
+Stop rules ignore `stop_hook_active: true` to avoid continuation loops.
+
+Files tracked by Git are disabled by default because opening a repository must
+not activate repository-authored instructions. Locally created, gitignored
+rules continue to work automatically. To review and explicitly trust tracked
+rules, set `ECC_HOOKIFY_ALLOW_TRACKED=1`; messages are still labeled as
+untrusted local rule data when passed to Claude.
+
### Writing Your Own Hook
- Hooks are shell commands that receive tool input as JSON on stdin and must output JSON on stdout.
+ Hooks are shell commands that receive tool input as JSON on stdin. A hook with
+ no decision or context to return should leave stdout empty. Only explicit hook
+ output, such as a deny decision or `additionalContext`, should be written to
+ stdout; the input payload must not be echoed as a no-op response.
**Basic structure:**
diff --cc hooks/hooks.json
index 131e34c20,8ec470673..8b92a2833
--- a/hooks/hooks.json
+++ b/hooks/hooks.json
@@@ -185,16 -164,6 +185,16 @@@
}
],
"Stop": [
+ {
+ "matcher": ".*",
+ "hooks": [
+ {
+ "type": "command",
- "command": "node -e \"const fs=require('fs');const path=require('path');const {spawnSync}=require('child_process');const raw=fs.readFileSync(0,'utf8');const finish=(out,err,code)=>{let pending=1;const done=()=>{pending-=1;if(pending===0)process.exit(code);};if(out){pending+=1;process.stdout.write(out,done);}if(err){pending+=1;process.stderr.write(err,done);}process.nextTick(done);};const rel=path.join('scripts','hooks','run-with-flags.js');const root=(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=p.join(o.homedir(),'.claude');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<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const script=path.join(root,rel);if(fs.existsSync(script)){const result=spawnSync(process.execPath,[script,'stop:hookify-runtime','scripts/hooks/hookify-runtime.js','minimal,standard,strict'],{input:raw,encoding:'utf8',env:process.env,cwd:process.cwd(),timeout:30000,maxBuffer:16*1024*1024});const failed=result.error||result.status===null||result.signal;const stdout=!failed&&typeof result.stdout==='string'?result.stdout:'';let stderr=typeof result.stderr==='string'?result.stderr:'';let code=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+='[Stop] ERROR: hook runner failed: '+reason+String.fromCharCode(10);code=1;}finish(stdout,stderr,code);}else{finish(raw,'[Stop] WARNING: could not resolve ECC plugin root; skipping hook'+String.fromCharCode(10),0);}\"",
++ "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=p.join(o.homedir(),'.claude');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<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const n=process.platform==='win32'&&r.charAt(0)==='/'&&/[a-zA-Z]/.test(r.charAt(1))&&(r.length===2||r.charAt(2)==='/')?r.charAt(1).toUpperCase()+':/'+r.slice(3):r;const s=p.join(n,'scripts/hooks/lifecycle-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=n;if(require('fs').existsSync(s)){process.argv.splice(1,0,s);require(s).cli()}else{process.stderr.write('[Hook] lifecycle bootstrap unavailable; skipping hook'+String.fromCharCode(10))}\" stop:hookify-runtime scripts/hooks/hookify-runtime.js minimal,standard,strict 10000",
+ "timeout": 10
+ }
+ ]
+ },
{
"matcher": ".*",
"hooks": [
diff --cc hooks/hooks.metadata.json
index e15e3c980,1c3a54c8a..974f34400
--- a/hooks/hooks.metadata.json
+++ b/hooks/hooks.metadata.json
@@@ -104,11 -92,6 +104,11 @@@
}
],
"Stop": [
+ {
+ "id": "stop:hookify-runtime",
+ "description": "Evaluate project-local Hookify completion rules before Claude stops",
- "fingerprint": "ebc0f182702e"
++ "fingerprint": "7dd7cbc0df5f"
+ },
{
"id": "stop:plan-canvas-pending",
"description": "Deliver undelivered Plan Canvas browser feedback before the agent stops",
diff --cc scripts/hooks/hook-input.js
index 000000000,648c0e767..682dffc6b
mode 000000,100644..100644
--- a/scripts/hooks/hook-input.js
+++ b/scripts/hooks/hook-input.js
@@@ -1,0 -1,69 +1,70 @@@
+ 'use strict';
+
+ const { StringDecoder } = require('string_decoder');
+
+ const DEFAULT_MAX_STDIN = 1024 * 1024;
+
+ function resolveMaxStdin(value, options = {}) {
+ const writeDiagnostic = options.writeDiagnostic || (() => {});
+ if (value === undefined || value === '') return DEFAULT_MAX_STDIN;
+
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
+ writeDiagnostic(
+ '[Hook] ECC_HOOK_INPUT_MAX_BYTES must be a positive safe integer; using the 1 MiB default\n'
+ );
+ return DEFAULT_MAX_STDIN;
+ }
+ if (parsed > DEFAULT_MAX_STDIN) {
+ writeDiagnostic(
+ '[Hook] ECC_HOOK_INPUT_MAX_BYTES exceeds the 1 MiB safety maximum; clamping to 1 MiB\n'
+ );
+ return DEFAULT_MAX_STDIN;
+ }
+ return parsed;
+ }
+
+ function readStdinRaw(stream = process.stdin, options = {}) {
+ const maxStdin = options.maxStdin || DEFAULT_MAX_STDIN;
+ const decoder = new StringDecoder('utf8');
+ let raw = '';
+ let acceptedBytes = 0;
+ let truncated = options.truncated === true;
+
+ return new Promise(resolve => {
+ let settled = false;
+ stream.on('data', chunk => {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
++ if (typeof options.onChunk === 'function') options.onChunk(buffer);
+ const remaining = Math.max(0, maxStdin - acceptedBytes);
+ const accepted = buffer.subarray(0, remaining);
+ if (accepted.length > 0) {
+ raw += decoder.write(accepted);
+ acceptedBytes += accepted.length;
+ }
+ if (accepted.length < buffer.length) truncated = true;
+ });
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ if (!truncated) raw += decoder.end();
+ resolve({ raw, truncated });
+ };
+ const finishIncomplete = () => {
+ if (settled) return;
+ truncated = true;
+ finish();
+ };
+ stream.once('end', finish);
+ // A transport error or premature close can leave a syntactically plausible
+ // prefix behind. Mark it incomplete so safety hooks remain fail closed.
+ stream.once('error', finishIncomplete);
+ stream.once('close', finishIncomplete);
+ });
+ }
+
+ module.exports = {
+ DEFAULT_MAX_STDIN,
+ readStdinRaw,
+ resolveMaxStdin
+ };
diff --cc scripts/hooks/lifecycle-hook-bootstrap.js
index 000000000,66280147f..d0fab3c0a
mode 000000,100644..100644
--- a/scripts/hooks/lifecycle-hook-bootstrap.js
+++ b/scripts/hooks/lifecycle-hook-bootstrap.js
@@@ -1,0 -1,120 +1,133 @@@
+ #!/usr/bin/env node
+ 'use strict';
+
+ 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 { createHookContextScanner } = require('./hook-input-limits');
+
+ const DEFAULT_TIMEOUT_MS = 30000;
+ const MAX_TIMEOUT_MS = 300000;
+
+ function writeStderr(text) {
+ if (typeof text !== 'string' || text.length === 0) return;
+ process.stderr.write(text.endsWith('\n') ? text : `${text}\n`);
+ }
+
+ function resolveTimeout(value) {
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) return DEFAULT_TIMEOUT_MS;
+ return Math.min(parsed, MAX_TIMEOUT_MS);
+ }
+
+ function exitAfterFlush(stdout, stderr, exitCode) {
+ process.exitCode = exitCode;
+ let pendingWrites = 2;
+ const finish = () => {
+ pendingWrites -= 1;
+ if (pendingWrites === 0) process.exit(exitCode);
+ };
+
+ // Empty writes still queue callbacks behind any earlier diagnostics on the
+ // same stream, so both streams are drained before the explicit exit.
+ process.stdout.write(stdout || '', finish);
+ process.stderr.write(stderr || '', finish);
+ }
+
+ async function main() {
+ const [, , hookId, relScriptPath, profilesCsv, timeoutValue] = process.argv;
+ const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES, {
+ writeDiagnostic: message => process.stderr.write(message)
+ });
- const { raw, truncated } = await readStdinRaw(process.stdin, { maxStdin });
++ const contextDecoder = new StringDecoder('utf8');
++ const contextScanner = createHookContextScanner();
++ const { raw, truncated } = await readStdinRaw(process.stdin, {
++ maxStdin,
++ truncated: /^(1|true|yes)$/i.test(
++ String(process.env.ECC_HOOK_INPUT_TRUNCATED_UPSTREAM || '')
++ ),
++ onChunk: buffer => contextScanner.push(contextDecoder.write(buffer))
++ });
++ contextScanner.push(contextDecoder.end());
++ const hookContext = contextScanner.context;
+
+ if (!hookId || !relScriptPath) {
+ writeStderr('[Hook] lifecycle bootstrap missing hook ID or script path; skipping hook');
+ process.exitCode = 0;
+ return;
+ }
+
+ const pluginRoot = normalizePluginRootForPlatform(
+ process.env.CLAUDE_PLUGIN_ROOT || process.env.ECC_PLUGIN_ROOT
+ );
+ if (!pluginRoot) {
+ writeStderr('[Hook] lifecycle bootstrap could not resolve ECC plugin root; skipping hook');
+ process.exitCode = 0;
+ return;
+ }
+ const resolvedRoot = path.resolve(pluginRoot);
+ const runner = path.resolve(resolvedRoot, 'scripts', 'hooks', 'run-with-flags.js');
+ if (!runner.startsWith(resolvedRoot + path.sep) || !fs.existsSync(runner)) {
+ writeStderr('[Hook] lifecycle bootstrap could not resolve ECC plugin root; skipping hook');
+ process.exitCode = 0;
+ return;
+ }
+
+ if (truncated) {
+ writeStderr(`[Hook] lifecycle stdin exceeded ${maxStdin} bytes; forwarded a bounded prefix`);
+ }
+
+ 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_INPUT_TRUNCATED_UPSTREAM: truncated ? '1' : '0',
++ ECC_HOOK_CONTEXT_JSON: JSON.stringify(hookContext)
+ },
+ cwd: process.cwd(),
+ timeout: resolveTimeout(timeoutValue),
+ 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`;
+ exitCode = 1;
+ }
+
+ exitAfterFlush(stdout, stderr, exitCode);
+ }
+
+ function cli() {
+ main().catch(error => {
+ writeStderr(`[Hook] lifecycle bootstrap failed: ${error.message}`);
+ process.exitCode = 0;
+ });
+ }
+
+ if (require.main === module) cli();
+
+ module.exports = { cli, exitAfterFlush, main, resolveTimeout };
diff --cc scripts/hooks/posttooluse-dispatcher.js
index dc902812a,58fbec53e..e81d1fb37
--- a/scripts/hooks/posttooluse-dispatcher.js
+++ b/scripts/hooks/posttooluse-dispatcher.js
@@@ -7,8 -7,8 +7,9 @@@
'use strict';
const path = require('path');
+const { StringDecoder } = require('string_decoder');
const { isHookEnabled } = require('../lib/hook-flags');
+ const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input');
const { runPostBash } = require('./bash-hook-dispatcher');
const { run: runQualityGate } = require('./quality-gate');
const { run: runDesignQualityCheck } = require('./design-quality-check');
@@@ -20,25 -20,15 +21,27 @@@ const { run: runObserve } = require('./
const { run: runMetricsBridge } = require('./ecc-metrics-bridge');
const { run: runContextMonitor } = require('./ecc-context-monitor');
const { run: runSkillRunTracker } = require('./skill-run-tracker');
+const { run: runHookify } = require('./hookify-runtime');
- const {
- REGISTERED_HOOK_MAX_STDIN_BYTES,
- createHookContextScanner,
- } = require('./hook-input-limits');
++const { createHookContextScanner } = require('./hook-input-limits');
- const MAX_STDIN = REGISTERED_HOOK_MAX_STDIN_BYTES;
+ const MAX_STDIN = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES, {
+ writeDiagnostic: message => process.stderr.write(message)
+ });
+ const UPSTREAM_TRUNCATED = /^(1|true|yes)$/i.test(
+ String(process.env.ECC_HOOK_INPUT_TRUNCATED_UPSTREAM || '')
+ );
const SYNC_HOOKS = [
+ {
+ id: 'post:hookify-runtime',
+ matcher: '*',
+ profiles: 'minimal,standard,strict',
+ script: 'scripts/hooks/hookify-runtime.js',
+ run(raw, options) {
+ const result = runHookify(raw, options);
+ return result.stdout === raw ? { ...result, stdout: '' } : result;
+ }
+ },
{ id: 'post:edit:design-quality-check', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/design-quality-check.js', run: runDesignQualityCheck },
{ id: 'post:edit:accumulator', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-accumulator.js', run: runPostEditAccumulator },
{ id: 'post:edit:console-warn', matcher: 'Edit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-console-warn.js', run: runConsoleWarn },
@@@ -279,46 -215,19 +282,25 @@@ function runHooks(raw, hooks, options
}
function readStdinRaw() {
- return new Promise(resolve => {
- const decoder = new StringDecoder('utf8');
- const contextDecoder = new StringDecoder('utf8');
- let raw = '';
- let bytesRead = 0;
- let truncated = false;
- let settled = false;
- const contextScanner = createHookContextScanner();
- process.stdin.on('data', chunk => {
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
- contextScanner.push(contextDecoder.write(buffer));
- const remaining = Math.max(0, MAX_STDIN - bytesRead);
- const accepted = buffer.subarray(0, remaining);
- if (accepted.length > 0) {
- raw += decoder.write(accepted);
- bytesRead += accepted.length;
- }
- if (buffer.length > accepted.length) truncated = true;
- });
- const finish = () => {
- if (settled) return;
- settled = true;
- contextScanner.push(contextDecoder.end());
- if (!truncated) raw += decoder.end();
- resolve({ raw, truncated, hookContext: contextScanner.context });
- };
- process.stdin.once('end', finish);
- process.stdin.once('error', finish);
++ const contextDecoder = new StringDecoder('utf8');
++ const contextScanner = createHookContextScanner();
+ return readBoundedStdin(process.stdin, {
+ maxStdin: MAX_STDIN,
- truncated: UPSTREAM_TRUNCATED
++ truncated: UPSTREAM_TRUNCATED,
++ onChunk: buffer => contextScanner.push(contextDecoder.write(buffer))
++ }).then(result => {
++ contextScanner.push(contextDecoder.end());
++ return { ...result, hookContext: contextScanner.context };
});
}
- function resolveMainStdout(raw, result, options = {}) {
- if (result.stdout) return result.stdout;
- if (options.truncated || result.exitCode !== 0 || !options.passthrough) return '';
- return raw;
+ function resolveMainStdout(_raw, result, _options = {}) {
+ return result.stdout || '';
}
- async function main() {
+ async function main(options = {}) {
const mode = process.argv[2] === 'async' ? 'async' : 'sync';
- const { raw, truncated } = await readStdinRaw();
+ const { raw, truncated, hookContext } = await readStdinRaw();
const dispatcherId = `post:dispatcher:${mode}`;
const dispatcherEnabled = isEnabled(
{
@@@ -327,11 -236,9 +309,12 @@@
},
process.env
);
- const hooks = dispatcherEnabled ? (mode === 'async' ? ASYNC_HOOKS : SYNC_HOOKS) : [];
+ const configuredHooks = options.hookListOverride || (mode === 'async' ? ASYNC_HOOKS : SYNC_HOOKS);
+ const hooks = dispatcherEnabled ? configuredHooks : [];
- const result = runHooks(raw, hooks, { truncated });
+ const result = runHooks(raw, hooks, {
+ truncated,
- ...(truncated ? { toolName: hookContext.toolName } : {}),
++ ...(truncated && hookContext.toolName ? { toolName: hookContext.toolName } : {}),
+ });
if (truncated) {
process.stderr.write(`[Hook] stdin exceeded ${MAX_STDIN} bytes for PostToolUse ${mode}; suppressing pass-through\n`);
}
diff --cc scripts/hooks/run-with-flags.js
index 3ca1bdaab,c24505adc..d16311c14
--- a/scripts/hooks/run-with-flags.js
+++ b/scripts/hooks/run-with-flags.js
@@@ -11,42 -11,26 +11,52 @@@
const fs = require('fs');
const path = require('path');
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 { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output');
- const {
- REGISTERED_HOOK_MAX_STDIN_BYTES,
- createHookContextScanner,
- } = require('./hook-input-limits');
++const { createHookContextScanner } = require('./hook-input-limits');
- const MAX_STDIN = REGISTERED_HOOK_MAX_STDIN_BYTES;
+ const FAIL_CLOSED_ON_TRUNCATION_HOOKS = new Set([
+ 'pre:powershell:gateguard-fact-force',
+ 'pre:edit-write:gateguard-fact-force',
+ 'pre:mcp-health-check'
+ ]);
+
+ const MAX_STDIN = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES, {
+ writeDiagnostic: message => process.stderr.write(message)
+ });
++const UPSTREAM_TRUNCATED = /^(1|true|yes)$/i.test(
++ String(process.env.ECC_HOOK_INPUT_TRUNCATED_UPSTREAM || '')
++);
++
++function readUpstreamHookContext() {
++ if (!UPSTREAM_TRUNCATED) return {};
++ try {
++ const parsed = JSON.parse(String(process.env.ECC_HOOK_CONTEXT_JSON || '{}'));
++ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
++ } catch {
++ return {};
++ }
++}
function readStdinRaw() {
- return new Promise(resolve => {
- const rawDecoder = new StringDecoder('utf8');
- const contextDecoder = new StringDecoder('utf8');
- let raw = '';
- let bytesRead = 0;
- let truncated = false;
- const contextScanner = createHookContextScanner();
- process.stdin.on('data', chunk => {
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
- contextScanner.push(contextDecoder.write(buffer));
- const remaining = Math.max(0, MAX_STDIN - bytesRead);
- const accepted = buffer.subarray(0, remaining);
- if (accepted.length > 0) {
- raw += rawDecoder.write(accepted);
- bytesRead += accepted.length;
- }
- if (accepted.length < buffer.length) truncated = true;
- });
- const finish = () => {
- contextScanner.push(contextDecoder.end());
- if (!truncated) raw += rawDecoder.end();
- resolve({ raw, truncated, hookContext: contextScanner.context });
++ const contextDecoder = new StringDecoder('utf8');
++ const contextScanner = createHookContextScanner();
++ const upstreamHookContext = readUpstreamHookContext();
+ return readBoundedStdin(process.stdin, {
+ maxStdin: MAX_STDIN,
- truncated: /^(1|true|yes)$/i.test(
- String(process.env.ECC_HOOK_INPUT_TRUNCATED_UPSTREAM || '')
- )
++ truncated: UPSTREAM_TRUNCATED,
++ onChunk: buffer => contextScanner.push(contextDecoder.write(buffer))
++ }).then(result => {
++ contextScanner.push(contextDecoder.end());
++ const scannedHookContext = contextScanner.context;
++ return {
++ ...result,
++ hookContext: UPSTREAM_TRUNCATED
++ ? { ...scannedHookContext, ...upstreamHookContext }
++ : scannedHookContext
+ };
- process.stdin.on('end', finish);
- process.stdin.on('error', finish);
});
}
@@@ -242,10 -249,9 +275,10 @@@ async function main()
pluginRoot,
scriptPath,
truncated,
- maxStdin: MAX_STDIN
+ maxStdin: MAX_STDIN,
+ ...(truncated ? hookContext : {})
});
- const result = resolveHookResult(raw, output);
+ const result = resolveHookResult(output);
exitWithStdout(sanitizeEcho(result.stdout), result.exitCode);
} catch (runErr) {
process.stderr.write(`[Hook] run() error for ${hookId}: ${runErr.message}\n`);
diff --cc tests/hooks/stop-hooks-stdout.test.js
index a7f1b1f1d,32337754f..e834eb222
--- a/tests/hooks/stop-hooks-stdout.test.js
+++ b/tests/hooks/stop-hooks-stdout.test.js
@@@ -232,29 -321,24 +321,24 @@@ if
passed++;
else failed++;
-// spawnSync limits captured output by bytes while the runner's stdin cap is
-// counted after UTF-8 decoding. A payload can therefore be below MAX_STDIN in
-// characters but above Node's default 1MB child-process buffer in bytes.
+// A payload can be below MAX_STDIN in characters but above the byte limit.
+// The runner must count UTF-8 bytes and suppress a truncated JSON document.
const multibytePayload = stopPayload(400 * 1024, '한');
assert.ok(multibytePayload.length < MAX_STDIN, 'fixture must stay below the runner character cap');
-assert.ok(Buffer.byteLength(multibytePayload) > MAX_STDIN, 'fixture must exceed the default byte buffer');
+assert.ok(Buffer.byteLength(multibytePayload) > MAX_STDIN, 'fixture must exceed the runner byte cap');
- // Every registered command uses the same generated wrapper, verified above.
- // Exercise the multi-megabyte byte-buffer edge once so the test does not
- // amplify hosted-runner load by serializing the identical payload seven times.
- if (
- test('registered Stop wrapper counts multibyte input by UTF-8 bytes', () => {
- const result = runRegisteredStopHook(representativeStopEntry, multibytePayload);
- assert.strictEqual(
- result.status,
- 0,
- `expected exit 0, got ${result.status}: ${result.stderr}`
- );
- assert.strictEqual(result.stdout, '', 'byte-oversized JSON must not be echoed');
- assert.match(result.stderr, /stdin exceeded 1048576 bytes/);
- })
- )
- passed++;
- else failed++;
+ for (const entry of hooksConfig.hooks.Stop) {
+ if (
+ test(`${entry.id} disabled registered wrapper stays silent for a multibyte payload`, () => {
+ const result = runRegisteredStopHook(entry, multibytePayload);
+ assert.strictEqual(result.status, 0, `${entry.id}: expected exit 0, got ${result.status}: ${result.stderr}`);
+ assert.strictEqual(result.stdout, '', `${entry.id}: disabled wrapper must stay silent`);
++ assert.match(result.stderr, /lifecycle stdin exceeded 1048576 bytes/);
+ })
+ )
+ passed++;
+ else failed++;
+ }
for (const [hookId, script] of STOP_HOOKS) {
if (
diff --cc tests/pi/pi-extension-adapter.test.js
index c4b018053,6d214de7f..b02e93b9b
--- a/tests/pi/pi-extension-adapter.test.js
+++ b/tests/pi/pi-extension-adapter.test.js
@@@ -100,12 -100,7 +100,13 @@@ function buildEccSkeleton(repoRoot)
const hooksDir = path.join(root, "scripts", "hooks")
fs.mkdirSync(hooksDir, { recursive: true })
- for (const name of ["hook-input.js", "run-with-flags.js", "session-end-marker.js", "pretooluse-visible-output.js"]) {
+ for (const name of [
- "run-with-flags.js",
++ "hook-input.js",
+ "hook-input-limits.js",
++ "run-with-flags.js",
+ "session-end-marker.js",
+ "pretooluse-visible-output.js",
+ ]) {
fs.cpSync(path.join(repoRoot, "scripts", "hooks", name), path.join(hooksDir, name))
}
fs.cpSync(path.join(repoRoot, "scripts", "lib"), path.join(root, "scripts", "lib"), { recursive: true })