Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(hooks): use blocking exit status for pre-bash denials

Dragan Spiridonovf65928eeaf81
diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs
index bf6ba5f87a..24635591a7 100755
--- a/.claude/helpers/hook-handler.cjs
+++ b/.claude/helpers/hook-handler.cjs
@@ -465,7 +465,8 @@ const handlers = {
for (const d of dangerous) {
if (cmd.includes(d)) {
console.error(`[BLOCKED] Dangerous command detected: ${d}`);
- process.exit(1);
+ // Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.
+ process.exit(2);
}
}
console.log('[OK] Command validated');
@@ -598,8 +599,8 @@ const handlers = {
}
}
-// Hooks must ALWAYS exit 0 β€” Claude Code treats non-zero as "hook error"
-// and skips all subsequent hooks for the event.
+// Non-blocking hooks exit 0; pre-bash denials exit 2 to block PreToolUse.
+// A denial exits immediately, before the normal completion path below.
//
// Only dispatch when run directly (node hook-handler.cjs <cmd>). When
// require()'d by a test, expose the internals instead of reading stdin and
diff --git a/scripts/smoke-pre-bash-hook.mjs b/scripts/smoke-pre-bash-hook.mjs
index f61cc88ccf..ce31e8b964 100644
--- a/scripts/smoke-pre-bash-hook.mjs
+++ b/scripts/smoke-pre-bash-hook.mjs
@@ -13,7 +13,7 @@
* This script pipes real-shaped Claude Code PreToolUse JSON into the
* locally-built handler and asserts:
*
- * - dangerous command β†’ exit 1 + `[BLOCKED] Dangerous command detected:`
+ * - dangerous command β†’ exit 2 + `[BLOCKED] Dangerous command detected:`
* - innocuous command β†’ exit 0 + `[OK] Command validated`
* - empty payload β†’ exit 0 (no crash, no false positive)
* - non-string command field β†’ exit 0 (defensive String() wrap holds)
@@ -22,7 +22,9 @@
* 1. v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs (the published template)
* 2. .claude/helpers/hook-handler.cjs (the dogfood copy)
*
- * Failure of either fails the build.
+ * Exit 2 is the Claude Code PreToolUse blocking contract; exit 1 reports a
+ * non-blocking hook error. Commands below are only JSON data and are NEVER
+ * executed. Failure of either handler fails the build.
*/
import { spawnSync } from 'node:child_process';
@@ -39,7 +41,7 @@ const cases = [
{
name: 'dangerous rm -rf / β†’ BLOCKED',
input: { tool_name: 'Bash', tool_input: { command: 'rm -rf / --no-preserve-root' } },
- expectExit: 1,
+ expectExit: 2,
expectStderrIncludes: '[BLOCKED]',
},
{
@@ -62,27 +64,23 @@ const cases = [
expectExit: 0,
},
{
- // The exact #2017 shape: the handler reads `toolInput` (object) instead
- // of `toolInput.command` (string), so `.toLowerCase()` throws TypeError,
- // global try/catch swallows, exits 0. This case asserts the regression
- // CAN'T return: a dangerous command sent in real Claude Code's snake_case
- // shape must still BLOCK. If a future refactor binds command to a
- // non-string and the safety check no-ops, this case fails loudly.
- name: '#2017 shape: snake_case tool_input.command dangerous β†’ BLOCKED',
- input: { tool_name: 'Bash', tool_input: { command: 'rm -rf / --no-preserve-root' } },
- expectExit: 1,
+ // The legacy camelCase shape must preserve the same blocking contract
+ // as Claude Code's snake_case payload above.
+ name: 'camelCase toolInput.command dangerous β†’ BLOCKED',
+ input: { tool_name: 'Bash', toolInput: { command: 'rm -rf / --no-preserve-root' } },
+ expectExit: 2,
expectStderrIncludes: '[BLOCKED]',
},
{
name: 'fork-bomb signature β†’ BLOCKED',
input: { tool_name: 'Bash', tool_input: { command: ':(){:|:&};:' } },
- expectExit: 1,
+ expectExit: 2,
expectStderrIncludes: '[BLOCKED]',
},
{
name: 'format c: β†’ BLOCKED',
input: { tool_name: 'Bash', tool_input: { command: 'format c: /q /y' } },
- expectExit: 1,
+ expectExit: 2,
expectStderrIncludes: '[BLOCKED]',
},
];
@@ -116,7 +114,7 @@ function runOne(handlerPath, c) {
// Also catch the "[OK] Command validated" + dangerous input + exit 0 shape
// directly β€” the form the published 3.6.30 actually printed before the
// global-catch warning was added.
- if (c.expectExit === 1 && /\[OK\] Command validated/.test(out) && r.status === 0) {
+ if (c.expectExit === 2 && /\[OK\] Command validated/.test(out) && r.status === 0) {
fails.push('dangerous command produced [OK] + exit 0 (regression of #2017)');
}
return { fails, out, err, status: r.status };
@@ -125,7 +123,8 @@ function runOne(handlerPath, c) {
let failed = 0;
for (const handlerPath of HANDLERS) {
if (!existsSync(handlerPath)) {
- console.error(`[skip] handler not found: ${handlerPath}`);
+ failed++;
+ console.error(`[fail] handler not found: ${handlerPath}`);
continue;
}
console.log(`\n# ${handlerPath}`);
@@ -144,7 +143,7 @@ for (const handlerPath of HANDLERS) {
}
if (failed > 0) {
- console.error(`\n${failed} pre-bash smoke case(s) failed β€” regression of #2017`);
+ console.error(`\n${failed} pre-bash smoke case(s) failed β€” blocking contract violated`);
process.exit(1);
}
console.log('\nok: pre-bash hook gates dangerous commands across both handler copies');
diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
index bf6ba5f87a..24635591a7 100755
--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
@@ -465,7 +465,8 @@ const handlers = {
for (const d of dangerous) {
if (cmd.includes(d)) {
console.error(`[BLOCKED] Dangerous command detected: ${d}`);
- process.exit(1);
+ // Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.
+ process.exit(2);
}
}
console.log('[OK] Command validated');
@@ -598,8 +599,8 @@ const handlers = {
}
}
-// Hooks must ALWAYS exit 0 β€” Claude Code treats non-zero as "hook error"
-// and skips all subsequent hooks for the event.
+// Non-blocking hooks exit 0; pre-bash denials exit 2 to block PreToolUse.
+// A denial exits immediately, before the normal completion path below.
//
// Only dispatch when run directly (node hook-handler.cjs <cmd>). When
// require()'d by a test, expose the internals instead of reading stdin and
diff --git a/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts b/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts
index 1976ab6af9..ad7a0b52bb 100644
--- a/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts
+++ b/v3/@claude-flow/cli/__tests__/hook-handler-artifact-parity.test.ts
@@ -16,7 +16,9 @@
*/
import { describe, it, expect } from 'vitest';
-import { readFileSync, existsSync } from 'fs';
+import { readFileSync, existsSync, mkdtempSync, writeFileSync, rmSync } from 'fs';
+import { spawnSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
import path from 'path';
import { fileURLToPath } from 'url';
import { generateHookHandler } from '../src/init/helpers-generator.js';
@@ -86,3 +88,40 @@ describe('generateHookHandler() fallback β€” funnel refresh wiring (#2661-adjace
expect(() => new Function(withoutShebang)).not.toThrow();
});
});
+
+describe('generateHookHandler() fallback β€” PreToolUse blocking contract', () => {
+ // Only the hook is executed. Dangerous commands are inert stdin JSON data.
+ const cases = [
+ ['snake_case destructive command', { tool_input: { command: 'rm -rf / --no-preserve-root' } }, 2],
+ ['camelCase destructive command', { toolInput: { command: 'format c: /q /y' } }, 2],
+ ['top-level destructive command', { command: ':(){:|:&};:' }, 2],
+ ['tool command takes precedence over prompt', { prompt: 'safe description', tool_input: { command: 'rm -rf /' } }, 2],
+ ['safe command', { tool_input: { command: 'ls -la' } }, 0],
+ ['empty payload', {}, 0],
+ ['null command', { tool_input: { command: null } }, 0],
+ ['object command', { tool_input: { command: {} } }, 0],
+ ] as const;
+
+ it.each(cases)('%s', (_name, input, status) => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'ruflo-pre-bash-'));
+ try {
+ const helper = path.join(dir, 'hook-handler.cjs');
+ writeFileSync(helper, generateHookHandler());
+ const result = spawnSync(process.execPath, [helper, 'pre-bash'], {
+ input: JSON.stringify(input), encoding: 'utf8', cwd: dir, timeout: 10_000,
+ env: { ...process.env, RUFLO_MODS_OWNS: 'route,post-edit,pre-bash' },
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.status).toBe(status);
+ if (status === 2) {
+ expect(result.stderr).toContain('[BLOCKED]');
+ expect(result.stdout).not.toContain('[OK]');
+ } else {
+ expect(result.stdout).toContain('[OK] Command validated');
+ expect(result.stderr).not.toContain('[BLOCKED]');
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
index 2873769a14..ff28c29203 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
@@ -197,7 +197,7 @@ describe('ADR-404 no double fire with the real classic hooks', () => {
it('pre-bash is a guard: it blocks even when the handshake names it', () => {
const r = classic('pre-bash', { tool_input: { command: 'rm -rf /' } }, { RUFLO_MODS_OWNS: 'route,post-edit,pre-bash' });
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain('[BLOCKED]');
});
@@ -208,7 +208,7 @@ describe('ADR-404 no double fire with the real classic hooks', () => {
expect(readFileSync(helper, 'utf8')).toContain('RUFLO_MODS_OWNS');
expect(classic('route', { prompt: 'implement the api' }, { RUFLO_MODS_OWNS: 'route' }).stdout.trim()).toBe('');
expect(classic('route', { prompt: 'implement the api' }, {}).stdout).toContain('Primary Recommendation');
- expect(classic('pre-bash', { tool_input: { command: 'rm -rf /' } }, { RUFLO_MODS_OWNS: 'pre-bash' }).status).toBe(1);
+ expect(classic('pre-bash', { tool_input: { command: 'rm -rf /' } }, { RUFLO_MODS_OWNS: 'pre-bash' }).status).toBe(2);
});
it('hook-handler exports the ownership check it applies', () => {
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index 28aa5f2d41..97c62b7ff7 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -643,12 +643,13 @@ export function generateHookHandler(): string {
' },',
'',
" 'pre-bash': () => {",
- ' var cmd = prompt.toLowerCase();',
+ " var cmd = String(hookInput.command || toolInputObj.command || prompt || '').toLowerCase();",
" var dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\\\', ':(){:|:&};:'];",
' for (var i = 0; i < dangerous.length; i++) {',
' if (cmd.includes(dangerous[i])) {',
" console.error('[BLOCKED] Dangerous command detected: ' + dangerous[i]);",
- ' process.exit(1);',
+ ' // Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.',
+ ' process.exit(2);',
' }',
' }',
" console.log('[OK] Command validated');",
@@ -772,6 +773,7 @@ export function generateHookHandler(): string {
'}',
'} // end main',
'',
+ '// Non-blocking hooks exit 0; pre-bash denials exit 2 before normal completion.',
'process.exitCode = 0;',
'main().catch(() => {}).finally(() => { process.exit(0); });',
];