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): re-pin every legacy project-helper command form in user scope

Dragan Spiridonov16bd4ac94889
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 813757545e..deed227414 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
@@ -6,13 +6,13 @@
*/
import { afterEach, describe, expect, it } from 'vitest';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, 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 { executeUpgrade, mergeSettingsForUpgrade } from '../src/init/executor.js';
import { helperHookCommand, helperStatusLineCommand, pinToUserHelpers } from '../src/init/helper-commands.js';
const tempRoots: string[] = [];
@@ -72,6 +72,70 @@ describe('helper command forms', () => {
});
});
+// Command forms earlier ruflo releases wrote into settings.json. Each one runs
+// the opened project's copy of the helper; in user scope all must be re-pinned.
+const GIT_ROOT = "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()}";
+const GIT_ROOT_ESM = "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()}";
+const userHook = (script: string, sub: string, windows: boolean) => helperHookCommand(`.claude/helpers/${script}`, sub, 'user', windows);
+const LEGACY: Array<[string, string, boolean, string]> = [
+ // name, shipped command, windows, expected pinned command
+ ['pre-#1943 sh form (settings-generator at 3657a6936^)',
+ `sh -c 'exec node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/hook-handler.cjs" pre-bash'`, false, userHook('hook-handler.cjs', 'pre-bash', false)],
+ ['pre-#1943 Windows cmd form',
+ 'cmd /c node %CLAUDE_PROJECT_DIR%/.claude/helpers/hook-handler.cjs pre-bash', true, userHook('hook-handler.cjs', 'pre-bash', true)],
+ ['ADR-059 git-root CJS form with argv.splice (48b70afca)',
+ `node -e "${GIT_ROOT}var s=p.join(r,'.claude/helpers/hook-handler.cjs');process.argv.splice(1,0,s);require(s)" pre-edit`, false, userHook('hook-handler.cjs', 'pre-edit', false)],
+ ['ADR-059 git-root ESM form with argv.splice',
+ `node -e "${GIT_ROOT_ESM}var f=p.join(r,'.claude/helpers/auto-memory-hook.mjs');process.argv.splice(1,0,f);import(u.pathToFileURL(f).href)" import`, false, userHook('auto-memory-hook.mjs', 'import', false)],
+ ['upgrade git-root ESM form without argv.splice',
+ `node -e "${GIT_ROOT_ESM}var f=p.join(r,'.claude/helpers/auto-memory-hook.mjs');import(u.pathToFileURL(f).href)" sync`, false, userHook('auto-memory-hook.mjs', 'sync', false)],
+ ['ADR-059 git-root statusline',
+ `node -e "${GIT_ROOT}var s=p.join(r,'.claude/helpers/statusline.cjs');process.argv.splice(1,0,s);require(s)"`, false, helperStatusLineCommand('user', false)],
+ ['pre-#1943 sh statusline',
+ `sh -c 'exec node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline.cjs"'`, false, helperStatusLineCommand('user', false)],
+ ['pre-ADR-059 relative statusline',
+ 'node .claude/helpers/statusline.cjs', false, helperStatusLineCommand('user', false)],
+ ['pre-ADR-059 relative hook',
+ 'node .claude/helpers/hook-handler.cjs session-restore', false, userHook('hook-handler.cjs', 'session-restore', false)],
+];
+
+describe('legacy command forms in user scope', () => {
+ for (const [name, command, windows, expected] of LEGACY) {
+ it(`re-pins ${name}`, () => {
+ expect(pinToUserHelpers(command, windows)).toBe(expected);
+ });
+ }
+
+ it('leaves user-authored and already-pinned commands alone', () => {
+ for (const command of [
+ 'node .claude/helpers/hook-handler.cjs pre-bash 2>/dev/null',
+ 'node .claude/helpers/hook-handler.cjs pre-bash && echo done',
+ 'node .claude/helpers/my-own-script.js run',
+ 'node ./scripts/lint.js',
+ userHook('hook-handler.cjs', 'pre-bash', false),
+ userHook('hook-handler.cjs', 'pre-bash', true),
+ helperStatusLineCommand('user', false),
+ helperStatusLineCommand('user', true),
+ ]) {
+ expect(pinToUserHelpers(command, command.startsWith('cmd') || command.includes('USERPROFILE'))).toBeNull();
+ }
+ });
+
+ it('mergeSettingsForUpgrade re-pins every legacy form for a home target', () => {
+ const existing = {
+ hooks: {
+ PreToolUse: [{ hooks: LEGACY.filter(([, , w]) => !w).map(([, command]) => ({ type: 'command', command })) }],
+ },
+ statusLine: { type: 'command', command: 'node .claude/helpers/statusline.cjs' },
+ };
+ const { merged } = mergeSettingsForUpgrade(existing, homedir());
+ const commands = commandsOf(merged as unknown as Settings);
+ for (const command of commands) {
+ expect(command).not.toMatch(/CLAUDE_PROJECT_DIR|git rev-parse|(^|\s)\.claude\/helpers/);
+ }
+ });
+});
+
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 = () => ({
@@ -102,6 +166,23 @@ describe('ruflo init --upgrade --settings', () => {
});
});
+describe('executeUpgrade creates missing settings for its target', () => {
+ it('pins the commands when the target is the home directory', async () => {
+ const savedHome = process.env.HOME;
+ const home = mkdtempSync(join(tmpdir(), 'ruflo-upgrade-home-'));
+ tempRoots.push(home);
+ process.env.HOME = home;
+ try {
+ const result = await executeUpgrade(home, true);
+ expect(result.created).toContain('.claude/settings.json');
+ const settings = JSON.parse(readFileSync(join(home, '.claude', 'settings.json'), 'utf8')) as Settings;
+ for (const command of commandsOf(settings)) expect(command).not.toContain('CLAUDE_PROJECT_DIR');
+ } finally {
+ if (savedHome === undefined) delete process.env.HOME; else process.env.HOME = savedHome;
+ }
+ });
+});
+
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-'));
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 5ddd82a5f6..319e36cd02 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -760,7 +760,7 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)
}
} else {
// Create new settings.json with defaults
- const defaultSettings = generateSettings(DEFAULT_INIT_OPTIONS);
+ const defaultSettings = generateSettings({ ...DEFAULT_INIT_OPTIONS, targetDir });
fs.writeFileSync(settingsPath, JSON.stringify(defaultSettings, null, 2), 'utf-8');
result.created.push('.claude/settings.json');
result.settingsUpdated = ['Created new settings.json with Agent Teams'];
diff --git a/v3/@claude-flow/cli/src/init/helper-commands.ts b/v3/@claude-flow/cli/src/init/helper-commands.ts
index 11ef8f7a65..5c5d99f073 100644
--- a/v3/@claude-flow/cli/src/init/helper-commands.ts
+++ b/v3/@claude-flow/cli/src/init/helper-commands.ts
@@ -79,26 +79,60 @@ export function helperStatusLineCommand(scope: HelperScope, windows = IS_WINDOWS
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)"`;
+// Helpers ruflo installs under .claude/helpers that settings can launch.
+const RUFLO_HELPERS = [
+ 'hook-handler.cjs', 'auto-memory-hook.mjs', 'statusline.cjs', 'ruflo-hook.cjs', 'router.cjs',
+ 'session.cjs', 'memory.cjs', 'intelligence.cjs', 'learning-service.mjs', 'metrics-db.mjs',
+ 'context-persistence-hook.mjs',
+];
+const HELPER_REF = new RegExp(`\\.claude[\\\\/]helpers[\\\\/](${RUFLO_HELPERS.map((h) => h.replace('.', '\\.')).join('|')})`, 'g');
+// How a ruflo-generated command reached the project's copy of a helper:
+// CLAUDE_PROJECT_DIR (sh, cmd or node -e), `git rev-parse --show-toplevel`,
+// or a path relative to the cwd.
+const PROJECT_REACH = /CLAUDE_PROJECT_DIR|git rev-parse --show-toplevel/;
+const RELATIVE_REF = /(?:^|[\s"'])(?:\.[\\/])?\.claude[\\/]helpers[\\/]/;
+const SHELL_CHAINING = /&&|\|\||[;|<>`]/;
+const ARGS = /^(?: [\w:.=-]+)*$/;
+// The fixed shell scaffolding of the #1943 probes, which itself contains `;`
+// and `||`; removed before checking the rest for chaining.
+const PROBE_PREAMBLE = /D="\$\{CLAUDE_PROJECT_DIR:-\.\}"; \[ -f "\$D\/\.claude\/helpers\/[\w.-]+" \] \|\| D="\$\{HOME\}"; /;
+const IF_EXIST_PREAMBLE = /"IF EXIST "%CLAUDE_PROJECT_DIR%\\\.claude\\helpers\\[\w.-]+" \(node "%CLAUDE_PROJECT_DIR%\\\.claude\\helpers\\[\w.-]+"(?: [\w:.=-]+)*\) ELSE \(/;
/**
- * 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).
+ * Rewrite a command that runs one of ruflo's helpers from the opened project
+ * into the pinned user-level form, keeping its subcommand. Covers every form
+ * ruflo has shipped: the #1943 sh/cmd probes, the earlier
+ * `${CLAUDE_PROJECT_DIR:-.}` / `%CLAUDE_PROJECT_DIR%` forms, the ADR-059
+ * `git rev-parse` node -e forms (CJS and ESM, with or without argv.splice),
+ * and plain relative paths. Returns null for anything else, so user-authored
+ * commands (other scripts, redirects, chains) 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 refs = [...command.matchAll(HELPER_REF)];
+ if (refs.length === 0) return null;
+ const helper = refs[refs.length - 1][1];
+ if (refs.some((m) => m[1] !== helper)) return null;
+ if (!PROJECT_REACH.test(command) && !RELATIVE_REF.test(command)) return null;
+
+ let args: string;
+ const nodeEval = /^node -e "(.*)"((?: [\w:.=-]+)*)$/.exec(command);
+ if (nodeEval) {
+ if (!/git rev-parse --show-toplevel|CLAUDE_PROJECT_DIR/.test(nodeEval[1])) return null;
+ args = nodeEval[2];
+ } else {
+ if (!/^(?:sh -c '|cmd \/c |node )/.test(command)) return null;
+ // Drop the shell wrapper's closing quote / paren, then split around the
+ // last helper reference: the head launches it, the tail is its argv.
+ const body = command.replace(/'$/, '').replace(/\)"$/, '');
+ const last = refs[refs.length - 1];
+ const head = body.slice(0, last.index ?? 0).replace(PROBE_PREAMBLE, '').replace(IF_EXIST_PREAMBLE, '');
+ let tail = body.slice((last.index ?? 0) + last[0].length);
+ if (tail.startsWith('"')) tail = tail.slice(1);
+ if (SHELL_CHAINING.test(head) || SHELL_CHAINING.test(tail)) return null;
+ args = tail.trimEnd();
}
- 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;
+ if (!ARGS.test(args)) return null;
+ const script = `.claude/helpers/${helper}`;
+ if (helper === 'statusline.cjs' && args === '') return helperStatusLineCommand('user', windows);
+ return helperHookCommand(script, args.trim(), 'user', windows);
}