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): pin user-level hook and statusline commands to $HOME helpers

Dragan Spiridonovd1d9df089139
diff --git a/scripts/audit-fix-invariants.mjs b/scripts/audit-fix-invariants.mjs
index a360559816..f49399914d 100755
--- a/scripts/audit-fix-invariants.mjs
+++ b/scripts/audit-fix-invariants.mjs
@@ -67,16 +67,17 @@ const INVARIANTS = [
why: 'Per-namespace vector_indexes provisioning in storeEntry (sql.js fallback) β€” same root cause as the bridge path; one needs both branches.',
},
- // #1943 β€” settings-generator project-local OR $HOME probe
+ // #1943 β€” project-level settings: project-local OR $HOME probe (user-level
+ // settings are pinned to $HOME instead; see helper-commands.ts)
{
issue: '#1943',
- file: 'v3/@claude-flow/cli/src/init/settings-generator.ts',
+ file: 'v3/@claude-flow/cli/src/init/helper-commands.ts',
substring: '[ -f "$D/',
- why: 'POSIX sh probe in hookCmd() β€” without it, global-install hook paths anchor at `${CLAUDE_PROJECT_DIR}` only and every Bash/Edit/Session hook fires MODULE_NOT_FOUND.',
+ why: 'POSIX sh probe in helperHookCommand() β€” without it, global-install hook paths anchor at `${CLAUDE_PROJECT_DIR}` only and every Bash/Edit/Session hook fires MODULE_NOT_FOUND.',
},
{
issue: '#1943',
- file: 'v3/@claude-flow/cli/src/init/settings-generator.ts',
+ 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.',
},
@@ -193,7 +194,7 @@ const INVARIANTS = [
// #1948 β€” Windows-specific statusLine command (no `sh` required)
{
issue: '#1948',
- file: 'v3/@claude-flow/cli/src/init/settings-generator.ts',
+ file: 'v3/@claude-flow/cli/src/init/helper-commands.ts',
regex: /process\.platform === ['"]win32['"]/,
why: 'Platform-aware statusLine emission. On native Windows we emit `node -e "…"` instead of `sh -c …` so missing/mangled-quoting `sh` no longer produces stray repo-root files.',
},
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
new file mode 100644
index 0000000000..813757545e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/settings-user-level-helpers.test.ts
@@ -0,0 +1,127 @@
+/**
+ * User-level settings (~/.claude/settings.json) apply to every opened project,
+ * so their hook and statusline commands must run the user's own
+ * $HOME/.claude/helpers, never a helper the project supplies. Project-level
+ * settings keep the #1943 project-first probe.
+ */
+import { afterEach, describe, expect, it } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { DEFAULT_INIT_OPTIONS } from '../src/init/types.js';
+import { generateSettings } from '../src/init/settings-generator.js';
+import { mergeSettingsForUpgrade } from '../src/init/executor.js';
+import { helperHookCommand, helperStatusLineCommand, pinToUserHelpers } from '../src/init/helper-commands.js';
+
+const tempRoots: string[] = [];
+afterEach(() => {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+type Settings = { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>>; statusLine: { command: string } };
+
+function commandsOf(settings: Settings): string[] {
+ const hooks = Object.values(settings.hooks).flatMap((groups) => groups.flatMap((g) => g.hooks.map((h) => h.command)));
+ return [...hooks, settings.statusLine.command];
+}
+
+const settingsFor = (targetDir: string) =>
+ generateSettings({ ...DEFAULT_INIT_OPTIONS, targetDir, statusline: { ...DEFAULT_INIT_OPTIONS.statusline, enabled: true } }) as Settings;
+
+describe('generated settings by scope', () => {
+ it('pins every helper command to $HOME when the target is the home directory', () => {
+ const commands = commandsOf(settingsFor(homedir()));
+ expect(commands.length).toBeGreaterThan(5);
+ for (const command of commands) {
+ expect(command).not.toContain('CLAUDE_PROJECT_DIR');
+ expect(command).toMatch(/\$\{HOME\}\/\.claude\/helpers\/|%USERPROFILE%|process\.env\.USERPROFILE/);
+ }
+ });
+
+ it('keeps the #1943 project-first probe for a project target', () => {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-settings-project-'));
+ tempRoots.push(project);
+ const commands = commandsOf(settingsFor(project));
+ for (const command of commands) expect(command).toContain('CLAUDE_PROJECT_DIR');
+ });
+});
+
+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(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)"');
+ });
+
+ it('re-pins every generated project-probe form and leaves other commands alone', () => {
+ for (const windows of [false, true]) {
+ const probe = helperHookCommand('.claude/helpers/hook-handler.cjs', 'post-edit', 'project', windows);
+ expect(pinToUserHelpers(probe, windows)).toBe(helperHookCommand('.claude/helpers/hook-handler.cjs', 'post-edit', 'user', windows));
+ expect(pinToUserHelpers(helperStatusLineCommand('project', windows), windows)).toBe(helperStatusLineCommand('user', windows));
+ }
+ expect(pinToUserHelpers('node my-own-hook.js', false)).toBeNull();
+ });
+});
+
+describe('ruflo init --upgrade --settings', () => {
+ const gitRootImport = `node -e "var c=require('child_process'),p=require('path'),u=require('url'),r;try{r=c.execSync('git rev-parse --show-toplevel',{encoding:'utf8'}).trim()}catch(e){r=process.cwd()}var f=p.join(r,'.claude/helpers/auto-memory-hook.mjs');import(u.pathToFileURL(f).href)" import`;
+ const existing = () => ({
+ hooks: {
+ PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: helperHookCommand('.claude/helpers/hook-handler.cjs', 'pre-bash', 'project') }] }],
+ SessionStart: [{ hooks: [{ type: 'command', command: gitRootImport }, { type: 'command', command: 'node my-own-hook.js' }] }],
+ },
+ statusLine: { type: 'command', command: helperStatusLineCommand('project') },
+ });
+
+ it('re-pins user-level settings to $HOME and keeps user-authored hooks', () => {
+ const { merged } = mergeSettingsForUpgrade(existing(), homedir());
+ const commands = commandsOf(merged as unknown as Settings);
+ expect(commands).toContain('node my-own-hook.js');
+ for (const command of commands.filter((c) => c !== 'node my-own-hook.js')) {
+ expect(command).not.toContain('CLAUDE_PROJECT_DIR');
+ expect(command).not.toContain('git rev-parse');
+ }
+ });
+
+ it('leaves project-level settings on the project-first forms', () => {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-upgrade-project-'));
+ tempRoots.push(project);
+ const { merged } = mergeSettingsForUpgrade(existing(), project);
+ const commands = commandsOf(merged as unknown as Settings);
+ expect(commands).toContain(gitRootImport);
+ expect(commands).toContain(helperStatusLineCommand('project'));
+ });
+});
+
+describe.skipIf(process.platform === 'win32')('user-level command at runtime', () => {
+ it('runs the home helper even when the project ships its own', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-user-hook-'));
+ tempRoots.push(root);
+ const home = join(root, 'home');
+ const project = join(root, 'project');
+ for (const dir of [join(home, '.claude', 'helpers'), join(project, '.claude', 'helpers')]) mkdirSync(dir, { recursive: true });
+ const marker = (name: string) => `require('fs').writeFileSync(${JSON.stringify(join(root, name))}, '1');\n`;
+ writeFileSync(join(home, '.claude', 'helpers', 'hook-handler.cjs'), marker('home-ran'));
+ writeFileSync(join(project, '.claude', 'helpers', 'hook-handler.cjs'), marker('project-ran'));
+
+ const command = helperHookCommand('.claude/helpers/hook-handler.cjs', 'route', 'user', false);
+ const result = spawnSync('sh', ['-c', command], {
+ cwd: project,
+ env: { ...process.env, HOME: home, CLAUDE_PROJECT_DIR: project },
+ timeout: 10_000,
+ });
+
+ expect(result.status).toBe(0);
+ expect(existsSync(join(root, 'home-ran'))).toBe(true);
+ expect(existsSync(join(root, 'project-ran'))).toBe(false);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 7ffabfebf1..5ddd82a5f6 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -33,6 +33,7 @@ import { generateClaudeMd } from './claudemd-generator.js';
import { recordMemoryPackagePath } from './memory-package-resolver.js';
import { ensureCommonJsCompanions } from './helper-companions.js';
import { scanSettingsForRisk, formatRiskFindingsAsWarnings } from './settings-risk-scanner.js';
+import { helperHookCommand, helperScopeFor, helperStatusLineCommand, pinToUserHelpers } from './helper-commands.js';
/**
* Skills to copy based on configuration
@@ -337,7 +338,8 @@ export interface UpgradeResult {
* Uses platform-specific commands for Mac, Linux, and Windows
*/
export function mergeSettingsForUpgrade(
- existing: Record<string, unknown>
+ existing: Record<string, unknown>,
+ targetDir?: string
): { merged: Record<string, unknown>; warnings: string[] } {
// Scan the pre-existing hooks/permissions BEFORE they get spread into
// `merged` below β€” this is the untrusted, disk-sourced content a
@@ -347,6 +349,9 @@ export function mergeSettingsForUpgrade(
);
const merged = { ...existing };
+ // User-level settings (~/.claude/settings.json) apply to every opened
+ // project, so their helper commands never look inside the project.
+ const scope = helperScopeFor(targetDir);
const platform = detectPlatform();
const isWindows = platform.os === 'windows';
@@ -376,8 +381,12 @@ export function mergeSettingsForUpgrade(
+ "try{r=c.execSync('git rev-parse --show-toplevel',{encoding:'utf8'}).trim()}"
+ 'catch(e){r=process.cwd()}';
const autoMemoryScript = '.claude/helpers/auto-memory-hook.mjs';
- const autoMemoryImportCmd = `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" import`;
- const autoMemorySyncCmd = `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" sync`;
+ const autoMemoryImportCmd = scope === 'user'
+ ? helperHookCommand(autoMemoryScript, 'import', 'user')
+ : `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" import`;
+ const autoMemorySyncCmd = scope === 'user'
+ ? helperHookCommand(autoMemoryScript, 'sync', 'user')
+ : `node -e "${gitRootResolver}var f=p.join(r,'${autoMemoryScript}');import(u.pathToFileURL(f).href)" sync`;
// Add auto-memory import to SessionStart (if not already present)
const sessionStartHooks = existingHooks.SessionStart as Array<{ hooks?: Array<{ command?: string }> }> | undefined;
@@ -435,7 +444,7 @@ export function mergeSettingsForUpgrade(
// / jetsam / kernel panic. Preserving the user's existing command (the
// old behavior here) means anyone who installed pre-#2337 and upgraded
// never gets the fix. Now we detect the broken form and overwrite.
- const NEW_STATUSLINE_CMD =
+ const NEW_STATUSLINE_CMD = scope === 'user' ? helperStatusLineCommand('user') :
`node -e "var c=require('child_process'),p=require('path'),r;try{r=c.execSync('git rev-parse --show-toplevel',{encoding:'utf8'}).trim()}catch(e){r=process.cwd()}var s=p.join(r,'.claude/helpers/statusline.cjs');process.argv.splice(1,0,s);require(s)"`;
// Matches any invocation of `claude-flow hooks statusline` β€” either via npx
// (`npx [--prefer-offline] [@]claude-flow[/cli][@<tag>] hooks statusline …`)
@@ -453,9 +462,10 @@ export function mergeSettingsForUpgrade(
if (existingStatusLine) {
const existingCmd = typeof existingStatusLine.command === 'string' ? existingStatusLine.command : '';
const isBroken = BROKEN_STATUSLINE_RE.test(existingCmd) || BROKEN_NPX_LATEST_RE.test(existingCmd);
+ const pinned = scope === 'user' ? pinToUserHelpers(existingCmd) : null;
merged.statusLine = {
type: 'command',
- command: isBroken || !existingCmd ? NEW_STATUSLINE_CMD : existingCmd,
+ command: isBroken || !existingCmd ? NEW_STATUSLINE_CMD : pinned ?? existingCmd,
// Remove invalid fields: refreshMs, enabled (not supported by Claude Code)
};
}
@@ -471,15 +481,9 @@ export function mergeSettingsForUpgrade(
// migration on already-correct settings is a no-op.
// Bounded for the same reason as BROKEN_STATUSLINE_RE above (CodeQL js/redos).
const BROKEN_HOOK_RE = /npx\s+(?:--?\S+\s+){0,10}@?claude-flow\/cli@latest\s+hooks\s+(\S+)/;
- const localHookCmd = (sub: string): string => {
- // POSIX form mirrors settings-generator.ts::hookCmd() exactly.
- // Windows users hit a separate code path (cmd /c …) β€” Claude Code on
- // Windows is rarer and the migration there is left to a follow-up.
- if (process.platform === 'win32') {
- return `cmd /c "IF EXIST \"%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs\" (node \"%CLAUDE_PROJECT_DIR%\\.claude\\helpers\\hook-handler.cjs\" ${sub}) ELSE (node \"%USERPROFILE%\\.claude\\helpers\\hook-handler.cjs\" ${sub})"`;
- }
- return `sh -c 'D="\${CLAUDE_PROJECT_DIR:-.}"; [ -f "$D/.claude/helpers/hook-handler.cjs" ] || D="\${HOME}"; exec node "$D/.claude/helpers/hook-handler.cjs" ${sub}'`;
- };
+ // Same command settings-generator.ts emits for this settings scope.
+ const localHookCmd = (sub: string): string =>
+ helperHookCommand('.claude/helpers/hook-handler.cjs', sub, scope);
const mergedHooks = merged.hooks as Record<string, unknown> | undefined;
if (mergedHooks) {
for (const eventName of Object.keys(mergedHooks)) {
@@ -489,6 +493,12 @@ export function mergeSettingsForUpgrade(
if (!Array.isArray(group.hooks)) continue;
group.hooks = group.hooks.filter((h) => {
if (typeof h?.command !== 'string') return true;
+ // A user-level probe ruflo generated earlier is re-pinned to HOME.
+ const pinned = scope === 'user' ? pinToUserHelpers(h.command) : null;
+ if (pinned) {
+ h.command = pinned;
+ return true;
+ }
const m = BROKEN_HOOK_RE.exec(h.command);
if (m) {
// Subcommand captured (e.g. "pre-bash", "post-edit", "route") β€” keep it.
@@ -730,7 +740,7 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)
if (fs.existsSync(settingsPath)) {
try {
const existingSettings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
- const { merged: mergedSettings, warnings: settingsRiskWarnings } = mergeSettingsForUpgrade(existingSettings);
+ const { merged: mergedSettings, warnings: settingsRiskWarnings } = mergeSettingsForUpgrade(existingSettings, targetDir);
fs.writeFileSync(settingsPath, JSON.stringify(mergedSettings, null, 2), 'utf-8');
result.updated.push('.claude/settings.json');
result.settingsUpdated = [
diff --git a/v3/@claude-flow/cli/src/init/helper-commands.ts b/v3/@claude-flow/cli/src/init/helper-commands.ts
new file mode 100644
index 0000000000..11ef8f7a65
--- /dev/null
+++ b/v3/@claude-flow/cli/src/init/helper-commands.ts
@@ -0,0 +1,104 @@
+/**
+ * Hook and statusline commands that launch the `.claude/helpers` scripts.
+ *
+ * A project-level settings.json (`<project>/.claude/settings.json`) keeps the
+ * #1943 probe: run the project's helper, fall back to `$HOME/.claude/helpers`.
+ * The project controls that settings file anyway, so preferring its helpers
+ * grants it nothing new.
+ *
+ * A user-level settings.json (`~/.claude/settings.json`) applies to every
+ * project the user opens. There the probe would let any opened project supply
+ * the helper that runs, so user-level commands are pinned to the user's own
+ * `$HOME/.claude/helpers` with no project lookup.
+ */
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+export type HelperScope = 'project' | 'user';
+
+const IS_WINDOWS = process.platform === 'win32';
+const STATUSLINE_SCRIPT = '.claude/helpers/statusline.cjs';
+
+function canonical(dir: string): string {
+ try {
+ return fs.realpathSync(dir);
+ } catch {
+ return path.resolve(dir);
+ }
+}
+
+/** Settings written into the user's home directory are user-level settings. */
+export function helperScopeFor(targetDir: string | undefined): HelperScope {
+ if (!targetDir) return 'project';
+ return canonical(targetDir) === canonical(os.homedir()) ? 'user' : 'project';
+}
+
+/** 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})"`;
+ }
+ // 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:-.}';
+ // eslint-disable-next-line no-template-curly-in-string
+ const homeVar = '${HOME}';
+ return `sh -c 'D="${projVar}"; [ -f "$D/${script}" ] || D="${homeVar}"; exec node "$D/${script}"${arg}'`;
+}
+
+/** Command for the statusLine entry. */
+export function helperStatusLineCommand(scope: HelperScope, windows = IS_WINDOWS): string {
+ if (windows) {
+ // The Node CLI's `-e` flag avoids all shell-quoting pitfalls (#1948,
+ // #1973): never `cmd /c` for statusline, it blocks stdin forwarding.
+ const home = "p.join(process.env.USERPROFILE||process.env.HOME||'.', '" + STATUSLINE_SCRIPT + "')";
+ const js = scope === 'user'
+ ? `const p=require('path');require(${home});`
+ : "const fs=require('fs'),p=require('path');" +
+ `const d=process.env.CLAUDE_PROJECT_DIR||'.';` +
+ `const f=p.join(d,'${STATUSLINE_SCRIPT}');` +
+ `const h=${home};` +
+ 'require(fs.existsSync(f)?f:h);';
+ return `node -e "${js}"`;
+ }
+ if (scope === 'user') return `sh -c 'exec node "\${HOME}/${STATUSLINE_SCRIPT}"'`;
+ // eslint-disable-next-line no-template-curly-in-string
+ const projVar = '${CLAUDE_PROJECT_DIR:-.}';
+ // eslint-disable-next-line no-template-curly-in-string
+ const homeVar = '${HOME}';
+ return `sh -c 'D="${projVar}"; [ -f "$D/${STATUSLINE_SCRIPT}" ] || D="${homeVar}"; exec node "$D/${STATUSLINE_SCRIPT}"'`;
+}
+
+const POSIX_PROBE = /^sh -c 'D="\$\{CLAUDE_PROJECT_DIR:-\.\}"; \[ -f "\$D\/(\.claude\/helpers\/[\w.-]+)" \] \|\| D="\$\{HOME\}"; exec node "\$D\/\1"( [\w:-]+)?'$/;
+const WINDOWS_PROBE = /^cmd \/c "IF EXIST "%CLAUDE_PROJECT_DIR%\\(\.claude\\helpers\\[\w.-]+)" \(node "%CLAUDE_PROJECT_DIR%\\\1"( [\w:-]+)?\) ELSE \(node "%USERPROFILE%\\\1"\2\)"$/;
+// `ruflo init --upgrade` wrote these git-root forms (#1259, #1284, #2450).
+const GIT_ROOT_IMPORT = /^node -e "var c=require\('child_process'\),p=require\('path'\),u=require\('url'\),r;try\{r=c\.execSync\('git rev-parse --show-toplevel',\{encoding:'utf8'\}\)\.trim\(\)\}catch\(e\)\{r=process\.cwd\(\)\}var f=p\.join\(r,'(\.claude\/helpers\/[\w.-]+)'\);import\(u\.pathToFileURL\(f\)\.href\)"( [\w:-]+)?$/;
+const GIT_ROOT_STATUSLINE = `node -e "var c=require('child_process'),p=require('path'),r;try{r=c.execSync('git rev-parse --show-toplevel',{encoding:'utf8'}).trim()}catch(e){r=process.cwd()}var s=p.join(r,'.claude/helpers/statusline.cjs');process.argv.splice(1,0,s);require(s)"`;
+
+/**
+ * Rewrite a command ruflo itself generated with a project lookup into the
+ * pinned user-level form. Returns null for anything else (user-authored
+ * commands are left alone).
+ */
+export function pinToUserHelpers(command: string, windows = IS_WINDOWS): string | null {
+ if (command === GIT_ROOT_STATUSLINE || command === helperStatusLineCommand('project', windows)) {
+ return helperStatusLineCommand('user', windows);
+ }
+ const posix = POSIX_PROBE.exec(command);
+ if (posix) return helperHookCommand(posix[1], (posix[2] ?? '').trim(), 'user', windows);
+ const win = WINDOWS_PROBE.exec(command);
+ if (win) return helperHookCommand(win[1].replace(/\\/g, '/'), (win[2] ?? '').trim(), 'user', windows);
+ const gitRoot = GIT_ROOT_IMPORT.exec(command);
+ if (gitRoot) return helperHookCommand(gitRoot[1], (gitRoot[2] ?? '').trim(), 'user', windows);
+ return null;
+}
diff --git a/v3/@claude-flow/cli/src/init/settings-generator.ts b/v3/@claude-flow/cli/src/init/settings-generator.ts
index 823f723aa7..1b49a6a48b 100644
--- a/v3/@claude-flow/cli/src/init/settings-generator.ts
+++ b/v3/@claude-flow/cli/src/init/settings-generator.ts
@@ -5,6 +5,7 @@
import type { InitOptions, HooksConfig, PlatformInfo } from './types.js';
import { detectPlatform } from './types.js';
+import { helperHookCommand, helperScopeFor, helperStatusLineCommand, type HelperScope } from './helper-commands.js';
/**
* Generate the complete settings.json content
@@ -19,7 +20,7 @@ export function generateSettings(options: InitOptions): object {
// fails to find its handler. Either bundle the helpers OR drop the hooks β€”
// the option this fix takes is the latter (minimal stays minimal).
if (options.components.settings && options.components.helpers) {
- settings.hooks = generateHooksConfig(options.hooks);
+ settings.hooks = generateHooksConfig(options.hooks, helperScopeFor(options.targetDir));
}
// Add statusLine configuration if enabled
@@ -173,109 +174,37 @@ export function generateSettings(options: InitOptions): object {
}
/**
- * Detect if we're on Windows for platform-aware hook commands.
+ * Build a hook command that resolves to the right helpers dir for where the
+ * settings live (#1943). Project-level settings probe the project's helpers
+ * first and fall back to `$HOME/.claude/helpers`; user-level settings
+ * (`~/.claude/settings.json`) apply to every opened project, so they are
+ * pinned to `$HOME/.claude/helpers`. See helper-commands.ts.
*/
-const IS_WINDOWS = process.platform === 'win32';
-
-/**
- * Build a hook command that resolves to the right helpers dir on every
- * install layout. `ruflo init` can land helpers either project-locally
- * (`<project>/.claude/helpers/…`, when run from a project root) or globally
- * (`$HOME/.claude/helpers/…`, when settings.json gets merged into the
- * user-level Claude Code config). The earlier `${CLAUDE_PROJECT_DIR:-.}`
- * form assumed project-local β€” so any global-install user hit
- * `MODULE_NOT_FOUND` on every Bash/Edit/Session hook (#1943).
- *
- * The fix is a tiny POSIX `sh` probe: try `$CLAUDE_PROJECT_DIR/.claude/...`
- * first, fall back to `$HOME/.claude/...` if it's missing. Both modes work,
- * the global install never crashes, and project-local overrides still take
- * precedence when present. On Windows, the same probe via `cmd /c` (the %~%
- * fallback uses `IF EXIST`).
- */
-function hookCmd(script: string, subcommand: string): string {
- if (IS_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%\\${script.replace(/\//g, '\\')}\" (node \"%CLAUDE_PROJECT_DIR%\\${script.replace(/\//g, '\\')}\" ${subcommand}) ELSE (node \"%USERPROFILE%\\${script.replace(/\//g, '\\')}\" ${subcommand})"`;
- }
- // POSIX sh: prefer project-local helpers, fall back to $HOME/.claude/.
- // The fallback handles `ruflo init`'s global-install path where helpers
- // live at `$HOME/.claude/helpers/` but Claude Code still sets
- // `CLAUDE_PROJECT_DIR` to the *project* root (which has no helpers).
- // eslint-disable-next-line no-template-curly-in-string
- const projVar = '${CLAUDE_PROJECT_DIR:-.}';
- // eslint-disable-next-line no-template-curly-in-string
- const homeVar = '${HOME}';
- return `sh -c 'D="${projVar}"; [ -f "$D/${script}" ] || D="${homeVar}"; exec node "$D/${script}" ${subcommand}'`;
+function hookCmd(script: string, subcommand: string, scope: HelperScope): string {
+ return helperHookCommand(script, subcommand, scope);
}
/** Shorthand for CJS hook-handler commands */
-function hookHandlerCmd(subcommand: string): string {
- return hookCmd('.claude/helpers/hook-handler.cjs', subcommand);
+function hookHandlerCmd(subcommand: string, scope: HelperScope): string {
+ return hookCmd('.claude/helpers/hook-handler.cjs', subcommand, scope);
}
/** Shorthand for ESM auto-memory-hook commands */
-function autoMemoryCmd(subcommand: string): string {
- return hookCmd('.claude/helpers/auto-memory-hook.mjs', subcommand);
+function autoMemoryCmd(subcommand: string, scope: HelperScope): string {
+ return hookCmd('.claude/helpers/auto-memory-hook.mjs', subcommand, scope);
}
/**
* Generate statusLine configuration for Claude Code
- * Uses local helper script for cross-platform compatibility (no npx cold-start)
+ * Uses local helper script for cross-platform compatibility (no npx cold-start).
+ * Claude Code pipes JSON session data to the script via stdin; valid fields
+ * are type, command and padding. Platform handling (#1948, #1973) lives in
+ * helperStatusLineCommand().
*/
-function generateStatusLineConfig(_options: InitOptions): object {
- // Claude Code pipes JSON session data to the script via stdin.
- // Valid fields: type, command, padding (optional).
- // The script runs after each assistant message (debounced 300ms).
- //
- // ruflo#1948 + #1973: the previous `sh -c 'D="${CLAUDE_PROJECT_DIR:-.}"; …'`
- // form requires a POSIX shell on PATH. On native Windows (no
- // Git-Bash / WSL), `sh` either isn't found or its quoting gets
- // mangled, producing weird artifacts like files named `0)` or
- // `toastr.error('ESD...` from misparsed tokens leaking back into
- // the file system. NEVER use `cmd /c` for statusline β€” Claude Code
- // manages stdin directly for statusline commands and `cmd /c`
- // blocks the stdin forwarding.
- //
- // Solution: emit a platform-appropriate command at init time.
- // POSIX: `sh -c 'D="…"; … exec node "$D/<script>"'` (existing)
- // Windows: a Node.js one-liner that resolves the path internally
- // using `process.env.CLAUDE_PROJECT_DIR` with a HOME
- // fallback β€” no shell-quoting hazards because the
- // resolution happens inside node, not in the shell.
- const script = '.claude/helpers/statusline.cjs';
-
- if (process.platform === 'win32') {
- // The Node CLI's `-e` flag avoids all shell-quoting pitfalls.
- // We write the path resolution in JS:
- // const fs = require('fs'); const p = require('path');
- // const d = process.env.CLAUDE_PROJECT_DIR || '.';
- // const f = p.join(d, '.claude/helpers/statusline.cjs');
- // const home = process.env.USERPROFILE || process.env.HOME || '.';
- // const h = p.join(home, '.claude/helpers/statusline.cjs');
- // require(fs.existsSync(f) ? f : h);
- // …compressed onto one line. Double-quotes around the -e arg are
- // safe on cmd.exe; the inner JS uses single-quotes for strings.
- const js =
- "const fs=require('fs'),p=require('path');" +
- `const d=process.env.CLAUDE_PROJECT_DIR||'.';` +
- `const f=p.join(d,'${script}');` +
- `const h=p.join(process.env.USERPROFILE||process.env.HOME||'.', '${script}');` +
- 'require(fs.existsSync(f)?f:h);';
- return {
- type: 'command',
- command: `node -e "${js}"`,
- };
- }
-
- // Same project-local / $HOME fallback as `hookCmd()` (see #1943).
- // eslint-disable-next-line no-template-curly-in-string
- const projVar = '${CLAUDE_PROJECT_DIR:-.}';
- // eslint-disable-next-line no-template-curly-in-string
- const homeVar = '${HOME}';
+function generateStatusLineConfig(options: InitOptions): object {
return {
type: 'command',
- command: `sh -c 'D="${projVar}"; [ -f "$D/${script}" ] || D="${homeVar}"; exec node "$D/${script}"'`,
+ command: helperStatusLineCommand(helperScopeFor(options.targetDir)),
};
}
@@ -285,7 +214,7 @@ function generateStatusLineConfig(_options: InitOptions): object {
* All hooks invoke scripts directly via `node <script> <subcommand>`,
* working identically on Windows, macOS, and Linux.
*/
-function generateHooksConfig(config: HooksConfig): object {
+function generateHooksConfig(config: HooksConfig, scope: HelperScope): object {
const hooks: Record<string, unknown[]> = {};
// Node.js scripts handle errors internally via try/catch.
@@ -299,7 +228,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('pre-bash'),
+ command: hookHandlerCmd('pre-bash', scope),
timeout: config.timeout,
},
],
@@ -309,7 +238,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('pre-edit'),
+ command: hookHandlerCmd('pre-edit', scope),
timeout: config.timeout,
},
],
@@ -325,7 +254,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('post-edit'),
+ command: hookHandlerCmd('post-edit', scope),
timeout: 10000,
},
],
@@ -335,7 +264,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('post-bash'),
+ command: hookHandlerCmd('post-bash', scope),
timeout: config.timeout,
},
],
@@ -350,7 +279,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('route'),
+ command: hookHandlerCmd('route', scope),
timeout: 10000,
},
],
@@ -365,12 +294,12 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('session-restore'),
+ command: hookHandlerCmd('session-restore', scope),
timeout: 15000,
},
{
type: 'command',
- command: autoMemoryCmd('import'),
+ command: autoMemoryCmd('import', scope),
timeout: 8000,
},
],
@@ -385,7 +314,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('session-end'),
+ command: hookHandlerCmd('session-end', scope),
timeout: 10000,
},
],
@@ -400,7 +329,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: autoMemoryCmd('sync'),
+ command: autoMemoryCmd('sync', scope),
timeout: 10000,
},
],
@@ -416,11 +345,11 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('compact-manual'),
+ command: hookHandlerCmd('compact-manual', scope),
},
{
type: 'command',
- command: hookHandlerCmd('session-end'),
+ command: hookHandlerCmd('session-end', scope),
timeout: 5000,
},
],
@@ -430,11 +359,11 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('compact-auto'),
+ command: hookHandlerCmd('compact-auto', scope),
},
{
type: 'command',
- command: hookHandlerCmd('session-end'),
+ command: hookHandlerCmd('session-end', scope),
timeout: 6000,
},
],
@@ -448,7 +377,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('status'),
+ command: hookHandlerCmd('status', scope),
timeout: 3000,
},
],
@@ -462,7 +391,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('post-task'),
+ command: hookHandlerCmd('post-task', scope),
timeout: 5000,
},
],
@@ -476,7 +405,7 @@ function generateHooksConfig(config: HooksConfig): object {
hooks: [
{
type: 'command',
- command: hookHandlerCmd('notify'),
+ command: hookHandlerCmd('notify', scope),
timeout: 3000,
},
],