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(init): Windows hooks launch through node -e, not cmd /c (#4045)

ra606b3cfeba5
diff --git a/scripts/audit-fix-invariants.mjs b/scripts/audit-fix-invariants.mjs
index f49399914d..8cd0ab3314 100755
--- a/scripts/audit-fix-invariants.mjs
+++ b/scripts/audit-fix-invariants.mjs
@@ -78,8 +78,8 @@ const INVARIANTS = [
{
issue: '#1943',
file: 'v3/@claude-flow/cli/src/init/helper-commands.ts',
- substring: 'IF EXIST',
- why: 'Windows `cmd /c IF EXIST … ELSE …` fallback — Win32 equivalent of the sh probe.',
+ substring: 'if(!fs.existsSync(f))f=p.join(',
+ why: 'Windows node -e fallback (#4045: no `cmd /c`) — Win32 equivalent of the sh probe.',
},
// #1945 / #1946 — memory bridge + doctor honor CLAUDE_FLOW_MEMORY_PATH
diff --git a/v3/@claude-flow/cli/__tests__/settings-user-level-helpers.test.ts b/v3/@claude-flow/cli/__tests__/settings-user-level-helpers.test.ts
index deed227414..3cbefe8ca8 100644
--- a/v3/@claude-flow/cli/__tests__/settings-user-level-helpers.test.ts
+++ b/v3/@claude-flow/cli/__tests__/settings-user-level-helpers.test.ts
@@ -50,16 +50,14 @@ describe('generated settings by scope', () => {
describe('helper command forms', () => {
it('user-level Windows commands never reference the project', () => {
- expect(helperHookCommand('.claude/helpers/hook-handler.cjs', 'pre-bash', 'user', true))
- .toBe('cmd /c "node "%USERPROFILE%\\.claude\\helpers\\hook-handler.cjs" pre-bash"');
+ expect(helperHookCommand('.claude/helpers/hook-handler.cjs', 'pre-bash', 'user', true)).not.toMatch(/cmd|CLAUDE_PROJECT_DIR/);
expect(helperStatusLineCommand('user', true)).not.toContain('CLAUDE_PROJECT_DIR');
});
it('project-level commands are unchanged from #1943', () => {
expect(helperHookCommand('.claude/helpers/hook-handler.cjs', 'route', 'project', false))
.toBe(`sh -c 'D="\${CLAUDE_PROJECT_DIR:-.}"; [ -f "$D/.claude/helpers/hook-handler.cjs" ] || D="\${HOME}"; exec node "$D/.claude/helpers/hook-handler.cjs" route'`);
- expect(helperHookCommand('.claude/helpers/hook-handler.cjs', 'route', 'project', true))
- .toBe('cmd /c "IF EXIST "%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs" (node "%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs" route) ELSE (node "%USERPROFILE%\\.claude\\helpers\\hook-handler.cjs" route)"');
+ expect(helperHookCommand('.claude/helpers/hook-handler.cjs', 'route', 'project', true)).toMatch(/^node -e "var a='\.claude\/helpers\/hook-handler\.cjs route'/);
});
it('re-pins every generated project-probe form and leaves other commands alone', () => {
diff --git a/v3/@claude-flow/cli/__tests__/windows-hook-commands-4045.test.ts b/v3/@claude-flow/cli/__tests__/windows-hook-commands-4045.test.ts
new file mode 100644
index 0000000000..f160871514
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/windows-hook-commands-4045.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #4045: on Windows under Git Bash the generated `cmd /c "IF EXIST ..."` hook
+ * started an interactive cmd (MSYS rewrote `/c`), which executed the hook's
+ * stdin JSON and created zero-byte files named after text following a `>`.
+ * Windows hook commands must be a single `node -e` with no `cmd`, no shell
+ * metacharacters and no `%VAR%` expansion, and must still forward stdin/args.
+ */
+import { describe, expect, it, afterEach } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { helperHookCommand, pinToUserHelpers } from '../src/init/helper-commands.js';
+
+const SCRIPT = '.claude/helpers/hook-handler.cjs';
+const roots: string[] = [];
+afterEach(() => { for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }); });
+
+const codeOf = (command: string): string => {
+ const m = /^node -e "(.*)"$/s.exec(command);
+ expect(m, `not a node -e command: ${command}`).not.toBeNull();
+ return m![1];
+};
+const fixture = (tag: string) => {
+ const dir = mkdtempSync(join(tmpdir(), `ruflo-4045-${tag}-`));
+ roots.push(dir);
+ mkdirSync(join(dir, '.claude', 'helpers'), { recursive: true });
+ writeFileSync(join(dir, SCRIPT), `let d='';process.stdin.on('data',c=>d+=c).on('end',()=>process.stdout.write(JSON.stringify({tag:${JSON.stringify(tag)},argv:process.argv.slice(2),stdin:d})));`);
+ return dir;
+};
+const run = (command: string, env: Record<string, string>, input: string) =>
+ spawnSync(process.execPath, ['-e', codeOf(command)], { env: { PATH: process.env.PATH ?? '', ...env }, input, encoding: 'utf8' });
+
+describe('#4045 Windows hook commands', () => {
+ for (const scope of ['project', 'user'] as const) {
+ it(`${scope} scope never goes through cmd and has no shell metacharacters`, () => {
+ const command = helperHookCommand(SCRIPT, 'pre-bash', scope, true);
+ expect(command).not.toMatch(/\bcmd(\.exe)?\b/i);
+ expect(command).not.toMatch(/IF EXIST/i);
+ const code = codeOf(command);
+ expect(code).not.toMatch(/[<>|&%$`"\\]/);
+ });
+ }
+
+ it('project scope runs the project helper with argv and forwards stdin', () => {
+ const project = fixture('project');
+ const home = fixture('home');
+ const out = run(helperHookCommand(SCRIPT, 'post-edit', 'project', true),
+ { CLAUDE_PROJECT_DIR: project, USERPROFILE: home }, '{"tool_input":"a => b > c"}');
+ expect(out.status).toBe(0);
+ expect(JSON.parse(out.stdout)).toEqual({ tag: 'project', argv: ['post-edit'], stdin: '{"tool_input":"a => b > c"}' });
+ expect(existsSync(join(process.cwd(), 'b'))).toBe(false);
+ });
+
+ it('project scope falls back to the user profile helper when the project has none', () => {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-4045-empty-'));
+ roots.push(project);
+ const home = fixture('home');
+ const out = run(helperHookCommand(SCRIPT, 'route', 'project', true), { CLAUDE_PROJECT_DIR: project, USERPROFILE: home }, '{}');
+ expect(JSON.parse(out.stdout).tag).toBe('home');
+ });
+
+ it('user scope ignores the project helper entirely', () => {
+ const project = fixture('project');
+ const home = fixture('home');
+ const out = run(helperHookCommand(SCRIPT, 'route', 'user', true), { CLAUDE_PROJECT_DIR: project, USERPROFILE: home }, '{}');
+ expect(JSON.parse(out.stdout).tag).toBe('home');
+ });
+
+ it('passes through a non-zero exit status of the helper', () => {
+ const project = fixture('project');
+ writeFileSync(join(project, SCRIPT), 'process.exit(2)');
+ expect(run(helperHookCommand(SCRIPT, 'pre-bash', 'project', true), { CLAUDE_PROJECT_DIR: project }, '').status).toBe(2);
+ });
+
+ it('keeps the subcommand next to the helper name so the mods ownership rule still recognises it', () => {
+ const command = helperHookCommand(SCRIPT, 'route', 'project', true);
+ expect(new RegExp('hook-handler\\.c?js\\\\?["\']?\\s+route(?![\\w-])').test(command)).toBe(true);
+ });
+
+ it('re-pins the new project form to the user form (and the old cmd form too)', () => {
+ const project = helperHookCommand(SCRIPT, 'post-edit', 'project', true);
+ expect(pinToUserHelpers(project, true)).toBe(helperHookCommand(SCRIPT, 'post-edit', 'user', true));
+ const old = 'cmd /c "IF EXIST "%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs" (node "%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs" post-edit) ELSE (node "%USERPROFILE%\\.claude\\helpers\\hook-handler.cjs" post-edit)"';
+ expect(pinToUserHelpers(old, true)).toBe(helperHookCommand(SCRIPT, 'post-edit', 'user', true));
+ });
+
+ it('does not re-pin a user-authored node -e command', () => {
+ expect(pinToUserHelpers('node -e "console.log(1)"', true)).toBeNull();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/helper-commands.ts b/v3/@claude-flow/cli/src/init/helper-commands.ts
index 5c5d99f073..e99ae896f0 100644
--- a/v3/@claude-flow/cli/src/init/helper-commands.ts
+++ b/v3/@claude-flow/cli/src/init/helper-commands.ts
@@ -34,20 +34,37 @@ export function helperScopeFor(targetDir: string | undefined): HelperScope {
return canonical(targetDir) === canonical(os.homedir()) ? 'user' : 'project';
}
+/**
+ * Windows hook command (#4045). It must not go through `cmd /c`: under Git Bash
+ * MSYS rewrites `/c` into a path, cmd starts interactively and executes the
+ * hook's stdin JSON, and any `>` in that text creates a file. A single
+ * `node -e` has no shell syntax to misread (no cmd, no `%VAR%`, no `<>|&$` and
+ * no inner double quotes), so cmd, PowerShell and Git Bash pass it through
+ * unchanged. The script and its subcommand stay in one string, because the
+ * ruflo-mods ownership rule matches `hook-handler.cjs <subcommand>`. Project
+ * scope prefers the project's helper and falls back to the user profile's
+ * (#1943); user scope never looks at the project. The helper runs as a child
+ * with inherited stdio so stdin, stdout and the exit status pass through (a
+ * `require` would skip the helper's `require.main === module` entry point).
+ */
+function windowsHookCommand(script: string, subcommand: string, scope: HelperScope): string {
+ // Ternaries, not `||`: the command carries no pipe or ampersand at all.
+ const home = "(e.USERPROFILE?e.USERPROFILE:e.HOME?e.HOME:'.')";
+ const pick = scope === 'user'
+ ? `f=p.join(${home},a[0]);`
+ : "f=p.join(e.CLAUDE_PROJECT_DIR?e.CLAUDE_PROJECT_DIR:'.',a[0]);" +
+ `if(!fs.existsSync(f))f=p.join(${home},a[0]);`;
+ const js = `var a='${[script, subcommand].filter(Boolean).join(' ')}'.split(' '),e=process.env,fs=require('fs'),p=require('path'),f;` + pick +
+ "var r=require('child_process').spawnSync(process.execPath,[f].concat(a.slice(1)),{stdio:'inherit'});" +
+ 'process.exit(r.status===null?1:r.status)';
+ return `node -e "${js}"`;
+}
+
/** Command that runs `node <script> <subcommand>` for a hook. */
export function helperHookCommand(script: string, subcommand: string, scope: HelperScope, windows = IS_WINDOWS): string {
- const winScript = script.replace(/\//g, '\\');
const arg = subcommand ? ` ${subcommand}` : '';
- if (scope === 'user') {
- return windows
- ? `cmd /c "node "%USERPROFILE%\\${winScript}"${arg}"`
- : `sh -c 'exec node "\${HOME}/${script}"${arg}'`;
- }
- if (windows) {
- // cmd.exe equivalent of the sh probe below. `IF EXIST` checks the
- // project-local path; falls back to %USERPROFILE% if missing.
- return `cmd /c "IF EXIST \"%CLAUDE_PROJECT_DIR%\\${winScript}\" (node \"%CLAUDE_PROJECT_DIR%\\${winScript}\"${arg}) ELSE (node \"%USERPROFILE%\\${winScript}\"${arg})"`;
- }
+ if (windows) return windowsHookCommand(script, subcommand, scope);
+ if (scope === 'user') return `sh -c 'exec node "\${HOME}/${script}"${arg}'`;
// POSIX sh: prefer project-local helpers, fall back to $HOME/.claude/.
// eslint-disable-next-line no-template-curly-in-string
const projVar = '${CLAUDE_PROJECT_DIR:-.}';
@@ -108,6 +125,16 @@ const IF_EXIST_PREAMBLE = /"IF EXIST "%CLAUDE_PROJECT_DIR%\\\.claude\\helpers\\[
* commands (other scripts, redirects, chains) are left alone.
*/
export function pinToUserHelpers(command: string, windows = IS_WINDOWS): string | null {
+ // The #4045 Windows form: recognised only when it is exactly what ruflo generates.
+ const generated = /^node -e "var a='\.claude\/helpers\/([\w.-]+)((?: [\w:.=-]+)*)'\.split\(' '\)/.exec(command);
+ if (generated) {
+ if (!RUFLO_HELPERS.includes(generated[1])) return null;
+ const script = `.claude/helpers/${generated[1]}`;
+ const subcommand = generated[2].trim();
+ return command === helperHookCommand(script, subcommand, 'project', true)
+ ? helperHookCommand(script, subcommand, 'user', true)
+ : null;
+ }
const refs = [...command.matchAll(HELPER_REF)];
if (refs.length === 0) return null;
const helper = refs[refs.length - 1][1];