π 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(cli,plugins): resolve executed optional modules from the tool's own install
Dragan Spiridonov4c95a6a1b605
diff --git a/plugins/ruflo-cost-tracker/scripts/compact.mjs b/plugins/ruflo-cost-tracker/scripts/compact.mjsindex ea9da3cef6..03a741daa4 100755--- a/plugins/ruflo-cost-tracker/scripts/compact.mjs+++ b/plugins/ruflo-cost-tracker/scripts/compact.mjs@@ -4,11 +4,10 @@// inlined Node one-liner.//// Resolution strategy (#1930): pnpm-workspace marketplace installs don't-// hoist `@claude-flow/integration` into `v3/node_modules/`, so resolving-// from cwd alone breaks. Try, in order:-// 1. createRequire(cwd) β works for npm-style hoisted installs-// 2. createRequire(script-dir) β works when run from inside the plugin-// 3. absolute path from this file β works on the marketplace layout+// hoist `@claude-flow/integration` into `v3/node_modules/`. The resolved+// module is imported, so it never comes from the cwd (the project). Try:+// 1. createRequire(script-dir) β works when run from inside the plugin+// 2. absolute path from this file β works on the marketplace layout// (script lives at <ruflo>/plugins/ruflo-cost-tracker/scripts/, the// integration package at <ruflo>/v3/@claude-flow/integration/)//@@ -68,9 +67,9 @@ async function main() {process.exit(2);}- // Resolution chain β cwd β script dir β absolute fallback (#1930 step 5)+ // Resolution chain β script dir β absolute fallback (#1930 step 5). Not the+ // cwd: the module found here is imported, and the cwd is the project.const candidates = [- tryResolveFrom(join(process.cwd(), 'package.json')),tryResolveFrom(join(__dirname, 'package.json')),tryAbsolutePath(),].filter(Boolean);@@ -104,7 +103,7 @@ async function main() {memoriesRetrieved: 0,tokensSaved: 0,agenticFlowAvailable: false,- hint: 'Tried cwd, script dir, and absolute path from this script β see #1930 for full troubleshooting.',+ hint: 'Tried the script dir and the absolute path from this script β see #1930 for full troubleshooting.',};if (process.env.COMPACT_QUIET === '1') return console.log(JSON.stringify(out));console.log(`# cost-compact-context\n\nbridge unavailable: ${reason}`);diff --git a/plugins/ruflo-ruos/scripts/lib/ledger.mjs b/plugins/ruflo-ruos/scripts/lib/ledger.mjsindex aa9b58e753..22437bcfa5 100644--- a/plugins/ruflo-ruos/scripts/lib/ledger.mjs+++ b/plugins/ruflo-ruos/scripts/lib/ledger.mjs@@ -55,7 +55,9 @@ export function projectCwd(env) {/*** Locate ruflo's in-process tool dispatcher without depending on it.- * @param {string} cwd+ * The dispatcher is imported, so it resolves from this plugin's own install+ * (or an explicit RUFLO_CLI_MCP_CLIENT), never from the project cwd.+ * @param {string} cwd kept for callers; not used for module resolution* @param {NodeJS.ProcessEnv} env* @returns {Promise<CallTool|null>}*/@@ -63,7 +65,7 @@ export async function resolveCallTool(cwd, env) {const candidates = [];if (env.RUFLO_CLI_MCP_CLIENT) candidates.push(env.RUFLO_CLI_MCP_CLIENT);try {- const req = createRequire(join(cwd, 'noop.js'));+ const req = createRequire(import.meta.url);for (const pkg of ['@claude-flow/cli', 'ruflo', 'claude-flow']) {try {const pj = req.resolve(`${pkg}/package.json`);diff --git a/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.tsnew file mode 100644index 0000000000..98e762d447--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/optional-module-resolution-trust.test.ts@@ -0,0 +1,109 @@+/**+ * The CLI, its MCP tools and plugin scripts load optional modules and plugin+ * scripts that they then execute. Those must resolve from the tool's own+ * install (or the user's marketplace checkout), never from the cwd: the cwd+ * is the opened project, and a project must not choose code that runs.+ */+import { afterEach, describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const here = dirname(fileURLToPath(import.meta.url));+const REPO = resolve(here, '../../../..');+const tempRoots: string[] = [];++afterEach(() => {+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++function scratch(): string {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-optional-module-')));+ tempRoots.push(root);+ return root;+}++function write(file: string, content: string) {+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, content);+}++/** Source of `function name(...) { ... }` up to the next top-level closing brace. */+function fnSource(file: string, name: string): string {+ const source = readFileSync(resolve(REPO, file), 'utf8');+ const start = source.search(new RegExp(`function ${name}\\(`));+ expect(start, `${name} in ${file}`).toBeGreaterThan(-1);+ return source.slice(start, source.indexOf('\n}\n', start));+}++describe('locators of executed modules never consult the cwd', () => {+ const cases: Array<[string, string]> = [+ ['v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts', 'locateTestgenScripts'],+ ['v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts', 'locatePluginScripts'],+ ['v3/@claude-flow/cli/src/commands/metaharness.ts', 'locatePluginScripts'],+ ['v3/@claude-flow/cli/src/commands/doctor.ts', 'checkMetaharnessIntegration'],+ ['v3/@claude-flow/cli/src/commands/init.ts', 'resolveCodexInitializer'],+ ['plugins/ruflo-ruos/scripts/lib/ledger.mjs', 'resolveCallTool'],+ ];+ for (const [file, name] of cases) {+ it(`${file} ${name}()`, () => {+ // Comments may still describe the old cwd lookup; only code counts.+ const body = fnSource(file, name).split('\n').filter((l) => !/^\s*(\/\/|\*)/.test(l)).join('\n');+ expect(body).not.toMatch(/process\.cwd\(\)|getProjectCwd\(\)|join\(cwd,/);+ });+ }++ it('embedding-service resolves agentic-flow from its own package only', () => {+ const source = readFileSync(resolve(REPO, 'v3/@claude-flow/embeddings/src/embedding-service.ts'), 'utf8');+ expect(source).not.toContain("path.join(cwd, 'node_modules/agentic-flow");+ expect(source).not.toContain('/workspaces/claude-flow/node_modules');+ expect(source).toContain("require.resolve('agentic-flow/package.json')");+ });++ it('compact.mjs does not resolve the token optimizer from the cwd', () => {+ const source = readFileSync(resolve(REPO, 'plugins/ruflo-cost-tracker/scripts/compact.mjs'), 'utf8');+ expect(source).not.toContain("tryResolveFrom(join(process.cwd(), 'package.json'))");+ });+});++describe('ruflo-ruos resolveCallTool at runtime', () => {+ it("never imports a dispatcher planted in the project's node_modules", async () => {+ const project = scratch();+ const marker = join(project, 'planted-dispatcher-ran');+ const planted = `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, '1');\nexport function callMCPTool() {}\n`;+ write(join(project, 'node_modules', '@claude-flow', 'cli', 'package.json'), JSON.stringify({ name: '@claude-flow/cli', type: 'module' }));+ write(join(project, 'node_modules', '@claude-flow', 'cli', 'dist', 'src', 'mcp-client.js'), planted);++ const { resolveCallTool } = await import(pathToFileURL(resolve(REPO, 'plugins/ruflo-ruos/scripts/lib/ledger.mjs')).href);+ await resolveCallTool(project, {});++ expect(existsSync(marker)).toBe(false);+ });+});++describe('cost-tracker compact.mjs at runtime', () => {+ it("never imports a token optimizer planted in the project's node_modules", () => {+ const project = scratch();+ const marker = join(project, 'planted-optimizer-ran');+ const pkg = join(project, 'node_modules', '@claude-flow', 'integration');+ write(join(pkg, 'package.json'), JSON.stringify({+ name: '@claude-flow/integration',+ type: 'module',+ exports: { './token-optimizer': './token-optimizer.js' },+ }));+ write(join(pkg, 'token-optimizer.js'), `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, '1');\n`);+ write(join(project, 'package.json'), JSON.stringify({ name: 'untrusted' }));++ const result = spawnSync(process.execPath, [resolve(REPO, 'plugins/ruflo-cost-tracker/scripts/compact.mjs'), 'query'], {+ cwd: project,+ env: { ...process.env, COMPACT_QUIET: '1' },+ encoding: 'utf8',+ timeout: 60_000,+ });++ expect(result.error).toBeUndefined();+ expect(existsSync(marker)).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.tsindex ffddd0112d..6be2781f6d 100644--- a/v3/@claude-flow/cli/src/commands/doctor.ts+++ b/v3/@claude-flow/cli/src/commands/doctor.ts@@ -2113,7 +2113,9 @@ async function checkMetaharnessIntegration(): Promise<HealthCheck> {// (dev) until we find a directory containing `plugins/ruflo-metaharness/`.const candidates: string[] = [];- // Strategy 1: walk up from this module's own URL β covers npx + global install.+ // Walk up from this module's own URL β covers npx, global and project-local+ // installs and monorepo dev. The plugin found here is imported below, so it+ // must come from this CLI's own install, never from the cwd (the project).try {const selfDir = dirname(fileURLToPath(import.meta.url));let q = selfDir;@@ -2122,19 +2124,9 @@ async function checkMetaharnessIntegration(): Promise<HealthCheck> {q = dirname(q);}} catch {- // import.meta.url unavailable under some bundlers β fall through to cwd walk.+ // import.meta.url unavailable under some bundlers β the plugin is reported absent.}- // Strategy 2: walk up from cwd β covers monorepo dev (running from a sub-package).- let p = process.cwd();- for (let i = 0; i < 8; i++) {- candidates.push(join(p, 'plugins', 'ruflo-metaharness'));- p = dirname(p);- }-- // Strategy 3: explicit node_modules path relative to cwd β covers project-local install.- candidates.push(join(process.cwd(), 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness'));-let pluginDir: string | null = null;for (const c of candidates) {if (existsSync(join(c, 'scripts', '_harness.mjs'))) {diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.tsindex 1db08afa47..1956ac4fee 100644--- a/v3/@claude-flow/cli/src/commands/init.ts+++ b/v3/@claude-flow/cli/src/commands/init.ts@@ -75,16 +75,9 @@ async function resolveCodexInitializer(cwd: string): Promise<CodexInitializerCtoconst resolutionStrategies = [// Strategy 1: Direct import (works if installed as CLI dependency)async () => (await import(codexModuleId)).CodexInitializer,- // Strategy 2: Project node_modules (works if installed in user's project)- async () => {- const projectPath = path.join(cwd, 'node_modules', '@claude-flow', 'codex', 'dist', 'index.js');- if (fs.existsSync(projectPath)) {- const mod = await import(`file://${projectPath}`);- return mod.CodexInitializer;- }- throw new Error('Not found in project');- },- // Strategy 3: Global node_modules+ // (No project node_modules strategy: init must not import code the+ // target project supplies.)+ // Strategy 2: Global node_modulesasync () => {const { execSync } = await import('child_process');const globalPath = execSync('npm root -g', { encoding: 'utf-8' }).trim();diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.tsindex c13f83ee2b..2f4804173c 100644--- a/v3/@claude-flow/cli/src/commands/metaharness.ts+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts@@ -40,6 +40,7 @@ import { spawnSync } from 'child_process';import { existsSync, readFileSync } from 'fs';import { join, dirname, resolve } from 'path';import { fileURLToPath } from 'url';+import { homedir } from 'os';import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';import {listFlywheelReceipts,@@ -227,12 +228,10 @@ function locatePluginScripts(requiredScript?: string): string | null {candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts'));p = dirname(p);}- // Also try from cwd (covers the "npx ruflo" case where the user is- // sitting in their own repo and `npx ruflo metaharness score` should- // score THAT repo using the LOCAL plugin if present).- const cwd = process.cwd();- candidates.push(join(cwd, 'plugins', 'ruflo-metaharness', 'scripts'));- candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts'));+ // The scripts are executed, so they come from this CLI's own install (or the+ // user's marketplace checkout), never from the cwd: scoring a repo must not+ // run plugin code that repo supplies. The repo is still the scoring target.+ candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts'));for (const c of candidates) {if (!existsSync(join(c, '_harness.mjs'))) continue;diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.tsindex d3db1f0869..6551dbca66 100644--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts@@ -53,6 +53,7 @@ import { spawn } from 'node:child_process';import { existsSync, readFileSync } from 'node:fs';import { join, dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';+import { homedir } from 'node:os';import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';import { evaluatePolicyRequest } from '../services/policy-runtime.js';import {@@ -83,9 +84,9 @@ function locatePluginScripts(requiredScript?: string): string | null {candidates.push(join(p, '..', 'plugins', 'ruflo-metaharness', 'scripts'));p = dirname(p);}- const cwd = getProjectCwd();- candidates.push(join(cwd, 'plugins', 'ruflo-metaharness', 'scripts'));- candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-metaharness', 'scripts'));+ // Scripts found here are executed, so they come from this CLI's own install+ // (or the user's marketplace checkout), never from the project's cwd.+ candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-metaharness', 'scripts'));for (const c of candidates) {if (!existsSync(join(c, '_harness.mjs'))) continue;if (requiredScript && !existsSync(join(c, requiredScript))) continue;diff --git a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.tsindex 3d10346492..e698ef79b6 100644--- a/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/testgen-tools.ts@@ -27,7 +27,7 @@ import { existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import type { MCPTool } from './types.js';-import { getProjectCwd } from './types.js';+import { homedir } from 'node:os';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -49,9 +49,9 @@ function locateTestgenScripts(): string | null {candidates.push(join(p, '..', 'plugins', 'ruflo-testgen', 'scripts'));p = dirname(p);}- const cwd = getProjectCwd();- candidates.push(join(cwd, 'plugins', 'ruflo-testgen', 'scripts'));- candidates.push(join(cwd, 'node_modules', '@claude-flow', 'cli', 'plugins', 'ruflo-testgen', 'scripts'));+ // Scripts found here are executed, so they come from this CLI's own install+ // (or the user's marketplace checkout), never from the project's cwd.+ candidates.push(join(homedir(), '.claude', 'plugins', 'marketplaces', 'ruflo', 'plugins', 'ruflo-testgen', 'scripts'));for (const c of candidates) {if (existsSync(join(c, 'tdd-repair', 'tdd-repair.mjs'))) return c;}diff --git a/v3/@claude-flow/embeddings/src/embedding-service.ts b/v3/@claude-flow/embeddings/src/embedding-service.tsindex 2b72a61a09..790ae4ffa3 100644--- a/v3/@claude-flow/embeddings/src/embedding-service.ts+++ b/v3/@claude-flow/embeddings/src/embedding-service.ts@@ -670,26 +670,18 @@ export class AgenticFlowEmbeddingService extends BaseEmbeddingService {// Try proper package exports first (preferred)possiblePaths.push('agentic-flow/embeddings');- // Try node_modules resolution from different locations (for file:// imports)+ // File fallback: resolve from this package's own location, never from+ // the cwd or a fixed path β the module found here is imported.try {- const path = await import('path');+ const { createRequire } = await import('module');const { existsSync } = await import('fs');- const cwd = process.cwd();-- // Prioritize absolute paths that exist (for file:// import fallback)- const absolutePaths = [- path.join(cwd, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'),- path.join(cwd, '../node_modules/agentic-flow/dist/embeddings/optimized-embedder.js'),- '/workspaces/claude-flow/node_modules/agentic-flow/dist/embeddings/optimized-embedder.js',- ];-- for (const p of absolutePaths) {- if (existsSync(p)) {- possiblePaths.push(p);- }- }+ const path = await import('path');+ const require = createRequire(import.meta.url);+ const pkgDir = path.dirname(require.resolve('agentic-flow/package.json'));+ const embedder = path.join(pkgDir, 'dist/embeddings/optimized-embedder.js');+ if (existsSync(embedder)) possiblePaths.push(embedder);} catch {- // fs/path module not available+ // agentic-flow not resolvable from this package}// Try each path