diff --git a/plugins/ruflo-core/.claude-plugin/plugin.json b/plugins/ruflo-core/.claude-plugin/plugin.json index 18c436cc8b..26cb905e02 100644 --- a/plugins/ruflo-core/.claude-plugin/plugin.json +++ b/plugins/ruflo-core/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-core", "description": "Foundation plugin — registers the ruflo MCP server (300+ tools across memory/agentdb/embeddings/hooks/aidefence/neural/autopilot/browser/agent/swarm), provides 4 generalist agents (coder/researcher/reviewer/witness-curator), 5 skills (discover-plugins/init-project/ruflo-doctor/ruflo-status/witness), and a curated plugin-discovery catalog", - "version": "0.2.10", + "version": "0.2.11", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-core/CHANGELOG.md b/plugins/ruflo-core/CHANGELOG.md index bdaf147c76..403778e6fc 100644 --- a/plugins/ruflo-core/CHANGELOG.md +++ b/plugins/ruflo-core/CHANGELOG.md @@ -2,6 +2,9 @@ Newest first. One `## — ` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history. +## 0.2.11 — 2026-10-14 +- perf: the MCP launcher runs the resolved local CLI inside its own process instead of spawning a second node (one process, about half the memory, a faster first answer: measured here with a stub CLI as 2 processes to 1, 89 MB to 46 MB, 30 ms to 19 ms spawn-to-initialize); `RUFLO_MCP_SPAWN=1` restores the child process, and the npx fallback still spawns (#3989, thanks @socrates6969). The real-CLI startup numbers in the PR (149 MB to 81 MB, 1.3 s to 0.7 s) were not re-measured. + ## 0.2.10 — 2026-10-14 - fix: the MCP launcher starts the server in the session project (`CLAUDE_PROJECT_DIR`, then `CLAUDE_FLOW_CWD`, then its own working directory; a drive root, the home folder or a missing folder is not a project) and looks for the local CLI from there, so on Windows the CLI and the MCP server keep one `.claude-flow` state, not two (#3987, thanks @socrates6969). It warns on stderr when there is no project. Tested with Windows-style environments only; no Windows machine was available. diff --git a/plugins/ruflo-core/scripts/mcp-launch.cjs b/plugins/ruflo-core/scripts/mcp-launch.cjs index 732a3cdeb4..8870cb03af 100644 --- a/plugins/ruflo-core/scripts/mcp-launch.cjs +++ b/plugins/ruflo-core/scripts/mcp-launch.cjs @@ -25,12 +25,21 @@ * fallback. RUFLO_MCP_CLI_OVERRIDE can pin a built bin/cli.js when * an install lives outside the standard project or global npm layouts; * RUFLO_MCP_SKIP_NPX=1 rejects an unpinned fallback. + * + * A resolved local CLI is run in THIS process (argv rewritten to the exact + * ` /cli.js mcp start` the child used to receive) rather than in + * a spawned child. The child-process hop cost every Claude Code session a + * second, otherwise idle node.exe (~21 MB private / ~60 MB working set on + * Windows) plus a second node startup. Stdio, env, cwd and signals are the + * same process's, so the server sees an identical environment. + * RUFLO_MCP_SPAWN=1 restores the old child-process behaviour. */ const { existsSync, statSync } = require('fs'); const { join, dirname, resolve, isAbsolute, delimiter, parse } = require('path'); const { spawn } = require('child_process'); const os = require('os'); +const { pathToFileURL } = require('url'); const MCP_ARGS = ['mcp', 'start']; @@ -157,6 +166,20 @@ function buildLaunchSpec(localBin, env = process.env, projectDir = null) { }; } +function runInProcess(localBin, projectDir = null) { + // Same placement the spawned child got from buildLaunchSpec(): run in the + // project and advertise it via CLAUDE_FLOW_CWD, before the CLI is imported + // (it reads both at import/start time). + if (projectDir) { + process.chdir(projectDir); + process.env.CLAUDE_FLOW_CWD = projectDir; + } + // Same argv shape the spawned child saw: [node, /cli.js, 'mcp', 'start']. + // cli.js decides MCP mode from process.argv and stdin at import time. + process.argv = [process.execPath, localBin, ...MCP_ARGS]; + return import(pathToFileURL(localBin).href); +} + function launch({ command, args, shell, cwd, env }) { const child = spawn(command, args, { stdio: 'inherit', env: env || process.env, shell, cwd }); @@ -193,11 +216,18 @@ if (require.main === module) { ); } const localBin = resolveLocalCliBin(projectDir, home); - launch(buildLaunchSpec(localBin, process.env, projectDir)); + if (localBin && process.env.RUFLO_MCP_SPAWN !== '1') { + runInProcess(localBin, projectDir).catch((error) => { + process.stderr.write(`[mcp-launch] failed to load ${localBin}: ${error && error.message}\n`); + process.exit(1); + }); + } else { + launch(buildLaunchSpec(localBin, process.env, projectDir)); + } } catch (error) { process.stderr.write(`[mcp-launch] ${error.message}\n`); process.exitCode = 1; } } -module.exports = { resolveLocalCliBin, resolveProjectDir, isNonProjectDir, buildLaunchSpec, MCP_ARGS }; +module.exports = { resolveLocalCliBin, resolveProjectDir, isNonProjectDir, buildLaunchSpec, runInProcess, MCP_ARGS }; diff --git a/plugins/ruflo-core/scripts/mcp-launch.test.cjs b/plugins/ruflo-core/scripts/mcp-launch.test.cjs index 5fce1dea6c..9262cf71bd 100644 --- a/plugins/ruflo-core/scripts/mcp-launch.test.cjs +++ b/plugins/ruflo-core/scripts/mcp-launch.test.cjs @@ -14,7 +14,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); -const { resolveLocalCliBin, buildLaunchSpec, MCP_ARGS } = require( +const { resolveLocalCliBin, buildLaunchSpec, runInProcess, MCP_ARGS } = require( path.join(__dirname, 'mcp-launch.cjs') ); const NO_GLOBAL_PATH = { PATH: '' }; @@ -245,3 +245,43 @@ test('resolveProjectDir: CLAUDE_PROJECT_DIR > CLAUDE_FLOW_CWD > cwd; home, root for (const d of [cwd, a, b, home]) fs.rmSync(d, { recursive: true, force: true }); } }); + +test('runInProcess loads the resolved bin in-process with the argv the child used to get', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-inproc-')); + const bin = path.join(dir, 'cli.js'); + fs.writeFileSync(bin, 'globalThis.__mcpLaunchArgv = process.argv.slice();\n'); + const savedArgv = process.argv; + try { + await runInProcess(bin); + assert.deepEqual(globalThis.__mcpLaunchArgv, [process.execPath, bin, ...MCP_ARGS]); + } finally { + process.argv = savedArgv; + delete globalThis.__mcpLaunchArgv; + } +}); + +test('runInProcess runs the CLI in the project dir with CLAUDE_FLOW_CWD set before import', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-inproc-proj-')); + const project = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-project-')); + const bin = path.join(dir, 'cli.js'); + fs.writeFileSync( + bin, + 'globalThis.__mcpLaunchSeen = { cwd: process.cwd(), flowCwd: process.env.CLAUDE_FLOW_CWD };\n', + ); + const savedArgv = process.argv; + const savedCwd = process.cwd(); + const hadFlowCwd = Object.prototype.hasOwnProperty.call(process.env, 'CLAUDE_FLOW_CWD'); + const savedFlowCwd = process.env.CLAUDE_FLOW_CWD; + try { + await runInProcess(bin, project); + assert.ok(samePath(globalThis.__mcpLaunchSeen.cwd, project), `cwd ${globalThis.__mcpLaunchSeen.cwd} should be ${project}`); + assert.equal(globalThis.__mcpLaunchSeen.flowCwd, project); + } finally { + process.chdir(savedCwd); + process.argv = savedArgv; + if (hadFlowCwd) process.env.CLAUDE_FLOW_CWD = savedFlowCwd; + else delete process.env.CLAUDE_FLOW_CWD; + delete globalThis.__mcpLaunchSeen; + for (const d of [dir, project]) fs.rmSync(d, { recursive: true, force: true }); + } +}); diff --git a/plugins/ruflo-core/scripts/smoke.sh b/plugins/ruflo-core/scripts/smoke.sh index abd0eb39da..15f3642a04 100755 --- a/plugins/ruflo-core/scripts/smoke.sh +++ b/plugins/ruflo-core/scripts/smoke.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Structural smoke test for ruflo-core v0.2.10 (ADR-0001). +# Structural smoke test for ruflo-core v0.2.11 (ADR-0001). set -u ROOT="$(cd "$(dirname "$0")/.." && pwd)" PASS=0 @@ -8,10 +8,10 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares 0.2.10 with new keywords" +step "1. plugin.json declares 0.2.11 with new keywords" v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) -if [[ "$v" != "0.2.10" ]]; then - bad "expected 0.2.10, got '$v'" +if [[ "$v" != "0.2.11" ]]; then + bad "expected 0.2.11, got '$v'" else miss="" for k in foundation mcp-server plugin-catalog discovery; do diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts index 93e776c717..a591d76ed3 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts @@ -54,7 +54,14 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, chmodSync } from 'node:fs'; import { join } from 'node:path'; import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; -import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'node:http'; +import { createRequire } from 'node:module'; +import type { Server, IncomingMessage, ServerResponse } from 'node:http'; + +// Lazy, CommonJS-style load of node:http: an ESM `import … from 'node:http'` +// materialises every export of the builtin, which trips http's lazy undici +// getters (~2.5 MB heap / ~6 MB RSS) at MCP startup even when no server is +// ever started. require() of the builtin does not touch those getters. +const loadHttp = (): typeof import('node:http') => createRequire(import.meta.url)('node:http'); /** Max envelopes accepted from one peer in one sync. */ export const MAX_ENVELOPES_PER_SYNC = 5_000; @@ -425,7 +432,7 @@ export function serveFederation( opts: { port?: number; bindHost?: string } = {}, ): Promise<{ server: Server; port: number; host: string }> { const host = opts.bindHost ?? '127.0.0.1'; - const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const server = loadHttp().createServer((req: IncomingMessage, res: ServerResponse) => { const send = (code: number, obj: unknown) => { const buf = Buffer.from(JSON.stringify(obj)); res.writeHead(code, { 'content-type': 'application/json', 'content-length': buf.length }); diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts index c63d04bce2..8d9598ce83 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/browser-intent-tools.ts @@ -86,10 +86,16 @@ */ import { createRequire } from 'node:module'; -import { createServer, type Server } from 'node:http'; +import type { Server } from 'node:http'; import { readFileSync, existsSync } from 'node:fs'; import { dirname, join } from 'node:path'; import type { MCPTool, MCPToolResult } from './types.js'; + +// Lazy, CommonJS-style load of node:http: an ESM `import … from 'node:http'` +// materialises every export of the builtin, which trips http's lazy undici +// getters (~2.5 MB heap / ~6 MB RSS) at MCP startup even when no server is +// ever started. require() of the builtin does not touch those getters. +const loadHttp = (): typeof import('node:http') => createRequire(import.meta.url)('node:http'); import { validateText, validateIdentifier } from './validate-input.js'; import { execBrowserCommand } from './browser-tools.js'; import { storeEntry } from '../memory/memory-initializer.js'; @@ -219,7 +225,7 @@ export interface LLMProxyHandle { export function startLocalLLMProxy(real: { baseURL: string; apiKey: string }): Promise { return new Promise((resolve, reject) => { - const server: Server = createServer((req, res) => { + const server: Server = loadHttp().createServer((req, res) => { const target = `${real.baseURL.replace(/\/+$/, '')}${req.url ?? ''}`; const chunks: Buffer[] = []; req.on('data', (c: Buffer) => chunks.push(c)); diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.ts index 2672cf9732..1cc9a8a699 100644 --- a/v3/@claude-flow/cli/src/services/policy-runtime.ts +++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts @@ -1,10 +1,11 @@ +// Narrow subpath imports (not the '@claude-flow/security' barrel): this module +// is loaded eagerly by the MCP server, and the barrel also evaluates the OAuth +// callback server (an ESM `node:http` import that materialises http's lazy +// undici getters), bcryptjs, keychain and credential helpers that the policy +// runtime never uses. import { AgenticPolicyEngine, createLegacyCompatibleState, - isMcpCallerAuthEnabled, - decodeTokenEnvelope, - publicKeyFromHex, - verifyInvocationToken, type BudgetLimit, type CapabilityEnvelope, type PolicyApproval, @@ -13,7 +14,13 @@ import { type PolicyRequest, type PolicyRule, type PolicyState, -} from '@claude-flow/security'; +} from '@claude-flow/security/policy/index'; +import { + isMcpCallerAuthEnabled, + decodeTokenEnvelope, + publicKeyFromHex, + verifyInvocationToken, +} from '@claude-flow/security/mcp-caller-identity'; import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'; import { execFileSync } from 'node:child_process'; import { diff --git a/v3/@claude-flow/cli/vitest.config.ts b/v3/@claude-flow/cli/vitest.config.ts index 6dff721cba..934201efe4 100644 --- a/v3/@claude-flow/cli/vitest.config.ts +++ b/v3/@claude-flow/cli/vitest.config.ts @@ -14,6 +14,14 @@ export default defineConfig({ find: '@claude-flow/guidance/compiler', replacement: fileURLToPath(new URL('../guidance/src/compiler.ts', import.meta.url)), }, + { + find: '@claude-flow/security/policy/index', + replacement: fileURLToPath(new URL('../security/src/policy/index.ts', import.meta.url)), + }, + { + find: '@claude-flow/security/mcp-caller-identity', + replacement: fileURLToPath(new URL('../security/src/mcp-caller-identity.ts', import.meta.url)), + }, { find: '@claude-flow/security/safe-git', replacement: fileURLToPath(new URL('../security/src/safe-git.ts', import.meta.url)),