π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(plugins): run the installed ruflo CLI before `npx @claude-flow/cli@latest` in cost-tracker, adr and metaharness (#3558)
Mr. Mak2015071b98de
diff --git a/.github/workflows/metaharness-ci.yml b/.github/workflows/metaharness-ci.ymlindex 0dccd1303c..982dee3f0d 100644--- a/.github/workflows/metaharness-ci.yml+++ b/.github/workflows/metaharness-ci.yml@@ -50,6 +50,9 @@ jobs:- name: CLI help and invalid arguments have no side effectsrun: node --test plugins/ruflo-metaharness/scripts/test-cli-help.mjs+ - name: Memory calls prefer the installed ruflo CLI over npx @latest (#3558)+ run: node --test plugins/ruflo-metaharness/scripts/test-cli-resolution-3558.mjs+- name: Plugin structural smokerun: bash plugins/ruflo-metaharness/scripts/smoke.shdiff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.ymlindex 83857d3ceb..9101f0370a 100644--- a/.github/workflows/v3-ci.yml+++ b/.github/workflows/v3-ci.yml@@ -11,6 +11,10 @@ on:- 'plugins/ruflo-core/scripts/witness/**'- 'plugins/ruflo-core/scripts/test-hooks.mjs'- 'plugins/ruflo-cost-tracker/scripts/test-hooks.mjs'+ # #3558 β installed-CLI resolution for cost-tracker's memory/hooks calls+ - 'plugins/ruflo-cost-tracker/scripts/_npx.mjs'+ - 'plugins/ruflo-cost-tracker/scripts/_ruflo-cli.mjs'+ - 'plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs'- 'verification/**'# scripts/*.mjs audits (tool-descriptions, plugin-packages, hook-commands)- 'scripts/**'@@ -163,6 +167,10 @@ on:- 'plugins/ruflo-core/scripts/witness/**'- 'plugins/ruflo-core/scripts/test-hooks.mjs'- 'plugins/ruflo-cost-tracker/scripts/test-hooks.mjs'+ # #3558 β installed-CLI resolution for cost-tracker's memory/hooks calls+ - 'plugins/ruflo-cost-tracker/scripts/_npx.mjs'+ - 'plugins/ruflo-cost-tracker/scripts/_ruflo-cli.mjs'+ - 'plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs'- 'scripts/**'- '**/hooks/hooks.json'- '**/scripts/ruflo-hook.cjs'@@ -659,6 +667,11 @@ jobs:run: |node plugins/ruflo-cost-tracker/scripts/test-hooks.mjs+ - name: cost-tracker prefers the installed ruflo CLI over npx @latest (#3558)+ shell: bash+ run: |+ node plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs+browser-rvf-create-flags-smoke:# Regression guard for ruvnet/ruflo#2015 β the ruflo-browser# `browser_session_record` MCP tool wraps `ruvector rvf create`.diff --git a/plugins/ruflo-adr/scripts/__tests__/import-root-exit-3097.test.mjs b/plugins/ruflo-adr/scripts/__tests__/import-root-exit-3097.test.mjsindex 4cb0cf30b0..19ba0208de 100644--- a/plugins/ruflo-adr/scripts/__tests__/import-root-exit-3097.test.mjs+++ b/plugins/ruflo-adr/scripts/__tests__/import-root-exit-3097.test.mjs@@ -42,6 +42,10 @@ function run(fixture, format, fail = false) {ADR_TEST_FAIL: fail ? '1' : '0',IMPORT_FORMAT: format,PATH: `${fixture.bin}:${process.env.PATH}`,+ // #3558: pin the npx shim β a built checkout or an installed ruflo on+ // PATH would otherwise be preferred over it (lib/ruflo-cli.mjs).+ RUFLO_PLUGIN_SKIP_LOCAL_CLI: '1',+ RUFLO_PLUGIN_SKIP_PATH_CLI: '1',},});}diff --git a/plugins/ruflo-adr/scripts/__tests__/prefer-installed-cli-3558.test.mjs b/plugins/ruflo-adr/scripts/__tests__/prefer-installed-cli-3558.test.mjsnew file mode 100644index 0000000000..ada160222c--- /dev/null+++ b/plugins/ruflo-adr/scripts/__tests__/prefer-installed-cli-3558.test.mjs@@ -0,0 +1,137 @@+// #3558: adr-index / adr-reindex / adr-verify must run the ruflo CLI that is+// already installed, not `npx @claude-flow/cli@latest`.+//+// A marketplace install copies the plugin to+// ~/.claude/plugins/cache/<marketplace>/ruflo-adr/<version>/ with no CLI next+// to it, so every store/purge/list went to npx @latest β possibly another CLI+// (and memory store) than the `ruflo memory search` that must find the+// records (#2781). Hermetic: the plugin is copied into a temp plugin-cache+// layout; PATH holds only temp dirs with fake `ruflo` / `npx` scripts that+// log their argv, plus a `node` link.+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import {+ chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, dirname, join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++// Support both the repository's Vitest collection and the standalone Node smoke.+const { test } = process.env.VITEST ? await import('vitest') : await import('node:test');++const PLUGIN_ROOT = fileURLToPath(new URL('../../', import.meta.url));++const write = (file, body, mode) => {+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ if (mode) chmodSync(file, mode);+};++function withFixture(fn) {+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-adr-cli-tbd-')));+ try {+ const home = join(tmp, 'home');+ const cache = join(home, '.claude', 'plugins', 'cache', 'ruflo', 'ruflo-adr', '0.0.0-test');+ cpSync(PLUGIN_ROOT, cache, { recursive: true });+ const log = join(tmp, 'calls.log');+ const fake = (dir, name) => write(join(dir, name),+ `#!/bin/sh\nprintf '%s %s\\n' "${name}" "$*" >> "${log}"\ncase "$*" in *"memory list"*) echo '[]' ;; *) echo '[OK] done' ;; esac\n`, 0o755);+ const nodeBin = join(tmp, 'node-bin');+ mkdirSync(nodeBin);+ symlinkSync(process.execPath, join(nodeBin, 'node'));+ const rufloBin = join(tmp, 'bin-ruflo');+ fake(rufloBin, 'ruflo');+ const npxBin = join(tmp, 'bin-npx');+ fake(npxBin, 'npx');+ const project = join(tmp, 'project');+ mkdirSync(join(project, '.git'), { recursive: true });+ write(join(project, 'docs', 'adr', 'ADR-001-test.md'), '# ADR-001: Test\n\n**Status**: Accepted\n');++ const env = { ...process.env, HOME: home, USERPROFILE: home, ADR_ROOT: project };+ for (const k of ['CLI_CORE', 'RUFLO_PLUGIN_SKIP_LOCAL_CLI', 'RUFLO_PLUGIN_SKIP_PATH_CLI', 'IMPORT_DRY_RUN', 'REINDEX_DRY_RUN', 'NODE_OPTIONS']) delete env[k];+ const run = (script, extraEnv = {}, pluginRoot = cache) => {+ rmSync(log, { force: true });+ const r = spawnSync(process.execPath, [join(pluginRoot, 'scripts', script)], {+ cwd: project, encoding: 'utf-8', timeout: 30_000, env: { ...env, ...extraEnv },+ });+ // Multi-line --value= argv spills over lines; only CLI-name-prefixed lines are calls.+ const calls = existsSync(log) ? readFileSync(log, 'utf-8').split('\n').filter((l) => /^(ruflo|npx|shipping-cli) /.test(l)) : [];+ return { ...r, calls };+ };+ fn({ tmp, run, log, path: (...dirs) => [...dirs, nodeBin].join(delimiter), rufloBin, npxBin });+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+}++test('win32: npm\'s ruflo.cmd shim maps to `node <package bin>`, never cmd.exe', async () => {+ const { findRufloOnPath } = await import(pathToFileURL(join(PLUGIN_ROOT, 'scripts', 'lib', 'ruflo-cli.mjs')).href);+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-adr-cli-win-')));+ try {+ write(join(tmp, 'ruflo.cmd'), '@ECHO off\r\n');+ write(join(tmp, 'node_modules', 'ruflo', 'package.json'), JSON.stringify({ name: 'ruflo', bin: { ruflo: 'bin/ruflo.js' } }));+ write(join(tmp, 'node_modules', 'ruflo', 'bin', 'ruflo.js'), '');+ const hit = findRufloOnPath({ Path: tmp }, 'win32');+ assert.equal(hit?.command, process.execPath);+ assert.deepEqual(hit?.args, [realpathSync(join(tmp, 'node_modules', 'ruflo', 'bin', 'ruflo.js'))]);+ assert.equal(hit?.shell, false);+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+});++if (process.platform !== 'win32') {+ test('plugin-cache install: import, reindex and verify all use the installed ruflo, never npx', () => withFixture(({ run, path, rufloBin, npxBin }) => {+ const env = { PATH: path(rufloBin, npxBin) };+ const imp = run('import.mjs', { ...env, IMPORT_FORMAT: 'json' });+ assert.equal(imp.status, 0, imp.stderr);+ assert.ok(imp.calls.some((l) => l.startsWith('ruflo memory store --namespace=adr-patterns --key=ADR-001::ADR-001-test --upsert --value=')), imp.calls.join(' | '));+ assert.deepEqual(imp.calls.filter((l) => l.startsWith('npx ')), []);++ const re = run('reindex.mjs', { ...env, REINDEX_FORMAT: 'json' });+ for (const cmd of ['ruflo memory purge --namespace=adr-patterns --force', 'ruflo memory store --namespace=adr-patterns', 'ruflo memory list --namespace adr-patterns']) {+ assert.ok(re.calls.some((l) => l.startsWith(cmd)), `reindex: expected "${cmd}" in ${re.calls.join(' | ')}`);+ }+ assert.deepEqual(re.calls.filter((l) => l.startsWith('npx ')), []);++ const ver = run('verify.mjs', { ...env, VERIFY_FORMAT: 'json' });+ assert.equal(ver.status, 0, ver.stderr);+ assert.ok(ver.calls.some((l) => l.startsWith('ruflo memory list --namespace=adr-patterns --format=json')), ver.calls.join(' | '));+ assert.deepEqual(ver.calls.filter((l) => l.startsWith('npx ')), []);+ }));++ test('no installed CLI: still `npx @claude-flow/cli@latest` (unchanged fallback)', () => withFixture(({ run, path, npxBin }) => {+ const imp = run('import.mjs', { PATH: path(npxBin), IMPORT_FORMAT: 'json' });+ assert.equal(imp.status, 0, imp.stderr);+ assert.ok(imp.calls.some((l) => l.startsWith('npx @claude-flow/cli@latest memory store --namespace=adr-patterns')), imp.calls.join(' | '));+ }));++ test('CLI_CORE=1 is still ignored (#2781): writer and reader stay on the same installed CLI', () => withFixture(({ run, path, rufloBin, npxBin }) => {+ const env = { PATH: path(rufloBin, npxBin), CLI_CORE: '1' };+ const imp = run('import.mjs', { ...env, IMPORT_FORMAT: 'json' });+ const ver = run('verify.mjs', { ...env, VERIFY_FORMAT: 'json' });+ assert.ok(imp.calls.some((l) => l.startsWith('ruflo memory store')), imp.calls.join(' | '));+ assert.ok(ver.calls.some((l) => l.startsWith('ruflo memory list')), ver.calls.join(' | '));+ assert.deepEqual([...imp.calls, ...ver.calls].filter((l) => l.includes('cli-core')), []);+ }));++ test('RUFLO_PLUGIN_SKIP_PATH_CLI=1 skips the PATH lookup (test seam)', () => withFixture(({ run, path, rufloBin, npxBin }) => {+ const imp = run('import.mjs', { PATH: path(rufloBin, npxBin), RUFLO_PLUGIN_SKIP_PATH_CLI: '1', IMPORT_FORMAT: 'json' });+ assert.ok(imp.calls.some((l) => l.startsWith('npx @claude-flow/cli@latest memory store')), imp.calls.join(' | '));+ assert.deepEqual(imp.calls.filter((l) => l.startsWith('ruflo ')), []);+ }));++ test('published layout: a built @claude-flow/cli next to the plugin wins over PATH', () => withFixture(({ tmp, run, log, path, rufloBin, npxBin }) => {+ const cli = join(tmp, 'published', 'node_modules', '@claude-flow', 'cli');+ const plugin = join(cli, 'plugins', 'ruflo-adr');+ cpSync(PLUGIN_ROOT, plugin, { recursive: true });+ write(join(cli, 'package.json'), JSON.stringify({ name: '@claude-flow/cli', version: '0.0.0-test', type: 'module' }));+ write(join(cli, 'dist', 'src', 'index.js'), 'export {};\n');+ write(join(cli, 'bin', 'cli.js'), `import { appendFileSync } from 'node:fs';\nappendFileSync(${JSON.stringify(log)}, 'shipping-cli ' + process.argv.slice(2).join(' ') + '\\n');\nconsole.log('[OK] done');\n`);+ const imp = run('import.mjs', { PATH: path(rufloBin, npxBin), IMPORT_FORMAT: 'json' }, plugin);+ assert.equal(imp.status, 0, imp.stderr);+ assert.ok(imp.calls.some((l) => l.startsWith('shipping-cli memory store --namespace=adr-patterns')), imp.calls.join(' | '));+ assert.deepEqual(imp.calls.filter((l) => !l.startsWith('shipping-cli ')), []);+ }));+}diff --git a/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs b/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjsindex dfc1b91eb5..0a58c80386 100644--- a/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs+++ b/plugins/ruflo-adr/scripts/__tests__/verify-read-safety-3147.test.mjs@@ -71,6 +71,10 @@ console.log(JSON.stringify(rows.slice(0, limit)));VERIFY_FORMAT: format,FAKE_MODE: mode,FAKE_CALLS: calls,+ // #3558: pin the npx shim β a built checkout or an installed ruflo on+ // PATH would otherwise be preferred over it (lib/ruflo-cli.mjs).+ RUFLO_PLUGIN_SKIP_LOCAL_CLI: '1',+ RUFLO_PLUGIN_SKIP_PATH_CLI: '1',...extraEnv,},encoding: 'utf8',diff --git a/plugins/ruflo-adr/scripts/import.mjs b/plugins/ruflo-adr/scripts/import.mjsindex 2b64e40edd..dbe6382a3f 100755--- a/plugins/ruflo-adr/scripts/import.mjs+++ b/plugins/ruflo-adr/scripts/import.mjs@@ -21,7 +21,6 @@// is hundreds of MCP round-trips. spawnSync over the CLI is materially faster// and avoids shell-quoting pitfalls in the ADR titles.-import { spawnSync } from 'node:child_process';import { existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { findAdrs, parseAdr } from './lib/parse-adrs.mjs';@@ -33,6 +32,7 @@ import {memoryStoreArgs,uniqueEdges,} from './lib/index-records.mjs';+import { spawnCliSync } from './lib/ruflo-cli.mjs';// #2781 (Jordi-Izquierdo-DDS): CLI_CORE=1 previously routed writes through// `@claude-flow/cli-core@alpha`, whose JsonMemoryBackend lives in a different@@ -91,7 +91,8 @@ function memoryStore(namespace, key, value) {// #2660: pass --upsert explicitly. The importer owns stable logical keys,// so re-running it must refresh changed ADRs and relationships in place.// Do not depend on a CLI parser default for this data-integrity contract.- const r = spawnSync('npx', memoryStoreArgs(namespace, key, value),+ // #3558: an installed ruflo CLI is preferred over npx (lib/ruflo-cli.mjs).+ const r = spawnCliSync(memoryStoreArgs(namespace, key, value),{ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: DB_ROOT });if (r.status !== 0) {return 'error: ' + (r.error?.message || r.stderr || r.stdout || `exit status ${r.status}`).slice(0, 100);diff --git a/plugins/ruflo-adr/scripts/lib/ruflo-cli.mjs b/plugins/ruflo-adr/scripts/lib/ruflo-cli.mjsnew file mode 100644index 0000000000..8a9c8a1ff4--- /dev/null+++ b/plugins/ruflo-adr/scripts/lib/ruflo-cli.mjs@@ -0,0 +1,133 @@+// ruflo-cli.mjs β which ruflo CLI adr-index / adr-reindex / adr-verify run (#3558).+//+// Every memory call used to be `npx @claude-flow/cli@latest β¦`, even on a+// machine where ruflo is installed. A plugin installed from the+// Claude Code marketplace is copied to+// ~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/ with no CLI next+// to it, so each call β one `memory store` per ADR and per edge β+// - resolved `latest` through the npm registry (a round trip per call;+// offline it fails and the record is lost);+// - could run a DIFFERENT @claude-flow/cli than the one the user installed+// or pinned: another memory backend / schema than the `ruflo memory+// search` that must find these records (#2781, #3306), including a+// release published minutes earlier.+//+// Resolution order, first hit wins (ruflo-metaharness/_invoke.mjs+// resolveRufloCli() from #3366, plus ruflo-core's PATH preference):+// 1. CLI_CORE=1 is ignored by this plugin (#2781), so there is no+// cli-core step: writer and reader must stay on the same store.+// 2. a built @claude-flow/cli that ships this plugin (<cli>/plugins/<plugin>;+// only ruflo-metaharness is published there today) or a repo checkout+// (<repo>/v3/@claude-flow/cli), with #3366's guards: package.json named+// @claude-flow/cli AND bin/cli.js AND dist/src/index.js.+// 3. a `ruflo`, then `claude-flow`, executable on PATH (fs-only probe).+// 4. null β the unchanged `npx @claude-flow/cli@latest` fallback.+//+// TEST SEAMS (same style as ruflo-metaharness's RUFLO_METAHARNESS_SKIP_LOCAL),+// so a test that stubs npx cannot pick up a developer's built checkout or+// installed ruflo instead:+// - RUFLO_PLUGIN_SKIP_LOCAL_CLI=1 disables step 2+// - RUFLO_PLUGIN_SKIP_PATH_CLI=1 disables step 3++import { spawnSync } from 'node:child_process';+import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { basename, delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { CLI_PKG } from './index-records.mjs';++const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');++/** Case-insensitive env lookup β Windows env keys are not case-stable (`Path`). */+function envValue(env, name) {+ const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());+ return key ? env[key] : undefined;+}++/** bin/cli.js of a built @claude-flow/cli at `dir`, else null (#3366 guards). */+function builtCliBin(dir) {+ try {+ const bin = join(dir, 'bin', 'cli.js');+ const pj = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));+ if (pj.name === '@claude-flow/cli' && existsSync(bin) && existsSync(join(dir, 'dist', 'src', 'index.js'))) return bin;+ } catch { /* not this layout */ }+ return null;+}++/**+ * npm's Windows shim (`<prefix>/ruflo.cmd`, or `node_modules/.bin/ruflo.cmd`)+ * cannot be spawned without a shell (CVE-2024-27980), so map it to the entry+ * it wraps: the package's own `bin` field, which must resolve inside the+ * package β ruflo-core's resolveNpmShim(). null when it is not such a shim.+ */+function npmShimEntry(shim, name) {+ try {+ const shimDir = dirname(shim);+ const pkgDir = basename(shimDir).toLowerCase() === '.bin'+ ? join(shimDir, '..', name)+ : join(shimDir, 'node_modules', name);+ const pj = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8'));+ const declared = typeof pj.bin === 'string' ? pj.bin : pj.bin?.[name];+ if (typeof declared !== 'string') return null;+ const entry = realpathSync(join(pkgDir, declared));+ const rel = relative(realpathSync(pkgDir), entry);+ if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel) || !statSync(entry).isFile()) return null;+ return entry;+ } catch { return null; }+}++/**+ * `ruflo`, then `claude-flow`, on PATH β `{ command, args, shell, source }`,+ * else null. fs-only like ruflo-core's resolveCommandPath(): no `which` /+ * `where` shell per call. Relative PATH entries (including the empty one) are+ * skipped so a `ruflo` file inside the project being worked on is never run.+ * On win32 only an npm shim that maps to its JS entry counts; anything else+ * is skipped rather than run through cmd.exe. `env` / `platform` are+ * parameters so the win32 branch is testable on POSIX.+ */+export function findRufloOnPath(env = process.env, platform = process.platform) {+ const dirs = (envValue(env, 'PATH') || '')+ .split(platform === 'win32' ? ';' : delimiter)+ .filter((d) => isAbsolute(d));+ for (const name of ['ruflo', 'claude-flow']) {+ for (const dir of dirs) {+ if (platform === 'win32') {+ const shim = join(dir, `${name}.cmd`);+ const entry = existsSync(shim) ? npmShimEntry(shim, name) : null;+ if (entry) return { command: process.execPath, args: [entry], shell: false, source: 'path' };+ continue;+ }+ const file = join(dir, name);+ try {+ accessSync(file, constants.X_OK);+ if (statSync(file).isFile()) return { command: file, args: [], shell: false, source: 'path' };+ } catch { /* keep searching */ }+ }+ }+ return null;+}++let RUFLO_CLI;+/** `{ command, args, shell, source }` for an installed ruflo CLI, or null (β npx). Memoized. */+export function resolveRufloCli() {+ if (RUFLO_CLI !== undefined) return RUFLO_CLI;+ const candidates = process.env.RUFLO_PLUGIN_SKIP_LOCAL_CLI === '1' ? [] : [+ join(PLUGIN_ROOT, '..', '..'), // published: <cli>/plugins/<plugin>+ join(PLUGIN_ROOT, '..', '..', 'v3', '@claude-flow', 'cli'), // repo checkout / marketplace clone+ ];+ for (const dir of candidates) {+ const bin = builtCliBin(dir);+ if (bin) return (RUFLO_CLI = { command: process.execPath, args: [bin], shell: false, source: 'local' });+ }+ RUFLO_CLI = process.env.RUFLO_PLUGIN_SKIP_PATH_CLI === '1' ? null : findRufloOnPath();+ return RUFLO_CLI;+}++/**+ * spawnSync `npx <npxArgs>` β unless npxArgs[0] is CLI_PKG and an installed+ * ruflo CLI resolves, which then runs with the rest of the argv and no shell.+ */+export function spawnCliSync(npxArgs, options = {}) {+ const cli = npxArgs[0] === CLI_PKG ? resolveRufloCli() : null;+ if (cli) return spawnSync(cli.command, [...cli.args, ...npxArgs.slice(1)], { ...options, shell: false });+ return spawnSync('npx', npxArgs, options);+}diff --git a/plugins/ruflo-adr/scripts/reindex.mjs b/plugins/ruflo-adr/scripts/reindex.mjsindex 8812f512b7..c871512a1c 100755--- a/plugins/ruflo-adr/scripts/reindex.mjs+++ b/plugins/ruflo-adr/scripts/reindex.mjs@@ -40,7 +40,6 @@// primitive. Re-run this script if that ever happens; the post-condition// check below will tell you.-import { spawnSync } from 'node:child_process';import { findAdrs, parseAdr } from './lib/parse-adrs.mjs';import {CLI_PKG,@@ -51,10 +50,12 @@ import {memoryStoreArgs,uniqueEdges,} from './lib/index-records.mjs';+import { spawnCliSync } from './lib/ruflo-cli.mjs';// #2781: unify on the default CLI so the reindex writer and the default// `ruflo memory search` reader hit the same store. See import.mjs for the-// full rationale.+// full rationale. #3558: every call below prefers an installed ruflo CLI over+// npx (lib/ruflo-cli.mjs), the same resolution import.mjs and verify.mjs use.if (process.env.CLI_CORE === '1') {console.warn('[ruflo-adr] warning: CLI_CORE=1 is ignored β writing to the default ' +@@ -69,7 +70,7 @@ const fmt = process.env.REINDEX_FORMAT || 'markdown';const NAMESPACES = ['adr-patterns', 'adr-edges'];function purgeNamespace(namespace) {- const r = spawnSync('npx', [+ const r = spawnCliSync([CLI_PKG, 'memory', 'purge',`--namespace=${namespace}`,'--force',@@ -83,8 +84,7 @@ function purgeNamespace(namespace) {function memoryStore(namespace, key, value) {// Same argv-encoding note as import.mjs: `--flag=value` avoids npm's// non-ASCII-leading-dash argv rejection on em-dash titles (#2474 Bug 1).- const r = spawnSync(- 'npx',+ const r = spawnCliSync(memoryStoreArgs(namespace, key, value),{ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT },);@@ -93,7 +93,7 @@ function memoryStore(namespace, key, value) {}function memoryListCount(namespace) {- const r = spawnSync('npx', [+ const r = spawnCliSync([CLI_PKG, 'memory', 'list','--namespace', namespace, '--format', 'json',], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', cwd: ROOT });diff --git a/plugins/ruflo-adr/scripts/verify.mjs b/plugins/ruflo-adr/scripts/verify.mjsindex 6ebed33845..28be739e13 100755--- a/plugins/ruflo-adr/scripts/verify.mjs+++ b/plugins/ruflo-adr/scripts/verify.mjs@@ -12,11 +12,13 @@// VERIFY_STRICT=1 node scripts/verify.mjs # exit 1 on ANY issue (default: only on cycles)// ADR_ROOT=/path/to/repo node scripts/verify.mjs # same root import.mjs was run with-import { spawnSync } from 'node:child_process';import { CLI_PKG, parseEdgeKey } from './lib/index-records.mjs';+import { spawnCliSync } from './lib/ruflo-cli.mjs';// Import/reindex always use the default CLI's SQLite store (#2781). Reading-// cli-core's separate JSON store would verify a different graph.+// cli-core's separate JSON store would verify a different graph. #3558: the+// read goes through the same installed-CLI resolution as the writers+// (lib/ruflo-cli.mjs), so verify reads the store import/reindex wrote.if (process.env.CLI_CORE === '1') {console.warn('[ruflo-adr] warning: CLI_CORE=1 is ignored for verification (#2781).');}@@ -34,7 +36,7 @@ const READ_TIMEOUT_MS = Math.min(120_000, Math.max(100,const MAX_BUFFER = 32 * 1024 * 1024;function memoryListJson(namespace) {- const r = spawnSync('npx', [+ const r = spawnCliSync([CLI_PKG, 'memory', 'list',`--namespace=${namespace}`, '--format=json', `--limit=${READ_LIMIT}`,], {diff --git a/plugins/ruflo-cost-tracker/scripts/_npx.mjs b/plugins/ruflo-cost-tracker/scripts/_npx.mjsindex 0dd1644f30..1a3dfd4ef0 100644--- a/plugins/ruflo-cost-tracker/scripts/_npx.mjs+++ b/plugins/ruflo-cost-tracker/scripts/_npx.mjs@@ -1,5 +1,6 @@import { spawnSync } from 'node:child_process';import { dirname, join } from 'node:path';+import { RUFLO_CLI_PKG, resolveRufloCli } from './_ruflo-cli.mjs';// Windows npm exposes npx through a .cmd shim, which cannot be spawned// directly by Node without a shell. Invoking npm's JS entry point preserves@@ -7,6 +8,13 @@ import { dirname, join } from 'node:path';export function spawnNpxSync(args, options = {}) {const npxArgs = args[0] === '-y' ? args : ['-y', ...args];const { shell: _ignoredShell, ...safeOptions } = options;+ // #3558: `@claude-flow/cli@latest` runs the ruflo CLI already installed on+ // this machine when there is one (_ruflo-cli.mjs); npx is the fallback.+ // CLI_CORE=1's `@claude-flow/cli-core@alpha` still goes through npx.+ const cli = npxArgs[1] === RUFLO_CLI_PKG ? resolveRufloCli() : null;+ if (cli) {+ return spawnSync(cli.command, [...cli.args, ...npxArgs.slice(2)], { ...safeOptions, shell: false });+ }if (process.platform === 'win32') {const npxCli = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js');return spawnSync(process.execPath, [npxCli, ...npxArgs], { ...safeOptions, shell: false });diff --git a/plugins/ruflo-cost-tracker/scripts/_ruflo-cli.mjs b/plugins/ruflo-cost-tracker/scripts/_ruflo-cli.mjsnew file mode 100644index 0000000000..656586c1c4--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/_ruflo-cli.mjs@@ -0,0 +1,122 @@+// _ruflo-cli.mjs β which ruflo CLI this plugin's scripts run (#3558).+//+// Every memory / hooks call used to be `npx -y @claude-flow/cli@latest β¦`,+// even on a machine where ruflo is installed. A plugin installed from the+// Claude Code marketplace is copied to+// ~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/ with no CLI next+// to it, so each call β the Stop hook's `memory store` runs on EVERY turn β+// - resolved `latest` through the npm registry (a round trip per call;+// offline it fails and the record is lost);+// - could run a DIFFERENT @claude-flow/cli than the one the user installed+// or pinned (another memory backend / schema than `ruflo memory β¦` reads,+// #3306), including a release published minutes earlier.+//+// Resolution order, first hit wins (ruflo-metaharness/_invoke.mjs+// resolveRufloCli() from #3366, plus ruflo-core's PATH preference):+// 1. CLI_CORE=1 is not handled here: callers already pass+// `@claude-flow/cli-core@alpha`, which keeps going through npx (ADR-100).+// 2. a built @claude-flow/cli that ships this plugin (<cli>/plugins/<plugin>;+// only ruflo-metaharness is published there today) or a repo checkout+// (<repo>/v3/@claude-flow/cli), with #3366's guards: package.json named+// @claude-flow/cli AND bin/cli.js AND dist/src/index.js.+// 3. a `ruflo`, then `claude-flow`, executable on PATH (fs-only probe).+// 4. null β the caller's unchanged `npx -y @claude-flow/cli@latest` fallback.+//+// TEST SEAMS (same style as ruflo-metaharness's RUFLO_METAHARNESS_SKIP_LOCAL),+// so a test that stubs npx cannot pick up a developer's built checkout or+// installed ruflo instead:+// - RUFLO_PLUGIN_SKIP_LOCAL_CLI=1 disables step 2+// - RUFLO_PLUGIN_SKIP_PATH_CLI=1 disables step 3++import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { basename, delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++export const RUFLO_CLI_PKG = '@claude-flow/cli@latest';++const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/** Case-insensitive env lookup β Windows env keys are not case-stable (`Path`). */+function envValue(env, name) {+ const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());+ return key ? env[key] : undefined;+}++/** bin/cli.js of a built @claude-flow/cli at `dir`, else null (#3366 guards). */+function builtCliBin(dir) {+ try {+ const bin = join(dir, 'bin', 'cli.js');+ const pj = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));+ if (pj.name === '@claude-flow/cli' && existsSync(bin) && existsSync(join(dir, 'dist', 'src', 'index.js'))) return bin;+ } catch { /* not this layout */ }+ return null;+}++/**+ * npm's Windows shim (`<prefix>/ruflo.cmd`, or `node_modules/.bin/ruflo.cmd`)+ * cannot be spawned without a shell (CVE-2024-27980), so map it to the entry+ * it wraps: the package's own `bin` field, which must resolve inside the+ * package β ruflo-core's resolveNpmShim(). null when it is not such a shim.+ */+function npmShimEntry(shim, name) {+ try {+ const shimDir = dirname(shim);+ const pkgDir = basename(shimDir).toLowerCase() === '.bin'+ ? join(shimDir, '..', name)+ : join(shimDir, 'node_modules', name);+ const pj = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8'));+ const declared = typeof pj.bin === 'string' ? pj.bin : pj.bin?.[name];+ if (typeof declared !== 'string') return null;+ const entry = realpathSync(join(pkgDir, declared));+ const rel = relative(realpathSync(pkgDir), entry);+ if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel) || !statSync(entry).isFile()) return null;+ return entry;+ } catch { return null; }+}++/**+ * `ruflo`, then `claude-flow`, on PATH β `{ command, args, shell, source }`,+ * else null. fs-only like ruflo-core's resolveCommandPath(): no `which` /+ * `where` shell per call. Relative PATH entries (including the empty one) are+ * skipped so a `ruflo` file inside the project being worked on is never run.+ * On win32 only an npm shim that maps to its JS entry counts; anything else+ * is skipped rather than run through cmd.exe. `env` / `platform` are+ * parameters so the win32 branch is testable on POSIX.+ */+export function findRufloOnPath(env = process.env, platform = process.platform) {+ const dirs = (envValue(env, 'PATH') || '')+ .split(platform === 'win32' ? ';' : delimiter)+ .filter((d) => isAbsolute(d));+ for (const name of ['ruflo', 'claude-flow']) {+ for (const dir of dirs) {+ if (platform === 'win32') {+ const shim = join(dir, `${name}.cmd`);+ const entry = existsSync(shim) ? npmShimEntry(shim, name) : null;+ if (entry) return { command: process.execPath, args: [entry], shell: false, source: 'path' };+ continue;+ }+ const file = join(dir, name);+ try {+ accessSync(file, constants.X_OK);+ if (statSync(file).isFile()) return { command: file, args: [], shell: false, source: 'path' };+ } catch { /* keep searching */ }+ }+ }+ return null;+}++let RUFLO_CLI;+/** `{ command, args, shell, source }` for an installed ruflo CLI, or null (β npx). Memoized. */+export function resolveRufloCli() {+ if (RUFLO_CLI !== undefined) return RUFLO_CLI;+ const candidates = process.env.RUFLO_PLUGIN_SKIP_LOCAL_CLI === '1' ? [] : [+ join(PLUGIN_ROOT, '..', '..'), // published: <cli>/plugins/<plugin>+ join(PLUGIN_ROOT, '..', '..', 'v3', '@claude-flow', 'cli'), // repo checkout / marketplace clone+ ];+ for (const dir of candidates) {+ const bin = builtCliBin(dir);+ if (bin) return (RUFLO_CLI = { command: process.execPath, args: [bin], shell: false, source: 'local' });+ }+ RUFLO_CLI = process.env.RUFLO_PLUGIN_SKIP_PATH_CLI === '1' ? null : findRufloOnPath();+ return RUFLO_CLI;+}diff --git a/plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs b/plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjsnew file mode 100644index 0000000000..9930a4dce7--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs@@ -0,0 +1,201 @@+#!/usr/bin/env node+/**+ * Regression guard for ruvnet/ruflo#3558 β cost-tracker must run the ruflo CLI+ * that is already installed, not `npx -y @claude-flow/cli@latest`.+ *+ * A plugin installed from the Claude Code marketplace lives in+ * ~/.claude/plugins/cache/<marketplace>/ruflo-cost-tracker/<version>/, with+ * no CLI next to it. Before #3558 every memory / hooks call from there went to+ * `npx @claude-flow/cli@latest` β for the Stop hook, a registry round trip on+ * every turn, running whatever `latest` was that day instead of the user's+ * installed ruflo.+ *+ * Hermetic: the plugin is copied into a temp plugin-cache layout, and PATH+ * holds only temp dirs with fake `ruflo` / `claude-flow` / `npx` scripts that+ * log their argv (plus a `node` link for the hook command). No network, no+ * real CLI, HOME points at a temp dir.+ *+ * Usage (from repo root):+ * node plugins/ruflo-cost-tracker/scripts/test-cli-resolution-3558.mjs+ *+ * Wired into .github/workflows/v3-ci.yml next to test-hooks.mjs. The+ * end-to-end cases use POSIX sh fakes and are skipped on win32; the win32+ * shim-mapping cases run everywhere.+ */++import { spawnSync } from 'node:child_process';+import {+ chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, dirname, join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++let passed = 0, failed = 0;+function assert(cond, label, detail = '') {+ if (cond) { passed++; console.log(`ok: ${label}`); return; }+ failed++;+ console.error(`FAIL: ${label}${detail ? `\n ${detail}` : ''}`);+}++const write = (file, body, mode) => {+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ if (mode) chmodSync(file, mode);+};++// realpath: macOS tmpdir() is /var/β¦ while resolved paths come back as /private/var/β¦+const TMP = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-cost-cli-resolution-')));+try {+ // ββ win32: npm's ruflo.cmd shim maps to its JS entry, never to cmd.exe ββ+ let findRufloOnPath = null;+ try {+ ({ findRufloOnPath } = await import(pathToFileURL(join(PLUGIN_ROOT, 'scripts', '_ruflo-cli.mjs')).href));+ } catch (e) {+ assert(false, 'scripts/_ruflo-cli.mjs exports findRufloOnPath()', e.message);+ }+ if (findRufloOnPath) {+ const prefix = join(TMP, 'win-prefix');+ write(join(prefix, 'ruflo.cmd'), '@ECHO off\r\n');+ write(join(prefix, 'node_modules', 'ruflo', 'package.json'), JSON.stringify({ name: 'ruflo', bin: { ruflo: 'bin/ruflo.js' } }));+ write(join(prefix, 'node_modules', 'ruflo', 'bin', 'ruflo.js'), '');+ const hit = findRufloOnPath({ Path: prefix }, 'win32');+ assert(hit?.command === process.execPath && hit?.args?.[0] === realpathSync(join(prefix, 'node_modules', 'ruflo', 'bin', 'ruflo.js')) && hit?.shell === false,+ 'win32: <prefix>/ruflo.cmd runs as `node <package bin>` with shell:false', JSON.stringify(hit));+ const escape = join(TMP, 'win-escape');+ write(join(escape, 'ruflo.cmd'), '@ECHO off\r\n');+ write(join(escape, 'node_modules', 'ruflo', 'package.json'), JSON.stringify({ name: 'ruflo', bin: { ruflo: '../../outside.js' } }));+ write(join(escape, 'outside.js'), '');+ assert(findRufloOnPath({ PATH: escape }, 'win32') === null, 'win32: a shim whose package bin points outside the package is refused');+ const bare = join(TMP, 'win-bare');+ write(join(bare, 'ruflo.cmd'), '@ECHO off\r\n');+ assert(findRufloOnPath({ PATH: bare }, 'win32') === null, 'win32: a ruflo.cmd that is not an npm package shim is skipped (no shell fallback)');+ }++ if (process.platform === 'win32') {+ console.log('\n# end-to-end cases SKIPPED on win32 (the fake CLIs are POSIX sh scripts)');+ } else {+ // ββ fixture βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ const HOME = join(TMP, 'home');+ const CACHE = join(HOME, '.claude', 'plugins', 'cache', 'ruflo', 'ruflo-cost-tracker', '0.0.0-test');+ cpSync(PLUGIN_ROOT, CACHE, { recursive: true });+ const LOG = join(TMP, 'calls.log');+ // Each fake logs `<name> <argvβ¦>` and answers like the CLI would: a JSON+ // array for `memory list`, an OK line otherwise.+ const fake = (dir, name) => write(join(dir, name),+ `#!/bin/sh\nprintf '%s %s\\n' "${name}" "$*" >> "${LOG}"\ncase "$*" in *"memory list"*) echo '[]' ;; *) echo '[OK] done' ;; esac\n`, 0o755);+ const NODE_BIN = join(TMP, 'node-bin');+ mkdirSync(NODE_BIN);+ symlinkSync(process.execPath, join(NODE_BIN, 'node'));+ const WITH_RUFLO = join(TMP, 'bin-ruflo');+ fake(WITH_RUFLO, 'ruflo');+ fake(WITH_RUFLO, 'claude-flow');+ const WITH_CLAUDE_FLOW = join(TMP, 'bin-claude-flow');+ fake(WITH_CLAUDE_FLOW, 'claude-flow');+ const NPX_ONLY = join(TMP, 'bin-npx');+ fake(NPX_ONLY, 'npx');+ const pathOf = (...dirs) => [...dirs, NODE_BIN].join(delimiter);++ // A Stop-hook-sized session for track.mjs to persist.+ const PROJECT = join(TMP, 'project');+ mkdirSync(PROJECT);+ const sessionDir = join(HOME, '.claude', 'projects', PROJECT.replace(/[/\\:]/g, '-'));+ write(join(sessionDir, 'sess-tbd.jsonl'), [+ { sessionId: 'sess-tbd', cwd: PROJECT, timestamp: '2026-09-28T16:20:00.000Z', type: 'user' },+ { sessionId: 'sess-tbd', cwd: PROJECT, timestamp: '2026-09-28T16:20:05.000Z', type: 'assistant',+ message: { model: 'claude-opus-5-5', usage: { input_tokens: 10, output_tokens: 20 } } },+ ].map((l) => JSON.stringify(l)).join('\n') + '\n');++ const baseEnv = { ...process.env, HOME, USERPROFILE: HOME, TRACK_CWD: PROJECT };+ for (const k of ['CLI_CORE', 'RUFLO_PLUGIN_SKIP_LOCAL_CLI', 'RUFLO_PLUGIN_SKIP_PATH_CLI', 'TRACK_DRY_RUN', 'TRACK_SESSION', 'NODE_OPTIONS']) delete baseEnv[k];+ const calls = () => (existsSync(LOG) ? readFileSync(LOG, 'utf-8').trim().split('\n').filter(Boolean) : []);+ const reset = () => rmSync(LOG, { force: true });++ // The Stop hook exactly as Claude Code runs it (hooks.json command, shell).+ const hookCmd = JSON.parse(readFileSync(join(CACHE, 'hooks', 'hooks.json'), 'utf-8')).hooks.Stop[0].hooks[0].command;+ const stopHook = (env, pluginRoot = CACHE) => spawnSync(hookCmd, {+ shell: true, cwd: PROJECT, encoding: 'utf-8', timeout: 30_000,+ input: JSON.stringify({ session_id: 'sess-tbd', hook_event_name: 'Stop', stop_hook_active: false }),+ env: { ...baseEnv, CLAUDE_PLUGIN_ROOT: pluginRoot, ...env },+ });+ const runScript = (script, args, env, scriptsDir = join(CACHE, 'scripts'), cwd = PROJECT) =>+ spawnSync(process.execPath, [join(scriptsDir, script), ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: { ...baseEnv, ...env } });++ const storeCall = 'memory store --namespace cost-tracking --key session-sess-tbd';++ // 1 β the bug: marketplace install + ruflo on PATH.+ reset();+ const hook = stopHook({ PATH: pathOf(WITH_RUFLO, NPX_ONLY) });+ assert(hook.status === 0, 'Stop hook exits 0', `status ${hook.status}: ${hook.stderr}`);+ let c = calls();+ assert(c.some((l) => l.startsWith(`ruflo ${storeCall}`)), 'plugin-cache install: Stop hook stores the session through the installed `ruflo`', c.join(' | ') || 'no CLI called');+ assert(!c.some((l) => l.startsWith('npx ')), 'plugin-cache install: Stop hook does not run npx', c.join(' | '));++ reset();+ runScript('outcome.mjs', ['format imports', 'haiku', 'success'], { PATH: pathOf(WITH_RUFLO, NPX_ONLY) });+ c = calls();+ assert(c.includes('ruflo hooks model-outcome -t format imports -m haiku -o success') && !c.some((l) => l.startsWith('npx ')),+ 'outcome.mjs: `hooks model-outcome` goes to the installed ruflo, not npx', c.join(' | '));++ reset();+ runScript('federation.mjs', [], { PATH: pathOf(WITH_RUFLO, NPX_ONLY), FED_FORMAT: 'json' });+ c = calls();+ assert(c.some((l) => l.startsWith('ruflo memory list --namespace federation-spend')) && !c.some((l) => l.startsWith('npx ')),+ 'federation.mjs (a module-level CLI_PKG caller): `memory list` goes to the installed ruflo', c.join(' | '));++ // 2 β `claude-flow` counts when there is no `ruflo`.+ reset();+ stopHook({ PATH: pathOf(WITH_CLAUDE_FLOW, NPX_ONLY) });+ c = calls();+ assert(c.some((l) => l.startsWith(`claude-flow ${storeCall}`)) && !c.some((l) => l.startsWith('npx ')),+ 'no `ruflo` but `claude-flow` on PATH β claude-flow is used', c.join(' | '));++ // 3 β contracts kept.+ reset();+ stopHook({ PATH: pathOf(NPX_ONLY) });+ c = calls();+ assert(c.some((l) => l.startsWith(`npx -y @claude-flow/cli@latest ${storeCall}`)),+ 'no installed CLI β still `npx -y @claude-flow/cli@latest` (unchanged fallback)', c.join(' | ') || 'no CLI called');++ reset();+ stopHook({ PATH: pathOf(WITH_RUFLO, NPX_ONLY), CLI_CORE: '1' });+ c = calls();+ assert(c.some((l) => l.startsWith(`npx -y @claude-flow/cli-core@alpha ${storeCall}`)) && !c.some((l) => l.startsWith('ruflo ')),+ 'CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha` (ADR-100)', c.join(' | '));++ reset();+ stopHook({ PATH: pathOf(WITH_RUFLO, NPX_ONLY), RUFLO_PLUGIN_SKIP_PATH_CLI: '1' });+ c = calls();+ assert(c.some((l) => l.startsWith('npx -y @claude-flow/cli@latest ')) && !c.some((l) => l.startsWith('ruflo ')),+ 'RUFLO_PLUGIN_SKIP_PATH_CLI=1 skips the PATH lookup (test seam)', c.join(' | '));++ // A `ruflo` in the project directory is never run via a relative PATH entry.+ reset();+ fake(PROJECT, 'ruflo');+ runScript('outcome.mjs', ['t', 'haiku', 'success'], { PATH: ['', '.', NPX_ONLY, NODE_BIN].join(delimiter) });+ c = calls();+ assert(!c.some((l) => l.startsWith('ruflo ')) && c.some((l) => l.startsWith('npx -y @claude-flow/cli@latest hooks model-outcome')),+ 'relative PATH entries (`.` / empty) are ignored', c.join(' | '));+ rmSync(join(PROJECT, 'ruflo'));++ // 4 β a built @claude-flow/cli that ships the plugin still wins over PATH.+ const CLI = join(TMP, 'published', 'node_modules', '@claude-flow', 'cli');+ const PUB_PLUGIN = join(CLI, 'plugins', 'ruflo-cost-tracker');+ cpSync(PLUGIN_ROOT, PUB_PLUGIN, { recursive: true });+ write(join(CLI, 'package.json'), JSON.stringify({ name: '@claude-flow/cli', version: '0.0.0-test', type: 'module' }));+ write(join(CLI, 'dist', 'src', 'index.js'), 'export {};\n');+ write(join(CLI, 'bin', 'cli.js'), `import { appendFileSync } from 'node:fs';\nappendFileSync(${JSON.stringify(LOG)}, 'shipping-cli ' + process.argv.slice(2).join(' ') + '\\n');\nconsole.log('[OK] done');\n`);+ reset();+ stopHook({ PATH: pathOf(WITH_RUFLO, NPX_ONLY) }, PUB_PLUGIN);+ c = calls();+ assert(c.some((l) => l.startsWith(`shipping-cli ${storeCall}`)) && c.every((l) => l.startsWith('shipping-cli ')),+ 'published layout: the @claude-flow/cli that ships the plugin wins over PATH', c.join(' | ') || 'no CLI called');+ }+} finally {+ rmSync(TMP, { recursive: true, force: true });+}++console.log(`\n${passed}/${passed + failed} passed`);+process.exit(failed === 0 ? 0 : 1);diff --git a/plugins/ruflo-metaharness/scripts/_invoke.mjs b/plugins/ruflo-metaharness/scripts/_invoke.mjsindex 738aff8139..62ae6f11a0 100644--- a/plugins/ruflo-metaharness/scripts/_invoke.mjs+++ b/plugins/ruflo-metaharness/scripts/_invoke.mjs@@ -28,7 +28,8 @@// library entries (gepa) β never throws on absence// - makeDegradedEmitter() the ADR-150 rule-#3 exit-0 degraded payload// - runRufloCli() `memory store|list|retrieve` through the ruflo CLI-// that ships this plugin (#3366) β replaces+// that ships this plugin (#3366), else an installed+// `ruflo` / `claude-flow` on PATH (#3558) β replaces// `npx @claude-flow/cli@latest` in 4 scripts//// WHAT DOES NOT LIVE HERE (the per-consumer parts):@@ -40,11 +41,16 @@// stays meaningful on machines with a warm cache / local install):// - RUFLO_METAHARNESS_CACHE_BASE overrides ~/.ruflo as the cache root// - RUFLO_METAHARNESS_SKIP_LOCAL=1 disables local node_modules resolution+// - RUFLO_PLUGIN_SKIP_LOCAL_CLI=1 resolveRufloCli() skips the shipping CLI /+// repo checkout (#3558; same name in+// ruflo-cost-tracker and ruflo-adr)+// - RUFLO_PLUGIN_SKIP_PATH_CLI=1 resolveRufloCli() skips `ruflo` /+// `claude-flow` on PATH (#3558)import { spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';+import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';import { homedir } from 'node:os';-import { dirname, join } from 'node:path';+import { basename, delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';const INSTALL_TIMEOUT_MS = 180_000; // npm install can be slow on cold cache@@ -303,12 +309,77 @@ export function makeDegradedEmitter(pkg, pinVersion) {// exists next to bin/cli.js β mcp-launch.cjs resolveLocalCliBin()'s guard// against an unbuilt checkout β AND its package.json is named// @claude-flow/cli, a check added here so an unrelated directory two levels up-// can never qualify. Unchanged:+// can never qualify.+// #3558: a Claude Code marketplace install copies the plugin to+// ~/.claude/plugins/cache/<marketplace>/ruflo-metaharness/<version>/, where+// neither candidate exists, so every memory call still went to npx @latest on+// a machine with ruflo installed. A `ruflo`, then `claude-flow`, found on+// PATH (ruflo-core ruflo-hook.cjs's order) is now tried before npx.+// Unchanged:// - CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha` (ADR-100);-// - no usable local CLI (e.g. a marketplace clone with no build) still falls-// back to `npx @claude-flow/cli@latest`.+// - no usable local CLI and no ruflo on PATH still falls back to+// `npx @claude-flow/cli@latest`.const PLUGIN_SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));+/** Case-insensitive env lookup β Windows env keys are not case-stable (`Path`). */+function envValue(env, name) {+ const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());+ return key ? env[key] : undefined;+}++/**+ * npm's Windows shim (`<prefix>/ruflo.cmd`, or `node_modules/.bin/ruflo.cmd`)+ * cannot be spawned without a shell (CVE-2024-27980), so map it to the entry+ * it wraps: the package's own `bin` field, which must resolve inside the+ * package β ruflo-core's resolveNpmShim(). null when it is not such a shim.+ */+function npmShimEntry(shim, name) {+ try {+ const shimDir = dirname(shim);+ const pkgDir = basename(shimDir).toLowerCase() === '.bin'+ ? join(shimDir, '..', name)+ : join(shimDir, 'node_modules', name);+ const pj = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8'));+ const declared = typeof pj.bin === 'string' ? pj.bin : pj.bin?.[name];+ if (typeof declared !== 'string') return null;+ const entry = realpathSync(join(pkgDir, declared));+ const rel = relative(realpathSync(pkgDir), entry);+ if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel) || !statSync(entry).isFile()) return null;+ return entry;+ } catch { return null; }+}++/**+ * `ruflo`, then `claude-flow`, on PATH β `{ command, args, shell, source }`,+ * else null. fs-only like ruflo-core's resolveCommandPath(): no `which` /+ * `where` shell per call. Relative PATH entries (including the empty one) are+ * skipped so a `ruflo` file inside the project being worked on is never run.+ * On win32 only an npm shim that maps to its JS entry counts; anything else+ * is skipped rather than run through cmd.exe. `env` / `platform` are+ * parameters so the win32 branch is testable on POSIX.+ */+export function findRufloOnPath(env = process.env, platform = process.platform) {+ const dirs = (envValue(env, 'PATH') || '')+ .split(platform === 'win32' ? ';' : delimiter)+ .filter((d) => isAbsolute(d));+ for (const name of ['ruflo', 'claude-flow']) {+ for (const dir of dirs) {+ if (platform === 'win32') {+ const shim = join(dir, `${name}.cmd`);+ const entry = existsSync(shim) ? npmShimEntry(shim, name) : null;+ if (entry) return { command: process.execPath, args: [entry], shell: false, source: 'path' };+ continue;+ }+ const file = join(dir, name);+ try {+ accessSync(file, constants.X_OK);+ if (statSync(file).isFile()) return { command: file, args: [], shell: false, source: 'path' };+ } catch { /* keep searching */ }+ }+ }+ return null;+}+let RUFLO_CLI = null;/** `{ command, args, shell, source }` for invoking the ruflo CLI. Memoized. */export function resolveRufloCli() {@@ -316,7 +387,7 @@ export function resolveRufloCli() {if (process.env.CLI_CORE === '1') {return (RUFLO_CLI = { command: 'npx', args: ['@claude-flow/cli-core@alpha'], shell: process.platform === 'win32', source: 'npx-cli-core' });}- const candidates = [+ const candidates = process.env.RUFLO_PLUGIN_SKIP_LOCAL_CLI === '1' ? [] : [join(PLUGIN_SCRIPTS_DIR, '..', '..', '..'), // published: <cli>/plugins/ruflo-metaharness/scriptsjoin(PLUGIN_SCRIPTS_DIR, '..', '..', '..', 'v3', '@claude-flow', 'cli'), // repo checkout / marketplace clone];@@ -329,6 +400,8 @@ export function resolveRufloCli() {}} catch { /* not this layout β try the next */ }}+ const onPath = process.env.RUFLO_PLUGIN_SKIP_PATH_CLI === '1' ? null : findRufloOnPath();+ if (onPath) return (RUFLO_CLI = onPath);return (RUFLO_CLI = { command: 'npx', args: ['@claude-flow/cli@latest'], shell: process.platform === 'win32', source: 'npx' });}diff --git a/plugins/ruflo-metaharness/scripts/test-cli-resolution-3558.mjs b/plugins/ruflo-metaharness/scripts/test-cli-resolution-3558.mjsnew file mode 100644index 0000000000..c26f7cc8e6--- /dev/null+++ b/plugins/ruflo-metaharness/scripts/test-cli-resolution-3558.mjs@@ -0,0 +1,141 @@+#!/usr/bin/env node+// test-cli-resolution-3558.mjs β regression test for #3558: in a Claude Code+// marketplace install, metaharness memory calls must use the ruflo CLI that+// is already installed on PATH, not `npx @claude-flow/cli@latest`.+//+// #3366 taught resolveRufloCli() (_invoke.mjs) two local layouts: the+// @claude-flow/cli that ships the plugin, and a repo checkout. A marketplace+// install is neither β the plugin is copied to+// ~/.claude/plugins/cache/<marketplace>/ruflo-metaharness/<version>/ β so it+// still fell through to npx @latest on a machine with ruflo installed.+//+// Hermetic: the plugin is copied into a temp plugin-cache layout; PATH holds+// only temp dirs with fake `ruflo` / `claude-flow` / `npx` scripts that log+// their argv. No network, no real CLI. The end-to-end cases use POSIX sh+// fakes and are skipped on win32; the win32 shim-mapping case runs everywhere.+//+// USAGE+// node --test plugins/ruflo-metaharness/scripts/test-cli-resolution-3558.mjs+import { test, before, after } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { delimiter, dirname, join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const posixOnly = { skip: process.platform === 'win32' ? 'fake CLIs are POSIX sh scripts' : false };++const write = (file, body, mode) => {+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, body);+ if (mode) chmodSync(file, mode);+};++let TMP, CACHE, LOG, WITH_RUFLO, WITH_CLAUDE_FLOW, NPX_ONLY, PROJECT, baseEnv;+before(() => {+ // realpath: macOS tmpdir() is /var/β¦ while resolved paths come back as /private/var/β¦+ TMP = realpathSync(mkdtempSync(join(tmpdir(), 'metaharness-cli-resolution-')));+ const home = join(TMP, 'home');+ CACHE = join(home, '.claude', 'plugins', 'cache', 'ruflo', 'ruflo-metaharness', '0.0.0-test');+ cpSync(PLUGIN_ROOT, CACHE, { recursive: true });+ LOG = join(TMP, 'calls.log');+ const fake = (dir, name) => write(join(dir, name),+ `#!/bin/sh\nprintf '%s %s\\n' "${name}" "$*" >> "${LOG}"\ncase "$*" in *"memory list"*) echo '[]' ;; *) echo '[OK] done' ;; esac\n`, 0o755);+ WITH_RUFLO = join(TMP, 'bin-ruflo');+ fake(WITH_RUFLO, 'ruflo');+ fake(WITH_RUFLO, 'claude-flow');+ WITH_CLAUDE_FLOW = join(TMP, 'bin-claude-flow');+ fake(WITH_CLAUDE_FLOW, 'claude-flow');+ NPX_ONLY = join(TMP, 'bin-npx');+ fake(NPX_ONLY, 'npx');+ PROJECT = join(TMP, 'project');+ mkdirSync(PROJECT);+ baseEnv = { ...process.env, HOME: home, USERPROFILE: home, RUFLO_METAHARNESS_CACHE_BASE: join(TMP, 'empty-cache-base') };+ for (const k of ['CLI_CORE', 'RUFLO_PLUGIN_SKIP_LOCAL_CLI', 'RUFLO_PLUGIN_SKIP_PATH_CLI', 'NODE_OPTIONS']) delete baseEnv[k];+});+after(() => rmSync(TMP, { recursive: true, force: true }));++const calls = () => (existsSync(LOG) ? readFileSync(LOG, 'utf-8').trim().split('\n').filter(Boolean) : []);+/** resolveRufloCli() as seen from `scriptsDir`, in a fresh process. */+function resolved(env, scriptsDir = join(CACHE, 'scripts')) {+ const src = `import { resolveRufloCli } from ${JSON.stringify(pathToFileURL(join(scriptsDir, '_invoke.mjs')).href)};\nconsole.log(JSON.stringify(resolveRufloCli()));`;+ const r = spawnSync(process.execPath, ['--input-type=module', '-e', src], { cwd: PROJECT, encoding: 'utf-8', env: { ...baseEnv, ...env } });+ assert.equal(r.status, 0, r.stderr);+ return JSON.parse(r.stdout);+}+function auditList(env, scriptsDir = join(CACHE, 'scripts')) {+ rmSync(LOG, { force: true });+ const r = spawnSync(process.execPath, [join(scriptsDir, 'audit-list.mjs'), '--format', 'json'], { cwd: PROJECT, encoding: 'utf-8', timeout: 30_000, env: { ...baseEnv, ...env } });+ assert.equal(r.status, 0, r.stderr);+ return calls();+}+const pathOf = (...dirs) => dirs.join(delimiter);++test('win32: npm\'s ruflo.cmd shim maps to `node <package bin>`, never cmd.exe', async () => {+ const { findRufloOnPath } = await import(pathToFileURL(join(PLUGIN_ROOT, 'scripts', '_invoke.mjs')).href);+ const prefix = join(TMP, 'win-prefix');+ write(join(prefix, 'ruflo.cmd'), '@ECHO off\r\n');+ write(join(prefix, 'node_modules', 'ruflo', 'package.json'), JSON.stringify({ name: 'ruflo', bin: { ruflo: 'bin/ruflo.js' } }));+ write(join(prefix, 'node_modules', 'ruflo', 'bin', 'ruflo.js'), '');+ assert.deepEqual(findRufloOnPath({ Path: prefix }, 'win32'),+ { command: process.execPath, args: [realpathSync(join(prefix, 'node_modules', 'ruflo', 'bin', 'ruflo.js'))], shell: false, source: 'path' });+ const bare = join(TMP, 'win-bare');+ write(join(bare, 'ruflo.cmd'), '@ECHO off\r\n');+ assert.equal(findRufloOnPath({ PATH: bare }, 'win32'), null, 'a ruflo.cmd that is not an npm package shim is skipped, not run through cmd.exe');+});++test('plugin-cache install: the installed `ruflo` on PATH serves memory calls, not npx', posixOnly, () => {+ const env = { PATH: pathOf(WITH_RUFLO, NPX_ONLY) };+ assert.deepEqual(resolved(env), { command: join(WITH_RUFLO, 'ruflo'), args: [], shell: false, source: 'path' });+ const c = auditList(env);+ assert.ok(c.some((l) => l.startsWith('ruflo memory list --namespace metaharness-audit')), c.join(' | ') || 'no CLI called');+ assert.deepEqual(c.filter((l) => l.startsWith('npx ')), []);+});++test('no `ruflo` but `claude-flow` on PATH β claude-flow', posixOnly, () => {+ const c = auditList({ PATH: pathOf(WITH_CLAUDE_FLOW, NPX_ONLY) });+ assert.ok(c.some((l) => l.startsWith('claude-flow memory list')), c.join(' | '));+ assert.deepEqual(c.filter((l) => l.startsWith('npx ')), []);+});++test('no installed CLI β still `npx @claude-flow/cli@latest` (unchanged fallback)', posixOnly, () => {+ const env = { PATH: pathOf(NPX_ONLY) };+ assert.equal(resolved(env).source, 'npx');+ const c = auditList(env);+ assert.ok(c.some((l) => l.startsWith('npx @claude-flow/cli@latest memory list')), c.join(' | '));+});++test('CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha` (ADR-100)', posixOnly, () => {+ const c = auditList({ PATH: pathOf(WITH_RUFLO, NPX_ONLY), CLI_CORE: '1' });+ assert.ok(c.some((l) => l.startsWith('npx @claude-flow/cli-core@alpha memory list')), c.join(' | '));+ assert.deepEqual(c.filter((l) => l.startsWith('ruflo ')), []);+});++test('RUFLO_PLUGIN_SKIP_PATH_CLI=1 skips the PATH lookup (test seam)', posixOnly, () => {+ assert.equal(resolved({ PATH: pathOf(WITH_RUFLO, NPX_ONLY), RUFLO_PLUGIN_SKIP_PATH_CLI: '1' }).source, 'npx');+});++test('a `ruflo` in the working directory is never run via a relative PATH entry', posixOnly, () => {+ write(join(PROJECT, 'ruflo'), '#!/bin/sh\nexit 0\n', 0o755);+ try {+ assert.equal(resolved({ PATH: ['', '.', NPX_ONLY].join(delimiter) }).source, 'npx');+ } finally {+ rmSync(join(PROJECT, 'ruflo'));+ }+});++test('published layout: the @claude-flow/cli that ships the plugin still wins over PATH (#3366)', posixOnly, () => {+ const cli = join(TMP, 'published', 'node_modules', '@claude-flow', 'cli');+ const scripts = join(cli, 'plugins', 'ruflo-metaharness', 'scripts');+ cpSync(join(PLUGIN_ROOT, 'scripts'), scripts, { recursive: true });+ write(join(cli, 'package.json'), JSON.stringify({ name: '@claude-flow/cli', version: '0.0.0-test', type: 'module' }));+ write(join(cli, 'dist', 'src', 'index.js'), 'export {};\n');+ write(join(cli, 'bin', 'cli.js'), `import { appendFileSync } from 'node:fs';\nappendFileSync(${JSON.stringify(LOG)}, 'shipping-cli ' + process.argv.slice(2).join(' ') + '\\n');\nconsole.log('[]');\n`);+ const env = { PATH: pathOf(WITH_RUFLO, NPX_ONLY) };+ assert.equal(resolved(env, scripts).source, 'local');+ const c = auditList(env, scripts);+ assert.ok(c.some((l) => l.startsWith('shipping-cli memory list')), c.join(' | '));+ assert.deepEqual(c.filter((l) => !l.startsWith('shipping-cli ')), []);+});diff --git a/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs b/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjsindex f7f9222e17..017dd6167b 100755--- a/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs+++ b/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs@@ -156,6 +156,11 @@ else process.exit(2);const baseEnv = { ...process.env, PATH: `${TRAP}:${process.env.PATH}`, RUFLO_METAHARNESS_CACHE_BASE: join(TMP, 'empty-cache-base') };delete baseEnv.RUFLO_METAHARNESS_SKIP_LOCAL;delete baseEnv.CLI_CORE;+ delete baseEnv.RUFLO_PLUGIN_SKIP_LOCAL_CLI;+ // #3558: Phase 4 asserts the npx fallback; an installed `ruflo` on the+ // developer's PATH would now be preferred over it. PATH resolution has its+ // own test (test-cli-resolution-3558.mjs).+ baseEnv.RUFLO_PLUGIN_SKIP_PATH_CLI = '1';const trapped = () => (existsSync(TRAP_LOG) ? readFileSync(TRAP_LOG, 'utf-8').trim() : '');const resetTrap = () => rmSync(TRAP_LOG, { force: true });const run = (script, args, env = baseEnv, scriptsDir = PLUGIN_SCRIPTS, cwd = PROJECT) => {