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(metaharness): use the @metaharness/* and ruflo CLI already installed instead of npm-installing at tool-call time (#3366)

Mr. Mak0a2df2bfd252
diff --git a/.github/workflows/metaharness-pin-drift.yml b/.github/workflows/metaharness-pin-drift.yml
index 743a15a707..fcf17e7df4 100644
--- a/.github/workflows/metaharness-pin-drift.yml
+++ b/.github/workflows/metaharness-pin-drift.yml
@@ -14,6 +14,10 @@ on:
paths:
- 'v3/@claude-flow/cli/package.json'
- 'v3/@claude-flow/cli/src/services/distill-oracle.ts'
+ # plugin helper pins β€” what the metaharness_* MCP tools actually resolve
+ - 'plugins/ruflo-metaharness/scripts/_harness.mjs'
+ - 'plugins/ruflo-metaharness/scripts/_darwin.mjs'
+ - 'plugins/ruflo-metaharness/scripts/_redblue.mjs'
- 'scripts/check-metaharness-pins.mjs'
permissions:
@@ -65,7 +69,8 @@ jobs:
echo "The metaharness pin-drift watcher found a pin whose range no longer"
echo "admits the current npm release. Bump the range in"
echo "\`v3/@claude-flow/cli/package.json\` (and \`MH_DARWIN_PIN\` in"
- echo "\`distill-oracle.ts\` if darwin moved), then re-run the guard."
+ echo "\`distill-oracle.ts\` if darwin moved, and the \`*_PIN_VERSION\`"
+ echo "constants in \`plugins/ruflo-metaharness/scripts/\`), then re-run the guard."
echo ""
echo '```json'
cat /tmp/pins.json
diff --git a/plugins/ruflo-metaharness/agents/metaharness-architect.md b/plugins/ruflo-metaharness/agents/metaharness-architect.md
index 4a896f3dc3..60637ce311 100644
--- a/plugins/ruflo-metaharness/agents/metaharness-architect.md
+++ b/plugins/ruflo-metaharness/agents/metaharness-architect.md
@@ -38,7 +38,7 @@ needs its own ADR.
## Tools (subprocess-only, no library imports)
-- All skills shell out to the pinned `metaharness` / `harness` binaries (`metaharness@~0.3.0`, local install or one-time versioned cache β€” never `@latest`) via the `_harness.mjs` shared helper.
+- All skills shell out to the pinned `metaharness` / `harness` binaries (`metaharness@~0.4.1`, local install or one-time versioned cache β€” never `@latest`) via the `_harness.mjs` shared helper.
- 60s hard timeout per subprocess.
- Output captured + parsed; `--json` flag forced unless the script opts out.
- No `@metaharness/*` import statement appears outside the optional-router path in `v3/@claude-flow/cli/src/ruvector/neural-router.ts`.
diff --git a/plugins/ruflo-metaharness/commands/ruflo-metaharness.md b/plugins/ruflo-metaharness/commands/ruflo-metaharness.md
index 67d21da4b3..2e83e989b4 100644
--- a/plugins/ruflo-metaharness/commands/ruflo-metaharness.md
+++ b/plugins/ruflo-metaharness/commands/ruflo-metaharness.md
@@ -4,7 +4,7 @@ description: MetaHarness integration β€” score, genome, mint, mcp-scan, threat-m
---
MetaHarness integration commands. All shell out to the PINNED
-`metaharness`/`harness` binaries (`metaharness@~0.3.0` β€” resolved from a local
+`metaharness`/`harness` binaries (`metaharness@~0.4.1` β€” resolved from a local
install or a one-time `~/.ruflo/metaharness-cache-<pin>` install, never
`@latest`) via the `_harness.mjs` shared helper; no library imports on
ruflo's boot path.
diff --git a/plugins/ruflo-metaharness/scripts/_darwin.mjs b/plugins/ruflo-metaharness/scripts/_darwin.mjs
index 556837b7ee..fab00f681c 100644
--- a/plugins/ruflo-metaharness/scripts/_darwin.mjs
+++ b/plugins/ruflo-metaharness/scripts/_darwin.mjs
@@ -2,16 +2,17 @@
//
// Mirrors `_harness.mjs` for the umbrella `metaharness` / `harness` binaries,
// but targets the separate darwin binary (`metaharness-darwin`) which is
-// published as its own npm package (`@metaharness/darwin@~0.8.0`).
+// published as its own npm package (`@metaharness/darwin@~0.10.2`).
//
// Shared plumbing (degraded classification, --json injection, trailing-JSON
// parse, degraded emitter) lives in `_invoke.mjs`. What stays here is the
// genuinely-darwin part: the ASYNC STREAMING variant (`runDarwinAsync`) that
// long `evolve` runs need for per-generation progress visibility.
//
-// Three subcommands surfaced (matches darwin 0.8.x β€” same verbs as 0.3.x,
-// with GEPA-engine evolve flags added upstream: --selection modes,
-// --crossover, --epistasis, --curriculum, --mutator ruvllm, --sandbox):
+// Three subcommands surfaced (matches darwin 0.8.x-0.10.x β€” same verbs as
+// 0.3.x, with GEPA-engine evolve flags added upstream: --selection modes,
+// --crossover, --epistasis, --curriculum, --mutator ruvllm, --sandbox;
+// 0.10.x only ADDS `evolve-numeric`, which this helper does not surface):
// - `metaharness-darwin evolve <repo> [...]` β€” harness self-improvement
// - `metaharness-darwin bench <create|verify> ...` β€” bench-suite lifecycle
// - `metaharness-darwin security bench [...]` β€” Darwin Shield (upstream ADR-155)
@@ -31,23 +32,43 @@
// matched to their --generations Γ— --children Γ— sandbox cost; the 60s
// default is for `bench verify` and `security bench --population 2 --cycles 1`
// smoke shapes only.
+//
+// RESOLUTION (#3366 β€” was `npx -y -p @metaharness/darwin@<pin>` on every call)
+// Same order as _harness.mjs: (a) an installed @metaharness/darwin that
+// satisfies the pin (the @claude-flow/cli optionalDependency β€” free), then
+// (b) the one-time versioned `~/.ruflo/darwin-cache-<pin>` install that gepa
+// already shares, then `process.execPath <abs bin>` with shell:false. The
+// npx path had npm resolve the range on every evolve / bench /
+// security-bench call (registry or npx cache state), ignored the copy ruflo
+// ships, and could run a different darwin than the gepa import in the same
+// plugin. (a) searches ruflo's own tree only β€” see findLocalPackageDir's
+// `fromCwd` in _invoke.mjs.
import { spawnSync, spawn } from 'node:child_process';
import {
classifyDegraded,
+ ensureCachedInstall,
+ findLocalPackageDir,
importOptionalLibrary,
injectJson,
makeDegradedEmitter,
+ packageBinRelPath,
parseTrailingJson,
+ resolvePackageBin,
} from './_invoke.mjs';
const DEFAULT_TIMEOUT_MS = 60_000;
-// Pinned semver range. Bump in lock-step with optionalDependencies in
-// @claude-flow/cli/package.json + ruflo/package.json. The `~` allows
-// patch upgrades without re-pinning.
+// Pinned semver range. The `~` allows patch upgrades without re-pinning.
+// Must cover the `@metaharness/darwin` optionalDependency range in
+// v3/@claude-flow/cli/package.json (`~0.10.2`). It sat at ~0.8.0 while that
+// range moved to ~0.9.0 (#2958) and ~0.10.2 (#3262), because the pin-drift
+// guard only compared MH_DARWIN_PIN (distill-oracle.ts). This range picks
+// the darwin version the evolve / bench / security-bench tools run and the
+// gepa cache fallback installs; scripts/check-metaharness-pins.mjs now fails
+// when it no longer covers the declared range.
const DARWIN_PKG = '@metaharness/darwin';
-const DARWIN_PIN_VERSION = '~0.8.0';
+const DARWIN_PIN_VERSION = '~0.10.2';
const DARWIN_PIN = `${DARWIN_PKG}@${DARWIN_PIN_VERSION}`;
const REASON_PREFIX = 'metaharness-darwin';
@@ -68,22 +89,71 @@ function buildArgv(args, wantJson) {
// (This last-block parse is now the family-wide shared implementation.)
const maybeParseJson = parseTrailingJson;
+const DARWIN_BIN = 'metaharness-darwin';
+
+/**
+ * Absolute path of the `metaharness-darwin` bin (see RESOLUTION above).
+ * Memoized per process, like _harness.mjs resolveMetaharnessBins().
+ */
+let RESOLVED = null;
+function resolveDarwinBin() {
+ if (RESOLVED) return RESOLVED;
+ // fromCwd:false β€” this lookup ends in a spawn of the bin with argv that
+ // comes from MCP input, so it only searches the ruflo install that owns
+ // this plugin, never the tool's cwd or its ancestors (see _invoke.mjs).
+ const localDir = findLocalPackageDir(DARWIN_PKG, DARWIN_PIN_VERSION, { fromCwd: false });
+ const localBin = localDir ? resolvePackageBin(localDir, DARWIN_BIN) : null;
+ if (localBin) return (RESOLVED = { ok: true, bin: localBin, source: 'local' });
+ let cached = ensureCachedInstall({ pkg: DARWIN_PKG, pinVersion: DARWIN_PIN_VERSION });
+ let cachedBin = cached.ok ? resolvePackageBin(cached.pkgDir, DARWIN_BIN) : null;
+ // The default cache probe is `<pkgDir>/package.json`, so a half-written
+ // cache β€” npm killed by the 180s install timeout, or two first calls
+ // installing into the same prefix β€” would count as installed forever and
+ // degrade every later call. npx repaired that by re-resolving; re-run the
+ // install once, probing the bin file itself, then give up (#3366).
+ if (cached.ok && !cachedBin) {
+ cached = ensureCachedInstall({
+ pkg: DARWIN_PKG,
+ pinVersion: DARWIN_PIN_VERSION,
+ cliRelPath: packageBinRelPath(cached.pkgDir, DARWIN_BIN) ?? 'dist/cli.js',
+ });
+ cachedBin = cached.ok ? resolvePackageBin(cached.pkgDir, DARWIN_BIN) : null;
+ }
+ if (cachedBin) return (RESOLVED = { ok: true, bin: cachedBin, source: 'cache' });
+ return (RESOLVED = {
+ ok: false,
+ stdout: cached.stdout ?? '',
+ stderr: cached.stderr ?? cached.error ?? `${DARWIN_PIN} has no ${DARWIN_BIN} bin`,
+ });
+}
+
+/** Same degraded shape the npx path produced when the package was unreachable. */
+function unavailable(resolved, start) {
+ return {
+ stdout: resolved.stdout, stderr: resolved.stderr,
+ exitCode: 127, json: null, durationMs: Date.now() - start,
+ degraded: true, reason: `${REASON_PREFIX}-not-available`,
+ };
+}
+
/**
* Sync invocation. Use for short subcommands (`bench verify`, smoke shapes).
* Async variant below for long-running `evolve` calls.
*/
export function runDarwin(args, opts = {}) {
const start = Date.now();
+ const resolved = resolveDarwinBin();
+ if (!resolved.ok) return unavailable(resolved, start);
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const wantJson = opts.json !== false;
const argv = buildArgv(args, wantJson);
- const r = spawnSync('npx', ['-y', '-p', DARWIN_PIN, 'metaharness-darwin', ...argv], {
+ const r = spawnSync(process.execPath, [resolved.bin, ...argv], {
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf-8',
timeout: timeoutMs,
cwd: opts.cwd,
env: { ...process.env, ...(opts.env || {}) },
- shell: process.platform === 'win32',
+ shell: false,
});
const durationMs = Date.now() - start;
const stdout = r.stdout || '';
@@ -119,14 +189,16 @@ export function runDarwin(args, opts = {}) {
export function runDarwinAsync(args, opts = {}) {
return new Promise((resolve) => {
const start = Date.now();
+ const resolved = resolveDarwinBin();
+ if (!resolved.ok) { resolve(unavailable(resolved, start)); return; }
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const wantJson = opts.json !== false;
const argv = buildArgv(args, wantJson);
- const p = spawn('npx', ['-y', '-p', DARWIN_PIN, 'metaharness-darwin', ...argv], {
+ const p = spawn(process.execPath, [resolved.bin, ...argv], {
stdio: ['ignore', 'pipe', 'pipe'],
cwd: opts.cwd,
env: { ...process.env, ...(opts.env || {}) },
- shell: process.platform === 'win32',
+ shell: false,
});
let stdout = '', stderr = '', stderrBuf = '';
p.stdout?.on('data', (d) => { stdout += d.toString(); });
diff --git a/plugins/ruflo-metaharness/scripts/_harness.mjs b/plugins/ruflo-metaharness/scripts/_harness.mjs
index 0b1ade0c3d..f6b42f736e 100755
--- a/plugins/ruflo-metaharness/scripts/_harness.mjs
+++ b/plugins/ruflo-metaharness/scripts/_harness.mjs
@@ -26,7 +26,8 @@
// arbitrary code on user machines on the very next skill invocation.
// The version is now PINNED to METAHARNESS_PIN_VERSION (tilde range β€”
// patch updates only) and only bumped deliberately, in lock-step with
-// optionalDependencies in @claude-flow/cli + ruflo package.json.
+// the range declared in @claude-flow/cli/package.json (enforced by
+// scripts/check-metaharness-pins.mjs).
// 2. PERF: @latest forced an npm-registry metadata check on EVERY call.
// Resolution is now (a) an already-installed local metaharness
// satisfying the pin (walk-up node_modules β€” free), then (b) a ONE-TIME
@@ -53,10 +54,15 @@ import {
const DEFAULT_TIMEOUT_MS = 60_000;
-// Pinned semver range. Bump in lock-step with optionalDependencies in
-// @claude-flow/cli/package.json + ruflo/package.json. NEVER @latest.
+// Pinned semver range. NEVER @latest. Must cover the `metaharness` range
+// declared in v3/@claude-flow/cli/package.json (optional peer `^0.4.1`):
+// this constant decides which INSTALLED copy findLocalPackageDir() accepts,
+// so a range that misses the declared one rejects the copy ruflo ships and
+// npm-installs another at tool-call time. It sat at ~0.3.0 after the CLI
+// moved to ^0.4.1 (b8ec03f34) because nothing compared the two;
+// scripts/check-metaharness-pins.mjs now fails when they diverge.
const METAHARNESS_PKG = 'metaharness';
-const METAHARNESS_PIN_VERSION = '~0.3.0';
+const METAHARNESS_PIN_VERSION = '~0.4.1';
const REASON_NOT_AVAILABLE = 'metaharness-not-available';
diff --git a/plugins/ruflo-metaharness/scripts/_invoke.mjs b/plugins/ruflo-metaharness/scripts/_invoke.mjs
index 9fed9b8943..738aff8139 100644
--- a/plugins/ruflo-metaharness/scripts/_invoke.mjs
+++ b/plugins/ruflo-metaharness/scripts/_invoke.mjs
@@ -21,9 +21,15 @@
// invalidate stale caches automatically
// - findLocalPackageDir() walk-up node_modules resolution so an already
// installed optionalDependency is used for free
+// - resolvePackageBin() realpath'd bin-map entry of a resolved package
+// (#3366 β€” lets _darwin/_redblue run the installed
+// copy instead of npx / a cache install)
// - importOptionalLibrary() bare-import β†’ cached-install fallback for
// 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
+// `npx @claude-flow/cli@latest` in 4 scripts
//
// WHAT DOES NOT LIVE HERE (the per-consumer parts):
// - _redblue's node-direct isMain workaround rationale
@@ -36,7 +42,7 @@
// - RUFLO_METAHARNESS_SKIP_LOCAL=1 disables local node_modules resolution
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -102,11 +108,22 @@ export function satisfiesTildeRange(version, pinVersion) {
* user's ruflo install shipped with). Returns the package dir or null.
* When `pinVersion` is given, only a copy satisfying the pin is accepted β€”
* a stale major/minor in an ancestor node_modules is skipped, not used.
+ *
+ * `{ fromCwd: false }` (#3366) searches ONLY the ruflo install that owns this
+ * plugin. The $CWD walk reaches every ancestor of the tool's working
+ * directory, i.e. directories the user's project β€” or anything above it β€”
+ * controls. That is tolerable for the pre-existing `metaharness` lookup,
+ * which this PR does not change, but the two lookups added here (_darwin,
+ * _redblue) END IN A SPAWN of the package's bin with MCP-supplied argv, so
+ * they stay inside ruflo's own tree and fall back to the pinned cache
+ * install instead.
*/
-export function findLocalPackageDir(pkg, pinVersion) {
+export function findLocalPackageDir(pkg, pinVersion, { fromCwd = true } = {}) {
if (process.env.RUFLO_METAHARNESS_SKIP_LOCAL === '1') return null;
const segments = pkg.split('/');
- const starts = [dirname(fileURLToPath(import.meta.url)), process.cwd()];
+ const starts = fromCwd
+ ? [dirname(fileURLToPath(import.meta.url)), process.cwd()]
+ : [dirname(fileURLToPath(import.meta.url))];
const seen = new Set();
for (const start of starts) {
let dir = start;
@@ -131,17 +148,51 @@ export function findLocalPackageDir(pkg, pinVersion) {
return null;
}
+/**
+ * Absolute path of `binName` from the package.json `bin` map of an already
+ * resolved package dir (findLocalPackageDir / ensureCachedInstall), or null.
+ * Read from the bin map rather than hardcoded, same as _harness.mjs.
+ *
+ * REALPATH'd on purpose (#3366): pnpm and other symlinked layouts hand us a
+ * symlinked package dir, and @metaharness/redblue's CLI only dispatches when
+ * `import.meta.url === file://${process.argv[1]}` (see _redblue.mjs) β€” Node
+ * reports import.meta.url as the REAL path, so argv[1] has to be one too or
+ * the CLI exits 0 having done nothing.
+ */
+export function resolvePackageBin(pkgDir, binName) {
+ const rel = packageBinRelPath(pkgDir, binName);
+ if (!rel) return null;
+ try {
+ const abs = join(pkgDir, rel);
+ return existsSync(abs) ? realpathSync(abs) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The package.json `bin` entry for `binName`, as declared (relative), or null. */
+export function packageBinRelPath(pkgDir, binName) {
+ try {
+ const pj = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8'));
+ const rel = typeof pj.bin === 'string' ? pj.bin : pj.bin?.[binName];
+ return rel || null;
+ } catch {
+ return null;
+ }
+}
+
/**
* One-time versioned cache install of a PINNED range. Generalizes
* gepa.mjs:98-121 / _redblue.mjs:72-102. The cache dir is
* `<base>/<shortname>-cache-<pin-digits>` (e.g. redblue-cache-0.1.4,
- * darwin-cache-0.8.0, metaharness-cache-0.3.0) so existing caches created
+ * darwin-cache-0.10.2, metaharness-cache-0.4.1) so existing caches created
* by the pre-consolidation helpers remain valid, and bumping the pin
- * invalidates stale installs automatically.
+ * invalidates stale installs automatically (the pre-bump darwin-cache-0.8.0
+ * and metaharness-cache-0.3.0 dirs are simply no longer selected).
*
* @param {object} spec
* @param {string} spec.pkg npm package name (may be scoped)
- * @param {string} spec.pinVersion tilde range, e.g. '~0.3.0'
+ * @param {string} spec.pinVersion tilde range, e.g. '~0.4.1'
* @param {string} [spec.cliRelPath] path inside the package that must exist
* post-install (also returned as cliPath)
* @param {number} [spec.timeoutMs] install timeout (default 180s)
@@ -228,3 +279,66 @@ export function makeDegradedEmitter(pkg, pinVersion) {
process.exit(0);
};
}
+
+// ---------------------------------------------------------------------------
+// The ruflo CLI that ships this plugin (#3366)
+// ---------------------------------------------------------------------------
+// audit-list / audit-trend / oia-audit / similarity read and write the
+// `metaharness-audit` memory namespace through the ruflo CLI. They used to
+// spawn `npx @claude-flow/cli@latest memory …`, which on every call:
+// - resolved `latest` through the npm registry (the "metadata check on
+// EVERY call" _harness.mjs removed for its own npx path); without registry
+// access it fails, so oia_audit reports `persisted: false` and audit_list
+// silently reports 0 records;
+// - could run a DIFFERENT @claude-flow/cli than the one that spawned the
+// tool (npx cache vs registry skew β€” #3306), i.e. another memory backend /
+// schema than the MCP server's own memory_* tools see;
+// - cold-fetched the whole CLI when the npx cache was empty (#3145, #3154).
+// The plugin is published INSIDE @claude-flow/cli
+// (<cli>/plugins/ruflo-metaharness/scripts β€” see prepare-publish.mjs), and the
+// MCP server / `ruflo metaharness` dispatcher locate it by walking up from
+// their own dist/, so the owning CLI is two directories above this plugin.
+// It is run with process.execPath + bin/cli.js (the mcp-launch.cjs /
+// daemon-autostart.ts pattern). A candidate only counts when dist/src/index.js
+// 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:
+// - 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`.
+const PLUGIN_SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
+
+let RUFLO_CLI = null;
+/** `{ command, args, shell, source }` for invoking the ruflo CLI. Memoized. */
+export function resolveRufloCli() {
+ if (RUFLO_CLI) return RUFLO_CLI;
+ 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 = [
+ join(PLUGIN_SCRIPTS_DIR, '..', '..', '..'), // published: <cli>/plugins/ruflo-metaharness/scripts
+ join(PLUGIN_SCRIPTS_DIR, '..', '..', '..', 'v3', '@claude-flow', 'cli'), // repo checkout / marketplace clone
+ ];
+ for (const dir of candidates) {
+ 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 (RUFLO_CLI = { command: process.execPath, args: [bin], shell: false, source: 'local' });
+ }
+ } catch { /* not this layout β€” try the next */ }
+ }
+ return (RUFLO_CLI = { command: 'npx', args: ['@claude-flow/cli@latest'], shell: process.platform === 'win32', source: 'npx' });
+}
+
+/** spawnSync the ruflo CLI with `args` (e.g. ['memory', 'list', …]); same result shape as before. */
+export function runRufloCli(args, opts = {}) {
+ const cli = resolveRufloCli();
+ return spawnSync(cli.command, [...cli.args, ...args], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ encoding: 'utf-8',
+ shell: cli.shell,
+ ...opts,
+ });
+}
diff --git a/plugins/ruflo-metaharness/scripts/_redblue.mjs b/plugins/ruflo-metaharness/scripts/_redblue.mjs
index cde4e1a40e..dcea41ac00 100644
--- a/plugins/ruflo-metaharness/scripts/_redblue.mjs
+++ b/plugins/ruflo-metaharness/scripts/_redblue.mjs
@@ -32,6 +32,16 @@
// (file separately β€” when fixed, we could go back to a bin-shim pattern,
// though the node-direct cached path is now the family-wide standard anyway).
//
+// INSTALLED COPY FIRST (#3366): an @metaharness/redblue already on disk that
+// satisfies the pin (a ruflo 3.42.4 install carries 0.1.4, via metaharness /
+// ruvector) is used before the cache install, same order as _harness.mjs /
+// _darwin.mjs. Previously the first call always ran `npm install` into the
+// cache even with that copy present.
+// Whichever copy is chosen, its CLI path is realpath'd
+// (_invoke.resolvePackageBin / realpathSync): a pnpm-symlinked package dir,
+// or a cache base under a symlink such as macOS /tmp -> /private/tmp, would
+// otherwise hit the same isMain mismatch described above.
+//
// CONTRACT (matches runMetaharness/runDarwin):
// - returns `{ stdout, stderr, exitCode, durationMs, degraded, reason? }`
// - subprocess hard timeout (default 120s; --mock-judge runs are seconds)
@@ -47,12 +57,15 @@
// $OPENROUTER_API_KEY which we never inject.
import { spawnSync } from 'node:child_process';
+import { realpathSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import {
classifyDegraded,
ensureCachedInstall,
+ findLocalPackageDir,
makeDegradedEmitter,
+ resolvePackageBin,
} from './_invoke.mjs';
const DEFAULT_TIMEOUT_MS = 120_000;
@@ -80,8 +93,15 @@ export function runRedblue(args, opts = {}) {
const start = Date.now();
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
- // 1. Ensure redblue is installed in our cache dir (one-time install).
- const install = ensureCachedInstall({
+ // 0. An installed copy satisfying the pin β€” free, no npm (#3366).
+ // fromCwd:false: the resolved bin is SPAWNED with argv that comes from
+ // MCP input, so only ruflo's own tree is searched, never the tool's cwd
+ // or its ancestors (see findLocalPackageDir in _invoke.mjs).
+ const localDir = findLocalPackageDir(REDBLUE_PKG, REDBLUE_PIN_VERSION, { fromCwd: false });
+ const localCli = localDir ? resolvePackageBin(localDir, 'redblue') : null;
+
+ // 1. Otherwise ensure redblue is installed in our cache dir (one-time install).
+ const install = localCli ? { ok: true, cliPath: localCli } : ensureCachedInstall({
pkg: REDBLUE_PKG,
pinVersion: REDBLUE_PIN_VERSION,
cliRelPath: CLI_REL_PATH,
@@ -99,15 +119,22 @@ export function runRedblue(args, opts = {}) {
};
}
- // 2. Invoke `node <real-path-to-cli> <args>` so upstream's isMain check
- // succeeds (argv[1] matches import.meta.url).
- const r = spawnSync('node', [install.cliPath, ...args], {
+ // 2. Invoke `<this node> <real-path-to-cli> <args>` so upstream's isMain
+ // check succeeds (argv[1] matches import.meta.url) β€” realpath'd, see
+ // header. process.execPath + shell:false, like _darwin/_harness: the
+ // argv carries MCP-supplied values (--config / --out / --in), and with
+ // shell:true on win32 Node hands cmd.exe one unquoted string, so a value
+ // such as `x.yaml & whoami` would run as a command (and a path with a
+ // space β€” `C:\Program Files\…` β€” would break). node needs no shell.
+ let cliPath = install.cliPath;
+ try { cliPath = realpathSync(cliPath); } catch { /* missing β€” node's MODULE_NOT_FOUND β†’ degraded below */ }
+ const r = spawnSync(process.execPath, [cliPath, ...args], {
stdio: ['ignore', 'pipe', 'pipe'],
encoding: 'utf-8',
timeout: timeoutMs,
cwd: opts.cwd,
env: { ...process.env, ...(opts.env || {}) },
- shell: process.platform === 'win32',
+ shell: false,
});
const durationMs = Date.now() - start;
const stdout = r.stdout || '';
diff --git a/plugins/ruflo-metaharness/scripts/audit-list.mjs b/plugins/ruflo-metaharness/scripts/audit-list.mjs
index 88a3a41d90..7687f2db6b 100755
--- a/plugins/ruflo-metaharness/scripts/audit-list.mjs
+++ b/plugins/ruflo-metaharness/scripts/audit-list.mjs
@@ -16,12 +16,13 @@
// 0 ok
// 2 config error
-import { spawnSync } from 'node:child_process';
+import { runRufloCli } from './_invoke.mjs';
const NS = process.env.AUDIT_LIST_NAMESPACE || 'metaharness-audit';
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// #3366 β€” memory calls go through runRufloCli() (_invoke.mjs): the ruflo CLI
+// that ships this plugin, not `npx @claude-flow/cli@latest` (npm-registry
+// resolution per call, possible version skew, fails without registry access).
+// CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`.
const ARGS = (() => {
const a = { limit: 20, since: null, format: 'table' };
@@ -43,10 +44,10 @@ function parseDurationMs(spec) {
}
function memList() {
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'list',
+ const r = runRufloCli([
+ 'memory', 'list',
'--namespace', NS, '--format', 'json',
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
+ ]);
if (r.status !== 0) return [];
const m = /\[[\s\S]*\]/.exec(r.stdout || '');
if (!m) return [];
@@ -54,10 +55,10 @@ function memList() {
}
function memRetrieve(key) {
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'retrieve',
+ const r = runRufloCli([
+ 'memory', 'retrieve',
'--namespace', NS, '--key', key,
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
+ ]);
if (r.status !== 0) return null;
const m = /\{[\s\S]*\}/.exec(r.stdout || '');
if (!m) return null;
diff --git a/plugins/ruflo-metaharness/scripts/audit-trend.mjs b/plugins/ruflo-metaharness/scripts/audit-trend.mjs
index e635167651..9b7e6ee36d 100755
--- a/plugins/ruflo-metaharness/scripts/audit-trend.mjs
+++ b/plugins/ruflo-metaharness/scripts/audit-trend.mjs
@@ -25,7 +25,7 @@
// 2 config error or input not found
import { readFileSync, existsSync } from 'node:fs';
-import { spawnSync } from 'node:child_process';
+import { runRufloCli } from './_invoke.mjs';
// iter 38 β€” structural-distance drift via ADR-152 Β§3.1 production module.
// Falls back to null if either record predates iter-38 oia-audit (no
// fingerprint field) β€” graceful degradation, never throws.
@@ -36,9 +36,10 @@ import { SEVERITY_RANK, rankSeverity } from './_harness.mjs';
// iter 63 β€” SEVERITY_RANK moved to _harness.mjs (imported above)
const NS = process.env.AUDIT_TREND_NAMESPACE || 'metaharness-audit';
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// #3366 β€” memory calls go through runRufloCli() (_invoke.mjs): the ruflo CLI
+// that ships this plugin, not `npx @claude-flow/cli@latest` (npm-registry
+// resolution per call, possible version skew, fails without registry access).
+// CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`.
const ARGS = (() => {
const a = {
@@ -62,10 +63,10 @@ const ARGS = (() => {
})();
function memRetrieve(key) {
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'retrieve',
+ const r = runRufloCli([
+ 'memory', 'retrieve',
'--namespace', NS, '--key', key,
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
+ ]);
if (r.status !== 0) return null;
const m = /\{[\s\S]*\}/.exec(r.stdout || '');
if (!m) return null;
diff --git a/plugins/ruflo-metaharness/scripts/drift-from-history.mjs b/plugins/ruflo-metaharness/scripts/drift-from-history.mjs
index 5479c718d0..15aecf9f35 100755
--- a/plugins/ruflo-metaharness/scripts/drift-from-history.mjs
+++ b/plugins/ruflo-metaharness/scripts/drift-from-history.mjs
@@ -42,9 +42,8 @@ import { fileURLToPath } from 'node:url';
const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
const NS = process.env.METAHARNESS_AUDIT_NAMESPACE || 'metaharness-audit';
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// Memory access is delegated to audit-list / oia-audit / audit-trend (they
+// call the shipping ruflo CLI through _invoke.runRufloCli β€” #3366).
const ARGS = (() => {
const a = {
diff --git a/plugins/ruflo-metaharness/scripts/oia-audit.mjs b/plugins/ruflo-metaharness/scripts/oia-audit.mjs
index c0ee474a9d..e3ee487485 100755
--- a/plugins/ruflo-metaharness/scripts/oia-audit.mjs
+++ b/plugins/ruflo-metaharness/scripts/oia-audit.mjs
@@ -24,7 +24,7 @@
// 1 --alert-on-worst threshold exceeded
// 2 config error or audit failure
-import { spawnSync } from 'node:child_process';
+import { runRufloCli } from './_invoke.mjs';
// iter 63 β€” SEVERITY_RANK + rankSeverity consolidated to _harness.mjs
// (was local in iter 62; now shared with audit-trend + mcp-scan).
import { runHarness, runMetaharness, runHarnessAsync, runMetaharnessAsync, emitDegradedJsonAndExit, parseMcpScanText, SEVERITY_RANK, rankSeverity } from './_harness.mjs';
@@ -33,9 +33,10 @@ import { runHarness, runMetaharness, runHarnessAsync, runMetaharnessAsync, emitD
// source of truth). The local copy from iter 62 is gone; the imports
// at the top of this file provide the same names.
const NS = process.env.OIA_AUDIT_NAMESPACE || 'metaharness-audit';
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// #3366 β€” memory calls go through runRufloCli() (_invoke.mjs): the ruflo CLI
+// that ships this plugin, not `npx @claude-flow/cli@latest` (npm-registry
+// resolution per call, possible version skew, fails without registry access).
+// CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`.
const ARGS = (() => {
const a = { path: '.', format: 'json', dryRun: false, alertWorst: null };
@@ -97,12 +98,12 @@ async function runAllParallel(path) {
function persist(payload) {
const key = `audit-${new Date().toISOString().replace(/[:.]/g, '-')}`;
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'store',
+ const r = runRufloCli([
+ 'memory', 'store',
'--namespace', NS,
'--key', key,
'--value', JSON.stringify(payload),
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
+ ]);
return {
ok: r.status === 0,
namespace: NS,
diff --git a/plugins/ruflo-metaharness/scripts/similarity.mjs b/plugins/ruflo-metaharness/scripts/similarity.mjs
index 5ace960046..50e042d13b 100755
--- a/plugins/ruflo-metaharness/scripts/similarity.mjs
+++ b/plugins/ruflo-metaharness/scripts/similarity.mjs
@@ -18,19 +18,20 @@
//
// ADR-150 ARCHITECTURAL CONSTRAINTS PRESERVED
// - Pure-TS function (`_similarity.mjs`), no `@metaharness/*` import
-// - No new dep; uses node:fs + node:child_process only for memory lookup
+// - No new dep; uses node:fs + _invoke.runRufloCli only for memory lookup
// - Graceful degradation: missing keys / malformed JSON β†’ exit 2 with
// a structured `{ degraded: true, reason: ... }` payload on stdout
// - CI-gate ready: smoke step 17y locks this contract
import { readFileSync, existsSync } from 'node:fs';
-import { spawnSync } from 'node:child_process';
+import { runRufloCli } from './_invoke.mjs';
import { similarity } from './_similarity.mjs';
const NS = process.env.HARNESS_SIMILARITY_NAMESPACE || 'metaharness-audit';
-const CLI_PKG = process.env.CLI_CORE === '1'
- ? '@claude-flow/cli-core@alpha'
- : '@claude-flow/cli@latest';
+// #3366 β€” memory calls go through runRufloCli() (_invoke.mjs): the ruflo CLI
+// that ships this plugin, not `npx @claude-flow/cli@latest` (npm-registry
+// resolution per call, possible version skew, fails without registry access).
+// CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`.
const ARGS = (() => {
const a = {
@@ -66,10 +67,10 @@ function emitDegradedAndExit(reason, code = 2) {
}
function memRetrieve(key) {
- const r = spawnSync('npx', [
- CLI_PKG, 'memory', 'retrieve',
+ const r = runRufloCli([
+ 'memory', 'retrieve',
'--namespace', NS, '--key', key,
- ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
+ ]);
if (r.status !== 0) return null;
const m = /\{[\s\S]*\}/.exec(r.stdout || '');
if (!m) return null;
diff --git a/plugins/ruflo-metaharness/scripts/smoke.sh b/plugins/ruflo-metaharness/scripts/smoke.sh
index b65551e642..b094c6dfe3 100755
--- a/plugins/ruflo-metaharness/scripts/smoke.sh
+++ b/plugins/ruflo-metaharness/scripts/smoke.sh
@@ -253,6 +253,24 @@ grep -q "bin.harness" "$F" 2>/dev/null || miss="$miss no-harness-bin"
grep -q "cwd: opts" "$F" || miss="$miss no-cwd-passthrough"
[[ -z "$miss" ]] && ok || bad "$miss"
+step "17r2. no tool-time npx: darwin / redblue / memory use what is installed (#3366)"
+miss=""
+# 17r locked _harness.mjs off npx; _darwin.mjs still ran `npx -y -p
+# @metaharness/darwin@<pin>` per call, _redblue.mjs npm-installed into its
+# cache ignoring the installed copy, and 4 scripts ran
+# `npx @claude-flow/cli@latest memory …`. Static guard + hermetic runtime
+# gate (stub packages in the published layout, npm/npx trap).
+if grep -qE "spawn(Sync)?\('npx'" "$ROOT/scripts/_darwin.mjs" 2>/dev/null; then
+ miss="$miss darwin-npx-regressed"
+fi
+for s in audit-list audit-trend oia-audit similarity; do
+ grep -q "runRufloCli" "$ROOT/scripts/${s}.mjs" 2>/dev/null || miss="$miss ${s}-not-using-runRufloCli"
+done
+F="$ROOT/scripts/test-no-tool-time-npx.mjs"
+[[ -x "$F" ]] || miss="$miss not-executable"
+node "$F" >/dev/null 2>&1 || miss="$miss test-no-tool-time-npx-fails"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
step "17z80. HIGH security findings survive wrapper + composite boundaries (#2750)"
miss=""
SEC_FIXTURE=$(mktemp -d)
@@ -461,6 +479,19 @@ for pkg in "metaharness" "@metaharness/router" "@metaharness/kernel" "@metaharne
done
[[ -z "$miss" ]] && ok || bad "$miss"
+step "17z74a. plugin helper pins accept the CLI-declared ranges β€” no tool-time download (#3366)"
+miss=""
+# 17z74 compares package.json files with each other; the helpers' own
+# *_PIN_VERSION constants (what findLocalPackageDir accepts) were never
+# compared with them and drifted (~0.3.0 / ~0.8.0 vs declared ^0.4.1 /
+# ~0.10.2), so every metaharness_* call npm-installed an older release next
+# to the one ruflo ships. Hermetic runtime gate: stub packages at the declared
+# versions, published layout, npm/npx trap.
+F="$ROOT/scripts/test-pin-alignment.mjs"
+[[ -x "$F" ]] || miss="$miss not-executable"
+node "$F" >/dev/null 2>&1 || miss="$miss test-pin-alignment-fails"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
step "17z73. metaharness packages tilde-pinned (anti-caret regression, iter 110)"
miss=""
# ADR-150 architectural-constraint review-round-1 mandated tilde pinning
diff --git a/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs b/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs
new file mode 100755
index 0000000000..f7f9222e17
--- /dev/null
+++ b/plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs
@@ -0,0 +1,319 @@
+#!/usr/bin/env node
+// test-no-tool-time-npx.mjs β€” regression test: metaharness_* tool calls must
+// not reach for npm / npx when what they need is already installed (#3366).
+//
+// THE BUG
+// Three helpers spawned the npm registry at TOOL-CALL time even on a complete
+// ruflo install:
+// - _darwin.mjs `npx -y -p @metaharness/darwin@<pin> metaharness-darwin`
+// on EVERY evolve / bench / security-bench call, although
+// the CLI ships @metaharness/darwin as an optionalDependency
+// - _redblue.mjs `npm install --prefix ~/.ruflo/redblue-cache-<pin>` on
+// first use, never looking at the installed copy
+// - audit-list / audit-trend / oia-audit / similarity
+// `npx @claude-flow/cli@latest memory …` β€” a registry
+// round trip per call, possibly a DIFFERENT CLI version
+// than the server that spawned the tool (#3306), and a
+// silent failure offline (oia_audit persisted:false,
+// audit_list "0 records")
+//
+// WHAT THIS TEST PROVES (hermetic β€” stub packages, no network)
+// A PUBLISHED layout is built in a temp dir:
+// <p>/node_modules/@claude-flow/cli/{package.json,bin/cli.js,dist/src/index.js}
+// <p>/node_modules/@claude-flow/cli/plugins/ruflo-metaharness/scripts/* (copied)
+// <p>/node_modules/metaharness stub, satisfies the _harness pin
+// <p>/node_modules/@metaharness/darwin stub, satisfies the _darwin pin
+// <p>/node_modules/@metaharness/redblue β†’ <p>/store/redblue (pnpm-style
+// SYMLINK; the stub keeps upstream redblue's
+// `import.meta.url === file://${argv[1]}` isMain guard)
+// with a PATH trap whose npm / npx log every call and exit 1 (offline).
+// Phase 1 darwin: bench verify (sync) + security bench (async) run the
+// installed bin β€” not degraded, zero npm/npx; and, with no
+// installed copy, the existing darwin-cache-<pin> runs instead
+// Phase 2 redblue: the symlinked installed copy runs (isMain holds because
+// the resolved bin is realpath'd) β€” zero npm/npx
+// Phase 3 memory round trip through the CLI that ships the plugin:
+// oia-audit persists β†’ audit-list lists it β†’ audit-trend and
+// similarity read it back β€” zero npm/npx
+// Phase 4 contracts kept: CLI_CORE=1 still opts into npx cli-core@alpha; a
+// layout with no usable local CLI β€” missing, or present but not
+// named @claude-flow/cli β€” still falls back to
+// `npx @claude-flow/cli@latest`; darwin absent β†’ degraded, exit 0
+// (ADR-150 rule #3)
+// Phase 5 the two new lookups stay inside ruflo's tree: a darwin / redblue
+// in the tool's OWN cwd node_modules is never executed
+// ({fromCwd:false}); a cache dir with package.json but no bin gets
+// one reinstall instead of degrading forever; and neither helper
+// spawns the resolved bin through a shell
+//
+// USAGE
+// node plugins/ruflo-metaharness/scripts/test-no-tool-time-npx.mjs
+//
+// EXIT CODES
+// 0 all assertions passed (or skipped on win32 β€” the trap is POSIX sh)
+// 1 at least one assertion failed
+
+import { spawnSync } from 'node:child_process';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
+
+if (process.platform === 'win32') {
+ console.log('# test-no-tool-time-npx β€” SKIPPED on win32 (the npm/npx trap is a POSIX sh script)');
+ process.exit(0);
+}
+
+let passed = 0, failed = 0;
+const failures = [];
+function assert(cond, label) {
+ console.log(` ${cond ? 'βœ“' : 'βœ—'} ${label}`);
+ if (cond) passed++;
+ else { failures.push(label); failed++; }
+}
+
+/** Lowest version a tilde pin admits β€” the stubs sit exactly there. */
+function floorOfPin(fullPin) {
+ const m = /@[~^]?(\d+\.\d+\.\d+)$/.exec(fullPin);
+ return m ? m[1] : '0.0.0';
+}
+const { METAHARNESS_VERSION_PIN } = await import(pathToFileURL(join(SCRIPTS_DIR, '_harness.mjs')).href);
+const { DARWIN_VERSION_PIN } = await import(pathToFileURL(join(SCRIPTS_DIR, '_darwin.mjs')).href);
+const { REDBLUE_VERSION_PIN } = await import(pathToFileURL(join(SCRIPTS_DIR, '_redblue.mjs')).href);
+
+const write = (file, body, mode) => {
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, body);
+ if (mode) chmodSync(file, mode);
+};
+const echoStub = (name, version) =>
+ `console.log(JSON.stringify({ stub: '${name}', version: '${version}', argv: process.argv.slice(2) }));\n`;
+
+// realpath: macOS tmpdir() is /var/… while resolved paths come back as /private/var/…
+const TMP = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-no-tool-time-npx-')));
+const NM = join(TMP, 'node_modules');
+const CLI = join(NM, '@claude-flow', 'cli');
+const PLUGIN_SCRIPTS = join(CLI, 'plugins', 'ruflo-metaharness', 'scripts');
+const TRAP = join(TMP, 'trap-bin');
+const TRAP_LOG = join(TMP, 'trap.log');
+const CLI_LOG = join(TMP, 'cli-calls.log');
+const PROJECT = join(TMP, 'project');
+
+try {
+ // ── fixture ───────────────────────────────────────────────────────────
+ mkdirSync(PLUGIN_SCRIPTS, { recursive: true });
+ for (const f of readdirSync(SCRIPTS_DIR)) {
+ if (f.endsWith('.mjs')) copyFileSync(join(SCRIPTS_DIR, f), join(PLUGIN_SCRIPTS, f));
+ }
+ mkdirSync(PROJECT);
+
+ // The ruflo CLI that ships the plugin: a stub with a tiny file-backed
+ // `memory store|list|retrieve`, logging every invocation.
+ write(join(CLI, 'package.json'), JSON.stringify({ name: '@claude-flow/cli', version: '0.0.0-test', type: 'module', bin: { cli: 'bin/cli.js' } }));
+ write(join(CLI, 'dist', 'src', 'index.js'), 'export {};\n');
+ write(join(CLI, 'bin', 'cli.js'), `
+import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
+const argv = process.argv.slice(2);
+appendFileSync(${JSON.stringify(CLI_LOG)}, argv.slice(0, 2).join(' ') + '\\n');
+const opt = (k) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : undefined; };
+const DB = ${JSON.stringify(join(TMP, 'stub-memory.json'))};
+const db = existsSync(DB) ? JSON.parse(readFileSync(DB, 'utf-8')) : {};
+const ns = opt('--namespace') ?? 'default';
+if (argv[0] !== 'memory') process.exit(2);
+if (argv[1] === 'store') { db[ns] = { ...(db[ns] ?? {}), [opt('--key')]: opt('--value') }; writeFileSync(DB, JSON.stringify(db)); console.log('[OK] Data stored successfully'); }
+else if (argv[1] === 'list') console.log(JSON.stringify(Object.keys(db[ns] ?? {}).map((key) => ({ key, namespace: ns }))));
+else if (argv[1] === 'retrieve') { const v = db[ns]?.[opt('--key')]; if (v === undefined) { console.error('not found'); process.exit(1); } console.log(v); }
+else process.exit(2);
+`);
+
+ const mhVersion = floorOfPin(METAHARNESS_VERSION_PIN);
+ write(join(NM, 'metaharness', 'package.json'), JSON.stringify({ name: 'metaharness', version: mhVersion, type: 'module', bin: { metaharness: 'dist/bin.js', harness: 'dist/harness-bin.js' } }));
+ write(join(NM, 'metaharness', 'dist', 'bin.js'), echoStub('metaharness', mhVersion));
+ write(join(NM, 'metaharness', 'dist', 'harness-bin.js'), echoStub('harness', mhVersion));
+
+ const darwinVersion = floorOfPin(DARWIN_VERSION_PIN);
+ const pinDigits = DARWIN_VERSION_PIN.replace(/^.*@[~^]?/, ''); // cache-dir suffix
+ const DARWIN = join(NM, '@metaharness', 'darwin');
+ write(join(DARWIN, 'package.json'), JSON.stringify({ name: '@metaharness/darwin', version: darwinVersion, type: 'module', bin: { 'metaharness-darwin': './dist/cli.js' } }));
+ write(join(DARWIN, 'dist', 'cli.js'), echoStub('metaharness-darwin', darwinVersion));
+
+ // redblue lives in a pnpm-like store and is SYMLINKED into node_modules;
+ // its CLI keeps upstream's isMain guard, so it only prints when argv[1] is
+ // the real path.
+ const redblueVersion = floorOfPin(REDBLUE_VERSION_PIN);
+ const RB_STORE = join(TMP, 'store', 'redblue');
+ write(join(RB_STORE, 'package.json'), JSON.stringify({ name: '@metaharness/redblue', version: redblueVersion, type: 'module', bin: { redblue: './dist/cli/index.js', 'metaharness-redblue': './dist/cli/index.js' } }));
+ write(join(RB_STORE, 'dist', 'cli', 'index.js'),
+ 'const isMain = import.meta.url === `file://${process.argv[1]}`;\n' +
+ `if (isMain) console.log(JSON.stringify({ stub: 'redblue', version: '${redblueVersion}', argv: process.argv.slice(2) }));\n`);
+ symlinkSync(RB_STORE, join(NM, '@metaharness', 'redblue'));
+
+ for (const t of ['npm', 'npx']) {
+ write(join(TRAP, t), `#!/bin/sh\nprintf '%s %s\\n' "${t}" "$*" >> "${TRAP_LOG}"\necho "npm ERR! ${t} blocked by test-no-tool-time-npx trap" >&2\nexit 1\n`, 0o755);
+ }
+ 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;
+ 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) => {
+ const r = spawnSync(process.execPath, [join(scriptsDir, script), ...args], { cwd, env, encoding: 'utf-8', timeout: 60_000 });
+ let json = null;
+ try { json = JSON.parse(r.stdout); } catch { /* callers assert */ }
+ return { ...r, json };
+ };
+ const noNpm = (label) => {
+ const t = trapped();
+ assert(t === '', `${label}: no npm / npx spawned${t ? ` (got: ${t.split('\n')[0].slice(0, 160)})` : ''}`);
+ resetTrap();
+ };
+
+ console.log('# test-no-tool-time-npx\n');
+
+ // ── Phase 1 β€” darwin runs the installed bin ──────────────────────────
+ console.log(`Phase 1 β€” @metaharness/darwin ${darwinVersion} (installed) serves bench + security bench`);
+ const suite = join(PROJECT, 'suite.json');
+ writeFileSync(suite, '{}');
+ const bench = run('bench.mjs', ['--op', 'verify', '--suite', suite]);
+ assert(bench.status === 0 && bench.json?.success === true, `bench verify exits 0 with success (got ${bench.status}, reason ${bench.json?.reason ?? 'none'})`);
+ assert(bench.json?.data?.stub === 'metaharness-darwin' && bench.json?.data?.argv?.[0] === 'bench',
+ 'bench verify ran the installed metaharness-darwin (sync path)');
+ noNpm('bench verify');
+ const sec = run('security-bench.mjs', ['--population', '1', '--cycles', '1']);
+ assert(sec.json?.degraded !== true, `security bench is not degraded (reason ${sec.json?.reason ?? 'none'})`);
+ noNpm('security bench (async path)');
+ // …and the OTHER success branch: the one-time versioned cache that gepa
+ // already shares, which is what a machine without a qualifying installed
+ // copy falls back to. Without this, deleting that branch leaves the suite
+ // green.
+ const seededCache = join(TMP, 'seeded-cache');
+ const cachedDarwin = join(seededCache, `darwin-cache-${pinDigits}`, 'node_modules', '@metaharness', 'darwin');
+ write(join(cachedDarwin, 'package.json'), JSON.stringify({ name: '@metaharness/darwin', version: darwinVersion, type: 'module', bin: { 'metaharness-darwin': './dist/cli.js' } }));
+ write(join(cachedDarwin, 'dist', 'cli.js'), echoStub('darwin-from-cache', darwinVersion));
+ const cachedBench = run('bench.mjs', ['--op', 'verify', '--suite', suite],
+ { ...baseEnv, RUFLO_METAHARNESS_CACHE_BASE: seededCache, RUFLO_METAHARNESS_SKIP_LOCAL: '1' });
+ assert(cachedBench.json?.data?.stub === 'darwin-from-cache',
+ `no installed copy β†’ the existing darwin-cache-${pinDigits} runs (got stub ${cachedBench.json?.data?.stub ?? 'none'})`);
+ noNpm('bench verify via darwin-cache');
+
+ // ── Phase 2 β€” redblue runs the installed (symlinked) copy ────────────
+ console.log(`\nPhase 2 β€” @metaharness/redblue ${redblueVersion} (installed, symlinked) serves attack`);
+ const rb = run('redblue.mjs', ['attack', 'prompt', '--count', '1']);
+ assert(rb.status === 0 && rb.json?.ok === true, `redblue attack exits 0 (got ${rb.status}, reason ${rb.json?.reason ?? 'none'})`);
+ assert(/"stub":"redblue"/.test(rb.json?.stdout ?? ''), 'redblue CLI actually dispatched (isMain held: resolved bin is realpath\'d)');
+ noNpm('redblue attack');
+
+ // ── Phase 3 β€” memory round trip through the CLI that ships the plugin ─
+ console.log('\nPhase 3 β€” oia-audit β†’ audit-list β†’ audit-trend / similarity via the shipping CLI');
+ rmSync(CLI_LOG, { force: true });
+ const oia = run('oia-audit.mjs', ['--path', PROJECT]);
+ assert(oia.json?.persisted?.ok === true, `oia-audit persisted the record (got ${JSON.stringify(oia.json?.persisted ?? null)})`);
+ const key = oia.json?.persisted?.key;
+ const list = run('audit-list.mjs', ['--format', 'json']);
+ assert(list.json?.returned === 1 && list.json?.records?.[0]?.key === key, `audit-list returns the persisted record (got ${list.json?.returned})`);
+ const trend = run('audit-trend.mjs', ['--baseline-key', key, '--current-key', key, '--format', 'json']);
+ assert(trend.status === 0 && trend.json !== null, `audit-trend reads both records back (exit ${trend.status})`);
+ const sim = run('similarity.mjs', ['--a-key', key, '--b-key', key, '--format', 'json']);
+ assert(sim.status === 0 && sim.json?.degraded !== true, `similarity reads both records back (exit ${sim.status}, reason ${sim.json?.reason ?? 'none'})`);
+ const cliCalls = existsSync(CLI_LOG) ? readFileSync(CLI_LOG, 'utf-8').trim().split('\n') : [];
+ assert(cliCalls.includes('memory store') && cliCalls.includes('memory list') && cliCalls.includes('memory retrieve'),
+ `the shipping CLI served store + list + retrieve (saw: ${[...new Set(cliCalls)].join(', ') || 'nothing'})`);
+ noNpm('memory round trip');
+
+ // ── Phase 4 β€” contracts kept ─────────────────────────────────────────
+ console.log('\nPhase 4 β€” opt-in and fallback contracts unchanged');
+ run('audit-list.mjs', ['--format', 'json'], { ...baseEnv, CLI_CORE: '1' });
+ assert(trapped().startsWith('npx @claude-flow/cli-core@alpha memory list'), 'CLI_CORE=1 still opts into `npx @claude-flow/cli-core@alpha`');
+ resetTrap();
+ // No usable local CLI (e.g. a marketplace clone with no dist/ build) β†’ the
+ // pre-existing npx fallback, unchanged.
+ const bare = join(TMP, 'bare', 'plugins', 'ruflo-metaharness', 'scripts');
+ mkdirSync(bare, { recursive: true });
+ for (const f of readdirSync(PLUGIN_SCRIPTS)) copyFileSync(join(PLUGIN_SCRIPTS, f), join(bare, f));
+ const bareList = run('audit-list.mjs', ['--format', 'json'], baseEnv, bare);
+ assert(bareList.status === 0 && trapped().startsWith('npx @claude-flow/cli@latest memory list'),
+ 'no local CLI β†’ falls back to `npx @claude-flow/cli@latest` (exit 0, as before)');
+ resetTrap();
+ // A directory two levels up that has bin/cli.js AND dist/src/index.js but
+ // is NOT @claude-flow/cli must not be run as the ruflo CLI.
+ const impostorScripts = join(TMP, 'impostor', 'plugins', 'ruflo-metaharness', 'scripts');
+ mkdirSync(impostorScripts, { recursive: true });
+ for (const f of readdirSync(PLUGIN_SCRIPTS)) copyFileSync(join(PLUGIN_SCRIPTS, f), join(impostorScripts, f));
+ write(join(TMP, 'impostor', 'package.json'), JSON.stringify({ name: 'some-other-package', version: '1.0.0' }));
+ write(join(TMP, 'impostor', 'bin', 'cli.js'), 'console.log("[]");\n');
+ write(join(TMP, 'impostor', 'dist', 'src', 'index.js'), 'export {};\n');
+ const impostor = run('audit-list.mjs', ['--format', 'json'], baseEnv, impostorScripts);
+ assert(impostor.status === 0 && trapped().startsWith('npx @claude-flow/cli@latest memory list'),
+ `a bin/cli.js whose package.json is not @claude-flow/cli is rejected (trap: ${trapped().split('\n')[0].slice(0, 60) || 'nothing'})`);
+ resetTrap();
+ const absent = run('bench.mjs', ['--op', 'verify', '--suite', suite], { ...baseEnv, RUFLO_METAHARNESS_SKIP_LOCAL: '1' });
+ assert(absent.status === 0 && absent.json?.degraded === true && absent.json?.reason === 'metaharness-darwin-not-available',
+ `darwin absent β†’ {degraded:true, reason:'metaharness-darwin-not-available'}, exit 0 (got ${absent.status}, ${absent.json?.reason})`);
+ resetTrap();
+
+ // ── Phase 5 β€” the resolution stays inside ruflo's own tree ───────────
+ // The darwin / redblue lookups END IN A SPAWN with MCP-supplied argv, so
+ // they pass { fromCwd: false } and must ignore a node_modules in the tool's
+ // cwd (or any ancestor of it). ISOLATED layout: plugin scripts under their
+ // own temp root, so the walk-up from the scripts finds no darwin/redblue at
+ // all and only the cwd copy could match.
+ console.log('\nPhase 5 β€” installed-copy lookup is scoped to ruflo, and a half-written cache is repaired');
+ const ISO = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-no-tool-time-npx-iso-')));
+ try {
+ const isoScripts = join(ISO, 'scripts');
+ mkdirSync(isoScripts, { recursive: true });
+ for (const f of readdirSync(PLUGIN_SCRIPTS)) copyFileSync(join(PLUGIN_SCRIPTS, f), join(isoScripts, f));
+ const isoProject = join(ISO, 'project');
+ mkdirSync(isoProject, { recursive: true });
+ const cwdDarwin = join(isoProject, 'node_modules', '@metaharness', 'darwin');
+ write(join(cwdDarwin, 'package.json'), JSON.stringify({ name: '@metaharness/darwin', version: darwinVersion, type: 'module', bin: { 'metaharness-darwin': './dist/cli.js' } }));
+ write(join(cwdDarwin, 'dist', 'cli.js'), echoStub('cwd-darwin', darwinVersion));
+ const cwdRedblue = join(isoProject, 'node_modules', '@metaharness', 'redblue');
+ write(join(cwdRedblue, 'package.json'), JSON.stringify({ name: '@metaharness/redblue', version: redblueVersion, type: 'module', bin: { redblue: './dist/cli/index.js' } }));
+ write(join(cwdRedblue, 'dist', 'cli', 'index.js'), echoStub('cwd-redblue', redblueVersion));
+ const isoEnv = { ...baseEnv, RUFLO_METAHARNESS_CACHE_BASE: join(ISO, 'empty-cache-base') };
+
+ const cwdBench = run('bench.mjs', ['--op', 'verify', '--suite', suite], isoEnv, isoScripts, isoProject);
+ assert(cwdBench.json?.data?.stub !== 'cwd-darwin',
+ `darwin in the tool's cwd node_modules is NOT executed (got stub ${cwdBench.json?.data?.stub ?? 'none'})`);
+ resetTrap();
+ const cwdRb = run('redblue.mjs', ['attack', 'prompt', '--count', '1'], isoEnv, isoScripts, isoProject);
+ assert(!/"stub":"cwd-redblue"/.test(cwdRb.json?.stdout ?? ''),
+ 'redblue in the tool\'s cwd node_modules is NOT executed');
+ resetTrap();
+
+ // A cache dir holding package.json but no bin (npm killed by the 180s
+ // install timeout, or two first calls racing into the same prefix) must
+ // not count as installed forever: one reinstall is attempted.
+ const halfCache = join(ISO, 'half-cache');
+ write(join(halfCache, `darwin-cache-${pinDigits}`, 'node_modules', '@metaharness', 'darwin', 'package.json'),
+ JSON.stringify({ name: '@metaharness/darwin', version: darwinVersion, type: 'module', bin: { 'metaharness-darwin': './dist/cli.js' } }));
+ const halfRun = run('bench.mjs', ['--op', 'verify', '--suite', suite], { ...isoEnv, RUFLO_METAHARNESS_CACHE_BASE: halfCache }, isoScripts, isoProject);
+ assert(/npm install/.test(trapped()), `a cache with package.json but no bin triggers one reinstall (trap: ${trapped().split('\n')[0].slice(0, 120) || 'nothing'})`);
+ assert(halfRun.status === 0 && halfRun.json?.degraded === true,
+ `…and still degrades with exit 0 when that reinstall fails (got ${halfRun.status}, degraded ${halfRun.json?.degraded})`);
+ resetTrap();
+ } finally {
+ rmSync(ISO, { recursive: true, force: true });
+ }
+
+ // Static: the resolved bins are spawned directly, never through a shell β€”
+ // their argv carries MCP-supplied values (redblue --config/--out/--in).
+ for (const f of ['_darwin.mjs', '_redblue.mjs']) {
+ const src = readFileSync(join(SCRIPTS_DIR, f), 'utf-8');
+ const code = src.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');
+ assert(!/shell:\s*(true|process\.platform)/.test(code), `${f} spawns the resolved bin with shell:false`);
+ }
+} finally {
+ rmSync(TMP, { recursive: true, force: true });
+}
+
+console.log(`\n${passed} passed, ${failed} failed`);
+if (failed > 0) {
+ console.log('\nFailures:');
+ for (const f of failures) console.log(` - ${f}`);
+ process.exit(1);
+}
+console.log('\nβœ“ No npm / npx at tool-call time when darwin, redblue and the ruflo CLI are installed.');
diff --git a/plugins/ruflo-metaharness/scripts/test-pin-alignment.mjs b/plugins/ruflo-metaharness/scripts/test-pin-alignment.mjs
new file mode 100755
index 0000000000..e27faf3e11
--- /dev/null
+++ b/plugins/ruflo-metaharness/scripts/test-pin-alignment.mjs
@@ -0,0 +1,182 @@
+#!/usr/bin/env node
+// test-pin-alignment.mjs β€” regression test for plugin helper pins that
+// drifted away from the ranges @claude-flow/cli declares (#3366).
+//
+// THE BUG
+// The plugin helpers carry their own tilde pins (_harness.mjs
+// METAHARNESS_PIN_VERSION, _darwin.mjs DARWIN_PIN_VERSION). Those pins decide
+// which INSTALLED copy `findLocalPackageDir()` accepts. They sat at ~0.3.0 /
+// ~0.8.0 while v3/@claude-flow/cli/package.json declared metaharness ^0.4.1 and
+// @metaharness/darwin ~0.10.2, so on a normal ruflo install every
+// metaharness_* tool call rejected the copy ruflo ships and ran
+// `npm install --prefix ~/.ruflo/metaharness-cache-0.3.0 metaharness@~0.3.0`
+// at TOOL-CALL time (a network download of an older release; `degraded` when
+// offline). scripts/check-metaharness-pins.mjs compared only the CLI's ranges,
+// so nothing noticed.
+//
+// WHAT THIS TEST PROVES (hermetic β€” no network, no real MetaHarness package)
+// Phase 1 each helper pin accepts the declared range's floor AND a later
+// patch in it, using the same `satisfiesTildeRange()` predicate
+// findLocalPackageDir() applies at runtime.
+// Phase 2 end-to-end in the PUBLISHED layout
+// (<prefix>/node_modules/@claude-flow/cli/plugins/ruflo-metaharness/
+// scripts, next to <prefix>/node_modules/metaharness at the declared
+// floor version): metaharnessResolution() reports source 'local',
+// score.mjs returns the installed copy's output, and NOT ONE
+// npm / npx process is spawned (a PATH trap logs any attempt).
+// The scripts are copied into that layout because resolution walks up from
+// the helper's own directory; in the repo checkout (plugins/ at the repo
+// root) the walk never reaches an installed CLI's node_modules.
+//
+// USAGE
+// node plugins/ruflo-metaharness/scripts/test-pin-alignment.mjs
+//
+// EXIT CODES
+// 0 all assertions passed (or skipped on win32 β€” the trap is POSIX sh)
+// 1 at least one assertion failed
+// 2 setup error
+
+import { spawnSync } from 'node:child_process';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
+const CLI_PKG_JSON = join(SCRIPTS_DIR, '..', '..', '..', 'v3', '@claude-flow', 'cli', 'package.json');
+
+if (process.platform === 'win32') {
+ console.log('# test-pin-alignment β€” SKIPPED on win32 (the npm/npx trap is a POSIX sh script)');
+ process.exit(0);
+}
+if (!existsSync(CLI_PKG_JSON)) {
+ console.error(`test-pin-alignment: ${CLI_PKG_JSON} not found β€” run from a ruflo repo checkout`);
+ process.exit(2);
+}
+
+let passed = 0, failed = 0;
+const failures = [];
+function assert(cond, label) {
+ console.log(` ${cond ? 'βœ“' : 'βœ—'} ${label}`);
+ if (cond) passed++;
+ else { failures.push(label); failed++; }
+}
+
+/** Same lookup order as scripts/check-metaharness-pins.mjs. */
+function declaredRange(pkgJson, name) {
+ for (const where of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
+ if (pkgJson[where]?.[name]) return pkgJson[where][name];
+ }
+ return null;
+}
+function floorOf(range) {
+ const m = /^[~^]?(\d+)\.(\d+)\.(\d+)/.exec(String(range));
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
+}
+
+const cliPkg = JSON.parse(readFileSync(CLI_PKG_JSON, 'utf-8'));
+const { satisfiesTildeRange } = await import(pathToFileURL(join(SCRIPTS_DIR, '_invoke.mjs')).href);
+const { METAHARNESS_VERSION_PIN } = await import(pathToFileURL(join(SCRIPTS_DIR, '_harness.mjs')).href);
+const { DARWIN_VERSION_PIN } = await import(pathToFileURL(join(SCRIPTS_DIR, '_darwin.mjs')).href);
+const pinOf = (full) => full.slice(full.lastIndexOf('@') + 1);
+
+console.log('# test-pin-alignment\n');
+
+// ──────────────────────────────────────────────────────────────────────
+// Phase 1 β€” every helper pin accepts what the CLI declares
+// ──────────────────────────────────────────────────────────────────────
+console.log('Phase 1 β€” helper pins accept the versions @claude-flow/cli declares');
+const PINS = [
+ { pkg: 'metaharness', helper: '_harness.mjs', pin: pinOf(METAHARNESS_VERSION_PIN) },
+ { pkg: '@metaharness/darwin', helper: '_darwin.mjs', pin: pinOf(DARWIN_VERSION_PIN) },
+];
+const floors = {};
+for (const p of PINS) {
+ const declared = declaredRange(cliPkg, p.pkg);
+ const floor = floorOf(declared);
+ assert(!!floor, `${p.pkg}: declared in v3/@claude-flow/cli/package.json (got ${declared})`);
+ if (!floor) continue;
+ floors[p.pkg] = floor.join('.');
+ const laterPatch = [floor[0], floor[1], floor[2] + 100].join('.');
+ assert(satisfiesTildeRange(floors[p.pkg], p.pin),
+ `${p.helper} pin ${p.pin} accepts ${floors[p.pkg]} (floor of declared ${declared})`);
+ assert(satisfiesTildeRange(laterPatch, p.pin),
+ `${p.helper} pin ${p.pin} accepts ${laterPatch} (a later patch inside declared ${declared})`);
+}
+
+// ──────────────────────────────────────────────────────────────────────
+// Phase 2 β€” published layout: the installed copy is used, nothing downloads
+// ──────────────────────────────────────────────────────────────────────
+console.log('\nPhase 2 β€” published layout resolves the installed metaharness without npm/npx');
+// realpath: macOS tmpdir() is /var/… while resolved paths come back as /private/var/…
+const TMP = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-pin-alignment-')));
+try {
+ const NM = join(TMP, 'node_modules');
+ const PLUGIN_SCRIPTS = join(NM, '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts');
+ mkdirSync(PLUGIN_SCRIPTS, { recursive: true });
+ for (const f of readdirSync(SCRIPTS_DIR)) {
+ if (f.endsWith('.mjs')) copyFileSync(join(SCRIPTS_DIR, f), join(PLUGIN_SCRIPTS, f));
+ }
+
+ // Stub `metaharness` at the declared floor: both bins echo a marker JSON.
+ const mhVersion = floors.metaharness ?? '0.0.0';
+ const MH = join(NM, 'metaharness');
+ mkdirSync(join(MH, 'dist'), { recursive: true });
+ writeFileSync(join(MH, 'package.json'), JSON.stringify({
+ name: 'metaharness', version: mhVersion, type: 'module',
+ bin: { metaharness: 'dist/bin.js', harness: 'dist/harness-bin.js' },
+ }, null, 2));
+ for (const [file, bin] of [['bin.js', 'metaharness'], ['harness-bin.js', 'harness']]) {
+ writeFileSync(join(MH, 'dist', file),
+ `console.log(JSON.stringify({ stub: '${bin}', version: '${mhVersion}', argv: process.argv.slice(2) }));\n`);
+ }
+
+ // npm / npx trap: log the attempt, fail like an offline machine would.
+ const TRAP = join(TMP, 'trap-bin');
+ const TRAP_LOG = join(TMP, 'trap.log');
+ mkdirSync(TRAP);
+ for (const t of ['npm', 'npx']) {
+ writeFileSync(join(TRAP, t), `#!/bin/sh\nprintf '%s %s\\n' "${t}" "$*" >> "${TRAP_LOG}"\necho "npm ERR! ${t} blocked by test-pin-alignment trap" >&2\nexit 1\n`);
+ chmodSync(join(TRAP, t), 0o755);
+ }
+ const PROJECT = join(TMP, 'project');
+ mkdirSync(PROJECT);
+ const env = {
+ ...process.env,
+ PATH: `${TRAP}:${process.env.PATH}`,
+ RUFLO_METAHARNESS_CACHE_BASE: join(TMP, 'empty-cache-base'),
+ };
+ delete env.RUFLO_METAHARNESS_SKIP_LOCAL;
+ const run = (args) => spawnSync(process.execPath, args, { cwd: PROJECT, env, encoding: 'utf-8', timeout: 60_000 });
+
+ const probe = run(['--input-type=module', '-e',
+ `const m = await import(${JSON.stringify(pathToFileURL(join(PLUGIN_SCRIPTS, '_harness.mjs')).href)});` +
+ 'console.log(JSON.stringify(m.metaharnessResolution()));']);
+ let resolution = null;
+ try { resolution = JSON.parse(probe.stdout.trim().split('\n').pop()); } catch { /* asserted below */ }
+ assert(resolution?.ok === true && resolution?.source === 'local',
+ `metaharnessResolution() β†’ source 'local' (got ${JSON.stringify(resolution)})`);
+ assert(typeof resolution?.bins?.metaharness === 'string' && resolution.bins.metaharness.startsWith(MH),
+ 'resolved metaharness bin is the installed copy next to @claude-flow/cli');
+
+ const score = run([join(PLUGIN_SCRIPTS, 'score.mjs'), '--path', PROJECT, '--format', 'json']);
+ let payload = null;
+ try { payload = JSON.parse(score.stdout); } catch { /* asserted below */ }
+ assert(score.status === 0, `score.mjs exits 0 (got ${score.status})`);
+ assert(payload?.degraded !== true, `score.mjs is not degraded (reason: ${payload?.reason ?? 'none'})`);
+ assert(payload?.stub === 'metaharness' && payload?.version === mhVersion,
+ `score.mjs ran the installed metaharness ${mhVersion}`);
+
+ const trapped = existsSync(TRAP_LOG) ? readFileSync(TRAP_LOG, 'utf-8').trim() : '';
+ assert(trapped === '', `no npm / npx process spawned${trapped ? ` (got: ${trapped.split('\n')[0]})` : ''}`);
+} finally {
+ rmSync(TMP, { recursive: true, force: true });
+}
+
+console.log(`\n${passed} passed, ${failed} failed`);
+if (failed > 0) {
+ console.log('\nFailures:');
+ for (const f of failures) console.log(` - ${f}`);
+ process.exit(1);
+}
+console.log('\nβœ“ Plugin helper pins accept the versions @claude-flow/cli declares; no tool-time download.');
diff --git a/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md b/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md
index 3f9cb4e220..f224e45955 100644
--- a/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md
@@ -35,8 +35,10 @@ Implementation: [`scripts/evolve.mjs`](../../scripts/evolve.mjs).
≀ 20, `--concurrency` ≀ 8, sandbox/selection/mutator are known values).
2. Without `--confirm`: print plan + exit 0 (mirrors `harness-mint` safety
convention; defense in depth over the upstream `safety.ts` checks).
-3. With `--confirm`: shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin evolve <repo> ...`
- via the shared `_darwin.mjs` async helper. Per-generation progress is
+3. With `--confirm`: run `metaharness-darwin evolve <repo> ...` from the installed
+ `@metaharness/darwin` (pin in `_darwin.mjs`; one-time `~/.ruflo/darwin-cache-<pin>`
+ install only if no installed copy qualifies β€” never npx) via the shared
+ `_darwin.mjs` async helper. Per-generation progress is
forwarded to stderr; final champion JSON is captured from stdout.
4. Compute timeout from `generations Γ— children Γ— per-variant` (per-variant
β‰ˆ 60s real, β‰ˆ 2s mock). Caller may override with `--timeout-ms`.
diff --git a/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md b/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md
index fee5fe177a..a930fcb50c 100644
--- a/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md
@@ -39,7 +39,7 @@ cross a subprocess boundary. Two supported paths instead:
Implementation: [`scripts/gepa.mjs`](../../scripts/gepa.mjs).
1. `import('@metaharness/darwin/gepa')`; on MODULE_NOT_FOUND fall back to a
- one-time `npm install --prefix ~/.ruflo/darwin-cache-0.8.0` and import
+ one-time `npm install --prefix ~/.ruflo/darwin-cache-<pin>` and import
the cached `dist/gepa/index.js` (versioned dir β†’ pin bumps invalidate).
2. Dispatch `--op`:
- `genome` β†’ `loadGenome(fs, path)` or `loadCand6Genome()` + `validateGenome`
diff --git a/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md b/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md
index f8452e8d23..46fed06da3 100644
--- a/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md
@@ -41,7 +41,7 @@ ADR-235 follow-up and not available yet.
Implementation: [`scripts/learn.mjs`](../../scripts/learn.mjs).
1. Validate `--repo` exists when given; export it as `$METAHARNESS_REPO`.
-2. Invoke the pinned `metaharness` binary (`metaharness@~0.3.0`, local install
+2. Invoke the pinned `metaharness` binary (`metaharness@~0.4.1`, local install
or one-time versioned cache β€” never `@latest`): `metaharness learn --host <h>
--model <m> --slice <s> [--run]` via `_harness.mjs` (graceful degradation,
hard timeout).
diff --git a/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md b/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md
index bfcf162fd6..9322e92b9c 100644
--- a/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md
@@ -13,7 +13,7 @@ tool; pure static analysis.
Implementation: [`scripts/mcp-scan.mjs`](../../scripts/mcp-scan.mjs).
-1. Invoke the pinned `harness` binary (`metaharness@~0.3.0`, resolved from a
+1. Invoke the pinned `harness` binary (`metaharness@~0.4.1`, resolved from a
local install or the one-time `~/.ruflo/metaharness-cache-<pin>` cache β€”
never `@latest`): `harness mcp-scan <path> --json`.
2. Parse `findings[]` with `{ severity, id, server, tool, message }`.
diff --git a/plugins/ruflo-metaharness/skills/harness-score/SKILL.md b/plugins/ruflo-metaharness/skills/harness-score/SKILL.md
index addce65184..7cd356ad05 100644
--- a/plugins/ruflo-metaharness/skills/harness-score/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-score/SKILL.md
@@ -58,7 +58,7 @@ no network, registry unreachable), the script emits:
{
"degraded": true,
"reason": "metaharness-not-available",
- "hint": "Install with `npm i -D metaharness@~0.3.0` (pinned range β€” this plugin never fetches @latest) or verify network access for the one-time cache install."
+ "hint": "Install with `npm i -D metaharness@~0.4.1` (pinned range β€” this plugin never fetches @latest) or verify network access for the one-time cache install."
}
```
diff --git a/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md b/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md
index e00c1e0bb0..9a19e1d9f0 100644
--- a/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md
@@ -29,7 +29,9 @@ ground-truth set. Running this nightly gives us:
Implementation: [`scripts/security-bench.mjs`](../../scripts/security-bench.mjs).
-1. Shell to `npx -y @metaharness/darwin@~0.8.0 metaharness-darwin security bench --population N --cycles N [--seed S]`.
+1. Run `metaharness-darwin security bench --population N --cycles N [--seed S]` from the
+ installed `@metaharness/darwin` (pin in `_darwin.mjs`; one-time cache install only if
+ no installed copy qualifies β€” never npx).
2. Default timeout = `3s Γ— 19 evaluations Γ— population Γ— cycles + 30s overhead`.
At default `--population 2 --cycles 1` β‰ˆ 144s; at `--population 4 --cycles 3` β‰ˆ 12 min.
3. Parse the markdown report β€” overall PASS/FAIL plus per-gate
diff --git a/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md b/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md
index 8365e921e2..da30872ef1 100644
--- a/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md
+++ b/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md
@@ -13,7 +13,7 @@ categorized report suitable for sharing with an InfoSec team.
Implementation: [`scripts/threat-model.mjs`](../../scripts/threat-model.mjs).
-1. Invoke the pinned `harness` binary (`metaharness@~0.3.0`, resolved from a
+1. Invoke the pinned `harness` binary (`metaharness@~0.4.1`, resolved from a
local install or the one-time `~/.ruflo/metaharness-cache-<pin>` cache β€”
never `@latest`): `harness threat-model <path> --json`.
2. Parse `{ worst, findings[] }`.
diff --git a/scripts/check-metaharness-pins.mjs b/scripts/check-metaharness-pins.mjs
index 6827edc553..cc266c120f 100644
--- a/scripts/check-metaharness-pins.mjs
+++ b/scripts/check-metaharness-pins.mjs
@@ -30,14 +30,36 @@
// for the Tier-1 oracle's `npx @metaharness/darwin@<pin>` calls) must satisfy
// the declared @metaharness/darwin range, so the two can't drift apart.
//
+// Plus the ruflo-metaharness PLUGIN helper pins (#3366). The metaharness_* MCP
+// tools never read package.json: each helper in plugins/ruflo-metaharness/
+// scripts/ carries its own tilde range, and that range alone decides which
+// INSTALLED copy the helper accepts (_invoke.findLocalPackageDir) and what it
+// npm-installs at tool-call time when no copy qualifies (ensureCachedInstall).
+// This watcher used to compare only the CLI's declared ranges, so the helper
+// pins drifted unseen (_harness.mjs ~0.3.0 vs declared ^0.4.1; _darwin.mjs
+// ~0.8.0 vs declared ~0.10.2) and every tool call re-downloaded an older
+// release while the one ruflo shipped sat unused on disk. Rules:
+// - the helper pin must be `~X.Y.Z` β€” _invoke.satisfiesTildeRange(), the
+// predicate the helpers actually apply, parses nothing else, so a `^` or
+// exact pin rejects every installed copy even though covers() below would
+// call it green
+// - package declared by the CLI β†’ the helper range must COVER the declared
+// range (accept every version a clean install can put on disk); offline-safe
+// - package not declared (redblue) β†’ the helper range must admit npm latest
+// - constant not found in the helper β†’ fatal (the watcher cannot protect a
+// pin it cannot read β€” same stance as UNDECLARED above)
+//
// USAGE
// node scripts/check-metaharness-pins.mjs # exits 1 if any pin is stale
// node scripts/check-metaharness-pins.mjs --format json # CI/issue-body consumable
// node scripts/check-metaharness-pins.mjs --offline # skip npm, only lock-step check
//
// EXIT CODES
-// 0 every pin's range admits npm latest (and the darwin constant is in range)
+// 0 every pin's range admits npm latest (and the darwin constant is in range,
+// and every plugin helper pin covers its declared range)
// 1 at least one pin is behind (range excludes latest) OR constant out of range
+// OR a plugin helper pin no longer covers its declared range / is not a
+// tilde range / is unreadable
// 2 unexpected error (network flake surfaces as a warning, NOT a false drift)
import { readFileSync } from 'node:fs';
@@ -49,6 +71,13 @@ const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = join(HERE, '..');
const CLI_PKG = join(REPO, 'v3', '@claude-flow', 'cli', 'package.json');
const DISTILL = join(REPO, 'v3', '@claude-flow', 'cli', 'src', 'services', 'distill-oracle.ts');
+const PLUGIN_SCRIPTS = join(REPO, 'plugins', 'ruflo-metaharness', 'scripts');
+// The plugin helper constants that pick what the metaharness_* tools run.
+const PLUGIN_PINS = [
+ { name: 'metaharness', file: '_harness.mjs', constant: 'METAHARNESS_PIN_VERSION' },
+ { name: '@metaharness/darwin', file: '_darwin.mjs', constant: 'DARWIN_PIN_VERSION' },
+ { name: '@metaharness/redblue', file: '_redblue.mjs', constant: 'REDBLUE_PIN_VERSION' },
+];
const ARGS = { format: 'table', offline: false, requireInstalled: false };
for (let i = 2; i < process.argv.length; i++) {
@@ -63,21 +92,33 @@ function parseVer(v) {
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
}
-/** Does `latest` satisfy `range`? Supports the caret/tilde/exact forms ruflo uses. */
-function satisfies(range, latest) {
- const lv = parseVer(latest);
- if (!lv) return null;
+/** Half-open [lo, hi) bounds of the caret/tilde/exact forms ruflo uses; null if unparseable. */
+function bounds(range) {
const op = range[0] === '^' || range[0] === '~' ? range[0] : '=';
- const bv = parseVer(op === '=' ? range : range.slice(1));
- if (!bv) return null;
- const gte = cmp(lv, bv) >= 0;
- if (!gte) return false;
- if (op === '=') return cmp(lv, bv) === 0;
+ const lo = parseVer(op === '=' ? range : range.slice(1));
+ if (!lo) return null;
// Upper bound: caret locks the left-most non-zero component; tilde locks minor.
let hi;
- if (op === '^') hi = bv[0] > 0 ? [bv[0] + 1, 0, 0] : bv[1] > 0 ? [0, bv[1] + 1, 0] : [0, 0, bv[2] + 1];
- else hi = [bv[0], bv[1] + 1, 0]; // ~
- return cmp(lv, hi) < 0;
+ if (op === '=') hi = [lo[0], lo[1], lo[2] + 1];
+ else if (op === '^') hi = lo[0] > 0 ? [lo[0] + 1, 0, 0] : lo[1] > 0 ? [0, lo[1] + 1, 0] : [0, 0, lo[2] + 1];
+ else hi = [lo[0], lo[1] + 1, 0]; // ~
+ return { lo, hi };
+}
+
+/** Does `latest` satisfy `range`? Supports the caret/tilde/exact forms ruflo uses. */
+function satisfies(range, latest) {
+ const lv = parseVer(latest);
+ const b = bounds(range);
+ if (!lv || !b) return null;
+ return cmp(lv, b.lo) >= 0 && cmp(lv, b.hi) < 0;
+}
+
+/** Does `outer` admit every version `inner` admits? (plugin helper pin vs declared range) */
+function covers(outer, inner) {
+ const o = bounds(outer);
+ const i = bounds(inner);
+ if (!o || !i) return null;
+ return cmp(o.lo, i.lo) <= 0 && cmp(i.hi, o.hi) <= 0;
}
function cmp(a, b) { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] - b[i]; return 0; }
@@ -137,6 +178,41 @@ async function main() {
}
} catch { /* non-fatal */ }
+ // Plugin helper pins (#3366): what the metaharness_* tools actually resolve
+ // and install. Declared by the CLI β†’ must cover the declared range (no
+ // network needed); otherwise β†’ must admit npm latest, like the rows above.
+ const pluginRows = [];
+ for (const p of PLUGIN_PINS) {
+ const row = { name: `${p.constant} (plugins/ruflo-metaharness/scripts/${p.file})`, package: p.name, pin: null, declared: null };
+ try {
+ const m = readFileSync(join(PLUGIN_SCRIPTS, p.file), 'utf-8').match(new RegExp(`${p.constant}\\s*=\\s*['"]([^'"]+)['"]`));
+ if (m) row.pin = m[1];
+ } catch { /* unreadable β€” reported below */ }
+ if (!row.pin) { pluginRows.push({ ...row, status: 'UNREADABLE', note: `${p.constant} not found in ${p.file} β€” the watcher cannot protect a pin it cannot read` }); continue; }
+ // The helpers match installed copies with _invoke.satisfiesTildeRange(),
+ // which parses ONLY `~X.Y.Z` and returns false for everything else. A
+ // `^`/exact/`latest` pin would therefore reject every installed copy and
+ // npm-install on each call, while covers()/satisfies() below β€” which do
+ // understand those forms β€” reported the row green. Fail closed instead.
+ if (!/^~\d+\.\d+\.\d+$/.test(row.pin)) {
+ pluginRows.push({ ...row, status: 'NOT-TILDE', note: `${row.pin} is not \`~X.Y.Z\`; _invoke.satisfiesTildeRange() accepts no other form, so every installed copy would be rejected` });
+ continue;
+ }
+ row.declared = declaredRange(pkg, p.name).range ?? null;
+ if (row.declared) {
+ const ok = covers(row.pin, row.declared);
+ pluginRows.push({ ...row, status: ok === false ? 'NOT-COVERED' : ok === true ? 'covers' : 'unparseable' });
+ continue;
+ }
+ if (ARGS.offline) { pluginRows.push({ ...row, status: 'skipped', note: 'not declared by the CLI; offline mode' }); continue; }
+ let latest;
+ try { latest = npmLatest(p.name); }
+ catch { pluginRows.push({ ...row, status: 'unknown', note: 'npm view failed (network?) β€” not treated as drift' }); continue; }
+ const ok = satisfies(row.pin, latest);
+ pluginRows.push({ ...row, latest, status: ok === false ? 'STALE' : ok === true ? 'current' : 'unparseable' });
+ }
+ const pluginBad = pluginRows.filter((r) => ['NOT-COVERED', 'NOT-TILDE', 'UNREADABLE', 'STALE', 'unparseable'].includes(r.status));
+
const stale = rows.filter((r) => r.status === 'STALE' || r.status === 'UNDECLARED' || r.status === 'PEER-ONLY');
const constBad = constRow && constRow.status === 'OUT-OF-RANGE';
const apiErrors = [];
@@ -163,12 +239,13 @@ async function main() {
}
}
}
- const drift = stale.length > 0 || constBad || apiErrors.length > 0;
+ const drift = stale.length > 0 || constBad || pluginBad.length > 0 || apiErrors.length > 0;
const payload = {
generatedAt: new Date().toISOString(),
drift,
pins: rows,
constCheck: constRow,
+ pluginPins: pluginRows,
installedApiChecked: ARGS.requireInstalled,
apiErrors,
};
@@ -181,14 +258,15 @@ async function main() {
console.log('|---|---|---|---|---|');
for (const r of rows) console.log(`| ${r.name} | ${r.range ?? 'β€”'} | ${r.where ?? 'β€”'} | ${r.latest ?? 'β€”'} | ${r.status} |`);
if (constRow) console.log(`| ${constRow.name} | =${constRow.pin} (vs ${constRow.declared}) | β€” | β€” | ${constRow.status} |`);
+ for (const r of pluginRows) console.log(`| ${r.name} | ${r.pin ?? 'β€”'}${r.declared ? ` (vs ${r.declared})` : ''} | plugin | ${r.latest ?? 'β€”'} | ${r.status} |`);
if (ARGS.requireInstalled) console.log(`\nInstalled API check: ${apiErrors.length ? `FAIL β€” ${apiErrors.join('; ')}` : 'PASS'}`);
console.log('');
if (drift) {
- console.log('⚠ **Pin drift detected.** A metaharness pin is stale, undeclared, or declared peer-only.');
+ console.log('⚠ **Pin drift detected.** A metaharness pin is stale, undeclared, declared peer-only, or a plugin helper pin no longer covers it (or is not a `~X.Y.Z` range).');
console.log('Fix the declaration in v3/@claude-flow/cli/package.json (installable pins belong in optionalDependencies;');
- console.log('bump MH_DARWIN_PIN if darwin moved), then re-run.');
+ console.log('bump MH_DARWIN_PIN if darwin moved, and the *_PIN_VERSION constants in plugins/ruflo-metaharness/scripts/), then re-run.');
} else {
- console.log('βœ“ All metaharness pins are declared installably and admit the current npm `latest`.');
+ console.log('βœ“ All metaharness pins are declared installably and admit the current npm `latest`; plugin helper pins cover them.');
}
}
process.exit(drift ? 1 : 0);
diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
index 40322b93b7..d3db1f0869 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
@@ -387,7 +387,7 @@ export const metaharnessTools: MCPTool[] = [
},
// ───────────────────────────────────────────────────────────────────────
// ADR-153 β€” @metaharness/darwin integration (3 tools).
- // Backed by the separate `@metaharness/darwin@~0.8.0` npm package, NOT
+ // Backed by the separate `@metaharness/darwin@~0.10.2` npm package, NOT
// the umbrella `metaharness`. Plugin scripts shell out via _darwin.mjs.
// Same {success, data, degraded, exitCode} contract.
// ───────────────────────────────────────────────────────────────────────
diff --git a/v3/@claude-flow/cli/src/services/distill-oracle.ts b/v3/@claude-flow/cli/src/services/distill-oracle.ts
index e227344a34..8c41637d56 100644
--- a/v3/@claude-flow/cli/src/services/distill-oracle.ts
+++ b/v3/@claude-flow/cli/src/services/distill-oracle.ts
@@ -51,7 +51,8 @@ import {
// behavior mid-run (the #142 pin-drift failure mode). Pin it, and let
// scripts/check-metaharness-pins.mjs watch this constant for drift. Kept in
// lock-step with the optionalDependencies pin in package.json and the plugin
-// darwin cache (versioned by the plugin's own `~0.8.0` pin in _darwin.mjs).
+// darwin cache (versioned by the plugin's own `~0.10.2` pin in _darwin.mjs;
+// both are checked by scripts/check-metaharness-pins.mjs β€” #3366).
export const MH_DARWIN_PIN = '0.10.2';
// ── Provenance ─────────────────────────────────────────────────────────────