π 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: prevent MCP server self-kill on startup (#1381)
rUv07ff7f564109
diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjsindex ec51323d31..77a692add1 100644--- a/.claude/helpers/auto-memory-hook.mjs+++ b/.claude/helpers/auto-memory-hook.mjs@@ -348,6 +348,10 @@ async function doStatus() {const command = process.argv[2] || 'status';+// Suppress unhandled rejection warnings from dynamic import() failures+// which can cause non-zero exit codes even when caught+process.on('unhandledRejection', () => {});+try {switch (command) {case 'import': await doImport(); break;@@ -361,3 +365,5 @@ try {// Hooks must never crash Claude Code - fail silentlydim(`Error (non-critical): ${err.message}`);}+// Ensure clean exit for Claude Code hooks (exit 0 = success, no stderr = no error)+process.exit(0);diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjsindex 1c0b104a33..7effd9533d 100644--- a/.claude/helpers/hook-handler.cjs+++ b/.claude/helpers/hook-handler.cjs@@ -228,4 +228,7 @@ if (command && handlers[command]) {main().catch(function(e) {console.log('[WARN] Hook handler error: ' + e.message);+}).finally(function() {+ // Ensure clean exit for Claude Code hooks+ process.exit(0);});diff --git a/package.json b/package.jsonindex f955f85822..96af4f2001 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.5.28",+ "version": "3.5.39","description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "dist/index.js","type": "module",@@ -54,7 +54,6 @@"v3:security": "npm run security:audit && npm run security:test"},"dependencies": {- "@ruvector/ruvllm-wasm": "^2.0.0","semver": "^7.6.0","zod": "^3.22.4"},diff --git a/ruflo/package.json b/ruflo/package.jsonindex 6b70a3a066..634b01143f 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.5.28",+ "version": "3.5.39","description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "bin/ruflo.js","type": "module",diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjsindex 94d005fcd4..3b3881bb0f 100755--- a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs+++ b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs@@ -348,6 +348,9 @@ async function doStatus() {const command = process.argv[2] || 'status';+// Suppress unhandled rejection warnings from dynamic import() failures+process.on('unhandledRejection', () => {});+try {switch (command) {case 'import': await doImport(); break;@@ -361,5 +364,5 @@ try {// Hooks must never crash Claude Code - fail silentlytry { dim(`Error (non-critical): ${err.message}`); } catch (_) {}}-// Hooks must ALWAYS exit 0-process.exitCode = 0;+// Force clean exit β process.exitCode alone isn't enough if async errors override it+process.exit(0);diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjsindex 78c7783915..ed13a38d8a 100644--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs@@ -267,5 +267,6 @@ const handlers = {process.exitCode = 0;main().catch((e) => {try { console.log(`[WARN] Hook handler error: ${e.message}`); } catch (_) {}- process.exitCode = 0;+}).finally(() => {+ process.exit(0);});diff --git a/v3/@claude-flow/cli/README.md b/v3/@claude-flow/cli/README.mdindex c5444d7481..0225f244c7 100644--- a/v3/@claude-flow/cli/README.md+++ b/v3/@claude-flow/cli/README.md@@ -25,7 +25,7 @@</div>-> **Why Ruflo?** Claude Flow is now Ruflo β named by Ruv, who loves Rust, flow states, and building things that feel inevitable. The "Ru" is the Ruv. The "flo" is the flow. Underneath, WASM kernels written in Rust power the policy engine, embeddings, and proof system. 5,800 commits later, the alpha is over. This is v3.5.+> **Why Ruflo?** Claude Flow is now Ruflo β named by Ruv, who loves Rust, flow states, and building things that feel inevitable. The "Ru" is the Ruv. The "flo" is the flow. Underneath, WASM kernels written in Rust power the policy engine, embeddings, and proof system. 5,900+ commits later, the alpha is over. This is v3.5.## Getting into the Flow@@ -161,6 +161,8 @@ curl -fsSL https://cdn.jsdelivr.net/gh/ruvnet/claude-flow@main/scripts/install.snpx ruflo@latest init --wizard```+> **New to Ruflo?** You don't need to learn 259 MCP tools or 26 CLI commands. After running `init`, just use Claude Code normally β the hooks system automatically routes tasks to the right agents, learns from successful patterns, and coordinates multi-agent work in the background. The advanced tools exist for fine-grained control when you need it.+---### Key Capabilities@@ -697,12 +699,12 @@ claude mcp add ruflo -- npx -y ruflo@latest mcp startclaude mcp list```-Once added, Claude Code can use all 175+ ruflo MCP tools directly:+Once added, Claude Code can use all 259 ruflo MCP tools directly:- `swarm_init` - Initialize agent swarms- `agent_spawn` - Spawn specialized agents- `memory_search` - Search patterns with HNSW vector search- `hooks_route` - Intelligent task routing-- And 170+ more tools...+- And 255+ more tools...---## What is it exactly? Agents that learn, build and work perpetually.@@ -752,7 +754,7 @@ Ruflo v3 introduces **self-learning neural capabilities** that no other agent or| Feature | Ruflo v3 | CrewAI | LangGraph | AutoGen | Manus ||---------|----------------|--------|-----------|---------|-------|-| **MCP Integration** | β Native (170+ tools) | β | β | β | β |+| **MCP Integration** | β Native (259 tools) | β | β | β | β || **Skills System** | β 42+ pre-built | β | β | β | Limited || **Stream Pipelines** | β JSON chains | β | Via code | β | β || **Pair Programming** | β Driver/Navigator | β | β | β | β |@@ -2158,7 +2160,7 @@ npx ruflo@v3alpha worker status| `agentConfigs` | 15 V3 agent configurations | Agent testing || `memoryEntries` | Patterns, rules, embeddings | Memory testing || `swarmConfigs` | V3 default, minimal, mesh, hierarchical | Swarm testing |-| `mcpTools` | 175+ tool definitions | MCP testing |+| `mcpTools` | 259 tool definitions | MCP testing |</details>@@ -5018,9 +5020,9 @@ npx agentic-flow mcp stdio</details><details>-<summary>π§ <strong>MCP Tools</strong> β 213+ Integration Tools</summary>+<summary>π§ <strong>MCP Tools</strong> β 259 Integration Tools</summary>-Agentic-flow exposes 213+ MCP tools for integration:+Agentic-flow exposes 259 MCP tools for integration:| Category | Tools | Examples ||----------|-------|----------|diff --git a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.tsindex 05c93f4e54..ac2ab03cb8 100644--- a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts@@ -577,25 +577,50 @@ describe('MCP Tools Deep Test Suite', () => {const result: any = await tool.handler({ topology: 'hierarchical' });expect(result.success).toBe(true);expect(result.swarmId).toBeDefined();+ expect(result.persisted).toBe(true);});- it('swarm_status returns running status', async () => {+ it('swarm_status returns running status after init', async () => {+ // Init a swarm first so status has something to report+ const initTool = swarmTools.find(t => t.name === 'swarm_init')!;+ const initResult: any = await initTool.handler({ topology: 'mesh' });const tool = swarmTools.find(t => t.name === 'swarm_status')!;- const result: any = await tool.handler({});+ const result: any = await tool.handler({ swarmId: initResult.swarmId });expect(result.status).toBe('running');});- it('swarm_shutdown returns success', async () => {+ it('swarm_shutdown returns success after init', async () => {+ const initTool = swarmTools.find(t => t.name === 'swarm_init')!;+ const initResult: any = await initTool.handler({ topology: 'hierarchical' });const tool = swarmTools.find(t => t.name === 'swarm_shutdown')!;- const result: any = await tool.handler({});+ const result: any = await tool.handler({ swarmId: initResult.swarmId });expect(result.success).toBe(true);+ expect(result.terminated).toBe(true);});- it('swarm_health returns healthy checks', async () => {+ it('swarm_health returns healthy checks after init', async () => {+ const initTool = swarmTools.find(t => t.name === 'swarm_init')!;+ const initResult: any = await initTool.handler({ topology: 'hierarchical' });const tool = swarmTools.find(t => t.name === 'swarm_health')!;- const result: any = await tool.handler({});+ const result: any = await tool.handler({ swarmId: initResult.swarmId });expect(result.status).toBe('healthy');expect(result.checks).toBeDefined();+ expect(result.healthy).toBe(true);+ });++ it('swarm_health returns not_found for nonexistent swarm ID', async () => {+ const tool = swarmTools.find(t => t.name === 'swarm_health')!;+ const result: any = await tool.handler({ swarmId: 'nonexistent-id-999' });+ expect(result.status).toBe('not_found');+ expect(result.healthy).toBe(false);+ expect(result.checks).toBeDefined();+ });++ it('swarm_init rejects invalid topology', async () => {+ const tool = swarmTools.find(t => t.name === 'swarm_init')!;+ const result: any = await tool.handler({ topology: 'invalid-topo' });+ expect(result.success).toBe(false);+ expect(result.error).toContain('Invalid topology');});});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 96b27ec529..fe769aa598 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/cli",- "version": "3.5.28",+ "version": "3.5.39","type": "module","description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code","main": "dist/src/index.js",@@ -86,7 +86,7 @@},"dependencies": {"@claude-flow/mcp": "^3.0.0-alpha.8",- "@claude-flow/shared": "^3.0.0-alpha.1",+ "@claude-flow/shared": "^3.0.0-alpha.7","@noble/ed25519": "^2.1.0","semver": "^7.6.0"},@@ -97,14 +97,11 @@"@claude-flow/guidance": "^3.0.0-alpha.1","@claude-flow/memory": "^3.0.0-alpha.11","@claude-flow/plugin-gastown-bridge": "^0.1.3",+ "agentic-flow": "^3.0.0-alpha.1","@ruvector/attention": "^0.1.4","@ruvector/learning-wasm": "^0.1.29","@ruvector/router": "^0.1.27",- "@ruvector/rvagent-wasm": "^0.1.0",- "@ruvector/ruvllm-wasm": "^2.0.2",- "@ruvector/sona": "^0.1.5",- "agentic-flow": "^3.0.0-alpha.1",- "ruvector": "^0.2.16"+ "@ruvector/sona": "^0.1.5"},"publishConfig": {"access": "public",diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.tsindex 5db3df8898..fa4aff016c 100644--- a/v3/@claude-flow/cli/src/commands/index.ts+++ b/v3/@claude-flow/cli/src/commands/index.ts@@ -70,6 +70,8 @@ const commandLoaders: Record<string, CommandLoader> = {guidance: () => import('./guidance.js'),// RVFA Appliance Managementappliance: () => import('./appliance.js'),+ 'appliance-advanced': () => import('./appliance-advanced.js'),+ 'transfer-store': () => import('./transfer-store.js'),};// Cache for loaded commandsdiff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.tsindex 939523087a..76b93ab9a7 100644--- a/v3/@claude-flow/cli/src/commands/init.ts+++ b/v3/@claude-flow/cli/src/commands/init.ts@@ -812,6 +812,8 @@ const hooksCommand: Command = {stop: false,preCompact: false,notification: false,+ teammateIdle: false,+ taskCompleted: false,timeout: 5000,continueOnError: true,}diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.tsindex 5893f40ed9..3da6bd1218 100644--- a/v3/@claude-flow/cli/src/commands/mcp.ts+++ b/v3/@claude-flow/cli/src/commands/mcp.ts@@ -113,9 +113,12 @@ const startCommand: Command = {output.printInfo('Starting MCP Server...');output.writeln();- // Check if already running+ // Check if already running (skip self-detection for stdio β getStatus()+ // reports the current process as "running" when transport=stdio and no+ // PID file exists, which would cause us to SIGKILL ourselves)const existingStatus = await getMCPServerStatus();- if (existingStatus.running) {+ const isSelfDetected = existingStatus.pid === process.pid;+ if (existingStatus.running && !isSelfDetected) {// For stdio transport, always force restart since we can't health check it// For other transports, check health unless --force is specifiedconst shouldForceRestart = force || transport === 'stdio';diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex 5be60fb566..e29882efaa 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -589,7 +589,7 @@ export function generateHookHandler(): string {'} // end main','','process.exitCode = 0;',- 'main().catch(() => { process.exitCode = 0; });',+ 'main().catch(() => {}).finally(() => { process.exit(0); });',];return lines.join('\n') + '\n';}@@ -907,6 +907,9 @@ function doStatus() {console.log('');}+// Suppress unhandled rejection warnings from dynamic import() failures+process.on('unhandledRejection', () => {});+const command = process.argv[2] || 'status';try {@@ -922,6 +925,8 @@ try {// Hooks must never crash Claude Code - fail silentlydim(\`Error (non-critical): \${err.message}\`);}+// Ensure clean exit for Claude Code hooks (exit 0 = success)+process.exit(0);`;}diff --git a/v3/@claude-flow/cli/src/init/settings-generator.ts b/v3/@claude-flow/cli/src/init/settings-generator.tsindex 0a71061f43..7241393c1a 100644--- a/v3/@claude-flow/cli/src/init/settings-generator.ts+++ b/v3/@claude-flow/cli/src/init/settings-generator.ts@@ -168,44 +168,31 @@ export function generateSettings(options: InitOptions): object {const IS_WINDOWS = process.platform === 'win32';/**- * Platform-aware project dir variable reference.- * Claude Code sets $CLAUDE_PROJECT_DIR (Unix) / %CLAUDE_PROJECT_DIR% (Windows)- * as an environment variable before running hook commands.- */-function projectDirVar(): string {- return IS_WINDOWS ? '%CLAUDE_PROJECT_DIR%' : '$CLAUDE_PROJECT_DIR';-}--/**- * Build a cross-platform hook command.- * On Windows, wraps with `cmd /c` to avoid PowerShell stdin/process issues- * that cause "UserPromptSubmit hook error" in Claude Code.+ * Build a hook command with reliable $CLAUDE_PROJECT_DIR expansion.+ * Wraps in `sh -c` to guarantee shell expansion on all platforms (macOS zsh,+ * Linux bash). Falls back to "." if CLAUDE_PROJECT_DIR is unset, since+ * Claude Code runs hooks from the project root.+ * On Windows, uses `cmd /c` with %CLAUDE_PROJECT_DIR%.*/function hookCmd(script: string, subcommand: string): string {- const cmd = `node ${script} ${subcommand}`.trim();- return IS_WINDOWS ? `cmd /c ${cmd}` : cmd;-}--/**- * Build a cross-platform hook command for ESM scripts (.mjs).- */-function hookCmdEsm(script: string, subcommand: string): string {- const cmd = `node ${script} ${subcommand}`.trim();- return IS_WINDOWS ? `cmd /c ${cmd}` : cmd;+ if (IS_WINDOWS) {+ return `cmd /c node %CLAUDE_PROJECT_DIR%/${script} ${subcommand}`.trim();+ }+ // Use sh -c to ensure $CLAUDE_PROJECT_DIR is expanded by a real shell,+ // even if Claude Code doesn't invoke hooks through a shell on macOS.+ // eslint-disable-next-line no-template-curly-in-string+ const dir = '${CLAUDE_PROJECT_DIR:-.}';+ return `sh -c 'exec node "${dir}/${script}" ${subcommand}'`;}/** Shorthand for CJS hook-handler commands */function hookHandlerCmd(subcommand: string): string {- const dir = projectDirVar();- const quote = IS_WINDOWS ? '' : '"';- return hookCmd(`${quote}${dir}/.claude/helpers/hook-handler.cjs${quote}`, subcommand);+ return hookCmd('.claude/helpers/hook-handler.cjs', subcommand);}/** Shorthand for ESM auto-memory-hook commands */function autoMemoryCmd(subcommand: string): string {- const dir = projectDirVar();- const quote = IS_WINDOWS ? '' : '"';- return hookCmdEsm(`${quote}${dir}/.claude/helpers/auto-memory-hook.mjs${quote}`, subcommand);+ return hookCmd('.claude/helpers/auto-memory-hook.mjs', subcommand);}/**@@ -218,11 +205,11 @@ function generateStatusLineConfig(_options: InitOptions): object {// The script runs after each assistant message (debounced 300ms).// NOTE: statusline must NOT use `cmd /c` β Claude Code manages its stdin// directly for statusline commands, and `cmd /c` blocks stdin forwarding.- const dir = projectDirVar();- const quote = IS_WINDOWS ? '' : '"';+ // eslint-disable-next-line no-template-curly-in-string+ const dir = '${CLAUDE_PROJECT_DIR:-.}';return {type: 'command',- command: `node ${quote}${dir}/.claude/helpers/statusline.cjs${quote}`,+ command: `sh -c 'exec node "${dir}/.claude/helpers/statusline.cjs"'`,};}@@ -431,8 +418,9 @@ function generateHooksConfig(config: HooksConfig): object {];}- // NOTE: TeammateIdle and TaskCompleted are NOT valid Claude Code hook events.- // Their configuration lives in claudeFlow.agentTeams.hooks instead (see generateSettings).+ // NOTE: TeammateIdle, TaskCompleted, and PostCompact are NOT accepted by+ // Claude Code's settings.json validator (rejected as "Invalid key in record").+ // Agent Teams coordination lives in claudeFlow.agentTeams.hooks instead.return hooks;}diff --git a/v3/@claude-flow/cli/src/init/types.ts b/v3/@claude-flow/cli/src/init/types.tsindex 74eb4036ce..d4a8c222ea 100644--- a/v3/@claude-flow/cli/src/init/types.ts+++ b/v3/@claude-flow/cli/src/init/types.ts@@ -32,8 +32,12 @@ export interface InitComponents {/*** Hook configuration options- * Valid hook types: PreToolUse, PostToolUse, Notification, UserPromptSubmit,- * SessionStart, SessionEnd, Stop, SubagentStop, PreCompact+ * Valid Claude Code hook events (23 total):+ * PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit,+ * SessionStart, SessionEnd, Stop, SubagentStart, SubagentStop,+ * PreCompact, PostCompact, Notification, ConfigChange,+ * InstructionsLoaded, PermissionRequest, WorktreeCreate, WorktreeRemove,+ * TeammateIdle, TaskCompleted, Elicitation, ElicitationResult*/export interface HooksConfig {/** Enable PreToolUse hooks */@@ -50,6 +54,10 @@ export interface HooksConfig {preCompact: boolean;/** Enable Notification hooks */notification: boolean;+ /** Enable TeammateIdle hooks (agent teams auto-assign) */+ teammateIdle: boolean;+ /** Enable TaskCompleted hooks (agent teams pattern learning) */+ taskCompleted: boolean;/** Hook timeout in milliseconds */timeout: number;/** Continue on hook error */@@ -330,6 +338,8 @@ export const DEFAULT_INIT_OPTIONS: InitOptions = {stop: true,preCompact: true,notification: true,+ teammateIdle: true,+ taskCompleted: true,timeout: 5000,continueOnError: true,},@@ -426,6 +436,8 @@ export const MINIMAL_INIT_OPTIONS: InitOptions = {userPromptSubmit: false,stop: false,notification: false,+ teammateIdle: false,+ taskCompleted: false,},skills: {core: true,diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.tsindex 0839bf3257..3ef8774994 100644--- a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts@@ -18,11 +18,11 @@ const browserSessions = new Map<string, {* Execute agent-browser CLI command*/async function execBrowserCommand(args: string[], session = 'default'): Promise<MCPToolResult> {- const { execSync } = await import('child_process');+ const { execFileSync } = await import('child_process');try {const fullArgs = ['--session', session, '--json', ...args];- const result = execSync(`agent-browser ${fullArgs.join(' ')}`, {+ const result = execFileSync('agent-browser', fullArgs, {encoding: 'utf-8',timeout: 30000,});diff --git a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/config-tools.tsindex f825dbf302..6db4d5fc0f 100644--- a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts@@ -44,7 +44,7 @@ function getConfigPath(): string {function ensureConfigDir(): void {const dir = getConfigDir();if (!existsSync(dir)) {- mkdirSync(dir, { recursive: true });+ mkdirSync(dir, { recursive: true, mode: 0o700 });}}@@ -98,7 +98,16 @@ function filterDangerousKeys(obj: Record<string, unknown>): Record<string, unkno}function setNestedValue(obj: Record<string, unknown>, key: string, value: unknown): void {+ const MAX_NESTING_DEPTH = 10;const parts = key.split('.');+ if (parts.length > MAX_NESTING_DEPTH) {+ throw new Error(`Key exceeds maximum nesting depth of ${MAX_NESTING_DEPTH}`);+ }+ for (const part of parts) {+ if (DANGEROUS_KEYS.has(part)) {+ throw new Error(`Dangerous key segment rejected: ${part}`);+ }+ }let current = obj;for (let i = 0; i < parts.length - 1; i++) {const part = parts[i];diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.tsindex 104a1c123d..c47267576f 100644--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts@@ -261,6 +261,8 @@ export const memoryTools: MCPTool[] = [const key = input.key as string;const namespace = (input.namespace as string) || 'default';+ validateMemoryInput(key);+try {const result = await getEntry({ key, namespace });@@ -394,6 +396,8 @@ export const memoryTools: MCPTool[] = [const key = input.key as string;const namespace = (input.namespace as string) || 'default';+ validateMemoryInput(key);+try {const result = await deleteEntry({ key, namespace });diff --git a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.tsindex e8e1e3deaf..3fe2cbb03a 100644--- a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts@@ -1,86 +1,251 @@/*** Swarm MCP Tools for CLI*- * Tool definitions for swarm coordination.+ * Tool definitions for swarm coordination with file-based state persistence.+ * Replaces previous stub implementations with real state tracking.*/+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';import type { MCPTool } from './types.js';+// Swarm state persistence+const SWARM_DIR = '.claude-flow/swarm';+const SWARM_STATE_FILE = 'swarm-state.json';++interface SwarmState {+ swarmId: string;+ topology: string;+ maxAgents: number;+ status: 'initializing' | 'running' | 'paused' | 'shutting_down' | 'terminated';+ agents: string[];+ tasks: string[];+ config: Record<string, unknown>;+ createdAt: string;+ updatedAt: string;+}++interface SwarmStore {+ swarms: Record<string, SwarmState>;+ version: string;+}++function getSwarmDir(): string {+ return join(process.cwd(), SWARM_DIR);+}++function getSwarmStatePath(): string {+ return join(getSwarmDir(), SWARM_STATE_FILE);+}++function ensureSwarmDir(): void {+ const dir = getSwarmDir();+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ }+}++function loadSwarmStore(): SwarmStore {+ try {+ const path = getSwarmStatePath();+ if (existsSync(path)) {+ return JSON.parse(readFileSync(path, 'utf-8'));+ }+ } catch { /* return default */ }+ return { swarms: {}, version: '3.0.0' };+}++function saveSwarmStore(store: SwarmStore): void {+ ensureSwarmDir();+ writeFileSync(getSwarmStatePath(), JSON.stringify(store, null, 2), 'utf-8');+}++// Input validation+const VALID_TOPOLOGIES = new Set([+ 'hierarchical', 'mesh', 'hierarchical-mesh', 'ring', 'star', 'hybrid', 'adaptive',+]);+export const swarmTools: MCPTool[] = [{name: 'swarm_init',- description: 'Initialize a swarm',+ description: 'Initialize a swarm with persistent state tracking',category: 'swarm',inputSchema: {type: 'object',properties: {- topology: { type: 'string', description: 'Swarm topology type' },- maxAgents: { type: 'number', description: 'Maximum number of agents' },- config: { type: 'object', description: 'Swarm configuration' },+ topology: { type: 'string', description: 'Swarm topology type (hierarchical, mesh, hierarchical-mesh, ring, star, hybrid, adaptive)' },+ maxAgents: { type: 'number', description: 'Maximum number of agents (1-50)' },+ strategy: { type: 'string', description: 'Agent strategy (specialized, balanced, adaptive)' },+ config: { type: 'object', description: 'Additional swarm configuration' },},},handler: async (input) => {- const topology = input.topology || 'hierarchical-mesh';- const maxAgents = input.maxAgents || 15;+ const topology = (input.topology as string) || 'hierarchical-mesh';+ const maxAgents = Math.min(Math.max((input.maxAgents as number) || 15, 1), 50);+ const strategy = (input.strategy as string) || 'specialized';const config = (input.config || {}) as Record<string, unknown>;- return {- success: true,- swarmId: `swarm-${Date.now()}`,+ if (!VALID_TOPOLOGIES.has(topology)) {+ return {+ success: false,+ error: `Invalid topology: ${topology}. Valid: ${[...VALID_TOPOLOGIES].join(', ')}`,+ };+ }++ const swarmId = `swarm-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+ const now = new Date().toISOString();++ const swarmState: SwarmState = {+ swarmId,topology,- initializedAt: new Date().toISOString(),+ maxAgents,+ status: 'running',+ agents: [],+ tasks: [],config: {topology,maxAgents,- currentAgents: 0,+ strategy,communicationProtocol: (config.communicationProtocol as string) || 'message-bus',autoScaling: (config.autoScaling as boolean) ?? true,consensusMechanism: (config.consensusMechanism as string) || 'majority',},+ createdAt: now,+ updatedAt: now,+ };++ const store = loadSwarmStore();+ store.swarms[swarmId] = swarmState;+ saveSwarmStore(store);++ return {+ success: true,+ swarmId,+ topology,+ strategy,+ maxAgents,+ initializedAt: now,+ config: swarmState.config,+ persisted: true,};},},{name: 'swarm_status',- description: 'Get swarm status',+ description: 'Get swarm status from persistent state',category: 'swarm',inputSchema: {type: 'object',properties: {- swarmId: { type: 'string', description: 'Swarm ID' },+ swarmId: { type: 'string', description: 'Swarm ID (omit for most recent)' },},},handler: async (input) => {+ const store = loadSwarmStore();+ const swarmId = input.swarmId as string;++ if (swarmId && store.swarms[swarmId]) {+ const swarm = store.swarms[swarmId];+ return {+ swarmId: swarm.swarmId,+ status: swarm.status,+ topology: swarm.topology,+ maxAgents: swarm.maxAgents,+ agentCount: swarm.agents.length,+ taskCount: swarm.tasks.length,+ config: swarm.config,+ createdAt: swarm.createdAt,+ updatedAt: swarm.updatedAt,+ };+ }++ // Return most recent swarm if no ID specified+ const swarmIds = Object.keys(store.swarms);+ if (swarmIds.length === 0) {+ return {+ status: 'no_swarm',+ message: 'No active swarms. Use swarm_init to create one.',+ totalSwarms: 0,+ };+ }++ const latest = swarmIds+ .map(id => store.swarms[id])+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0];+return {- swarmId: input.swarmId,- status: 'running',- agentCount: 0,- taskCount: 0,+ swarmId: latest.swarmId,+ status: latest.status,+ topology: latest.topology,+ maxAgents: latest.maxAgents,+ agentCount: latest.agents.length,+ taskCount: latest.tasks.length,+ config: latest.config,+ createdAt: latest.createdAt,+ updatedAt: latest.updatedAt,+ totalSwarms: swarmIds.length,};},},{name: 'swarm_shutdown',- description: 'Shutdown a swarm',+ description: 'Shutdown a swarm and update persistent state',category: 'swarm',inputSchema: {type: 'object',properties: {- swarmId: { type: 'string', description: 'Swarm ID' },- graceful: { type: 'boolean', description: 'Graceful shutdown' },+ swarmId: { type: 'string', description: 'Swarm ID to shutdown' },+ graceful: { type: 'boolean', description: 'Graceful shutdown (default: true)' },},},handler: async (input) => {+ const store = loadSwarmStore();+ const swarmId = input.swarmId as string;++ // Find the swarm+ let target: SwarmState | undefined;+ if (swarmId && store.swarms[swarmId]) {+ target = store.swarms[swarmId];+ } else {+ // Shutdown most recent running swarm+ const running = Object.values(store.swarms)+ .filter(s => s.status === 'running')+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());+ target = running[0];+ }++ if (!target) {+ return {+ success: false,+ error: swarmId ? `Swarm ${swarmId} not found` : 'No running swarms to shutdown',+ };+ }++ if (target.status === 'terminated') {+ return {+ success: false,+ swarmId: target.swarmId,+ error: 'Swarm already terminated',+ };+ }++ target.status = 'terminated';+ target.updatedAt = new Date().toISOString();+ saveSwarmStore(store);+return {success: true,- swarmId: input.swarmId,+ swarmId: target.swarmId,terminated: true,+ graceful: (input.graceful as boolean) ?? true,+ agentsTerminated: target.agents.length,+ terminatedAt: target.updatedAt,};},},{name: 'swarm_health',- description: 'Check swarm health status',+ description: 'Check swarm health status with real state inspection',category: 'swarm',inputSchema: {type: 'object',@@ -89,15 +254,76 @@ export const swarmTools: MCPTool[] = [},},handler: async (input) => {+ const store = loadSwarmStore();+ const swarmId = input.swarmId as string;++ // Find the swarm+ let target: SwarmState | undefined;+ if (swarmId) {+ target = store.swarms[swarmId];+ if (!target) {+ return {+ status: 'not_found',+ healthy: false,+ checks: [+ { name: 'swarm_exists', status: 'fail', message: `Swarm ${swarmId} not found` },+ ],+ checkedAt: new Date().toISOString(),+ };+ }+ } else {+ const running = Object.values(store.swarms)+ .filter(s => s.status === 'running')+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());+ target = running[0];+ }++ if (!target) {+ return {+ status: 'no_swarm',+ healthy: false,+ checks: [+ { name: 'swarm_exists', status: 'fail', message: 'No active swarm found' },+ ],+ checkedAt: new Date().toISOString(),+ };+ }++ const isRunning = target.status === 'running';+ const stateFileExists = existsSync(getSwarmStatePath());++ const checks = [+ {+ name: 'coordinator',+ status: isRunning ? 'ok' : 'warn',+ message: isRunning ? 'Coordinator active' : `Swarm status: ${target.status}`,+ },+ {+ name: 'agents',+ status: target.agents.length > 0 ? 'ok' : 'info',+ message: `${target.agents.length} agents registered (max: ${target.maxAgents})`,+ },+ {+ name: 'persistence',+ status: stateFileExists ? 'ok' : 'warn',+ message: stateFileExists ? 'State file persisted' : 'State file missing',+ },+ {+ name: 'topology',+ status: 'ok',+ message: `Topology: ${target.topology}`,+ },+ ];++ const healthy = isRunning && stateFileExists;+return {- status: 'healthy' as const,- swarmId: input.swarmId || 'default',- checks: [- { name: 'coordinator', status: 'ok', message: 'Coordinator responding' },- { name: 'agents', status: 'ok', message: 'Agent pool healthy' },- { name: 'memory', status: 'ok', message: 'Memory backend connected' },- { name: 'messaging', status: 'ok', message: 'Message bus active' },- ],+ status: healthy ? 'healthy' : 'degraded',+ healthy,+ swarmId: target.swarmId,+ topology: target.topology,+ agentCount: target.agents.length,+ checks,checkedAt: new Date().toISOString(),};},diff --git a/v3/@claude-flow/cli/src/transfer/storage/gcs.ts b/v3/@claude-flow/cli/src/transfer/storage/gcs.tsindex 3c8bb0aa4c..33853c0d8f 100644--- a/v3/@claude-flow/cli/src/transfer/storage/gcs.ts+++ b/v3/@claude-flow/cli/src/transfer/storage/gcs.ts@@ -117,6 +117,12 @@ export async function uploadToGCS(const contentId = generateContentId(content);const checksum = crypto.createHash('sha256').update(content).digest('hex');const fileName = options.name || `${contentId}.cfp.json`;++ // Validate filename to prevent path traversal+ if (!/^[a-zA-Z0-9._\-]+$/.test(fileName) || fileName.includes('..')) {+ throw new Error(`Invalid filename: ${fileName}`);+ }+const objectPath = config.prefix ? `${config.prefix}/${fileName}` : fileName;// S-1: Validate bucket name and object path to prevent command injection@@ -154,8 +160,11 @@ export async function uploadToGCS(}}- // Clean up temp file- fs.unlinkSync(tempFile);+ // Clean up temp file (validate path is within temp dir)+ const resolvedTemp = path.resolve(tempFile);+ if (resolvedTemp.startsWith(path.resolve(tempDir))) {+ fs.unlinkSync(tempFile);+ }const uri = `gs://${config.bucket}/${objectPath}`;const publicUrl = `https://storage.googleapis.com/${config.bucket}/${objectPath}`;@@ -171,9 +180,12 @@ export async function uploadToGCS(contentId,};} catch (error) {- // Clean up temp file on error+ // Clean up temp file on error (validate path is within temp dir)try {- fs.unlinkSync(tempFile);+ const resolvedTemp = path.resolve(tempFile);+ if (resolvedTemp.startsWith(path.resolve(tempDir))) {+ fs.unlinkSync(tempFile);+ }} catch { /* ignore */ }throw new Error(`GCS upload failed: ${error}`);@@ -202,13 +214,19 @@ export async function downloadFromGCS(execFileSync('gcloud', downloadArgs, { encoding: 'utf-8', stdio: 'pipe' });const content = fs.readFileSync(tempFile);- fs.unlinkSync(tempFile);+ const resolvedTemp = path.resolve(tempFile);+ if (resolvedTemp.startsWith(path.resolve(tempDir))) {+ fs.unlinkSync(tempFile);+ }console.log(`[GCS] Downloaded ${content.length} bytes`);return content;} catch (error) {try {- fs.unlinkSync(tempFile);+ const resolvedTemp = path.resolve(tempFile);+ if (resolvedTemp.startsWith(path.resolve(tempDir))) {+ fs.unlinkSync(tempFile);+ }} catch { /* ignore */ }console.error(`[GCS] Download failed: ${error}`);diff --git a/v3/@claude-flow/shared/package.json b/v3/@claude-flow/shared/package.jsonindex 8905e2004b..e67f928d66 100644--- a/v3/@claude-flow/shared/package.json+++ b/v3/@claude-flow/shared/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/shared",- "version": "3.0.0-alpha.6",+ "version": "3.0.0-alpha.7","type": "module","description": "Shared module - common types, events, utilities, core interfaces","main": "dist/index.js",diff --git a/v3/@claude-flow/shared/src/core/config/loader.ts b/v3/@claude-flow/shared/src/core/config/loader.tsindex a3e6aca31c..3d6427db0a 100644--- a/v3/@claude-flow/shared/src/core/config/loader.ts+++ b/v3/@claude-flow/shared/src/core/config/loader.ts@@ -182,7 +182,23 @@ export class ConfigLoader {path = configPath;break;} else {- warnings.push(`Invalid config at ${configPath}: ${validation.errors?.map(e => e.message).join(', ')}`);+ // Config file exists but doesn't match the strict schema.+ // Merge whatever valid object fields exist with defaults and continue.+ // This handles partial configs, legacy configs, and simple key-value files.+ if (fileConfig && typeof fileConfig === 'object' && !Array.isArray(fileConfig)) {+ const partial = fileConfig as Record<string, unknown>;+ const merged = { ...defaultSystemConfig } as Record<string, unknown>;+ for (const key of Object.keys(partial)) {+ if (partial[key] && typeof partial[key] === 'object' && !Array.isArray(partial[key])) {+ merged[key] = { ...(merged[key] as Record<string, unknown> || {}), ...(partial[key] as Record<string, unknown>) };+ }+ }+ config = merged as SystemConfig;+ source = 'file';+ path = configPath;+ }+ // Always break on first found config file β don't search further+ break;}} catch (error) {warnings.push(`Failed to load config from ${configPath}: ${(error as Error).message}`);diff --git a/v3/@claude-flow/shared/src/core/config/schema.ts b/v3/@claude-flow/shared/src/core/config/schema.tsindex dabfeaa95f..6257eb40f2 100644--- a/v3/@claude-flow/shared/src/core/config/schema.ts+++ b/v3/@claude-flow/shared/src/core/config/schema.ts@@ -156,13 +156,15 @@ export const OrchestratorConfigSchema = z.object({/*** Full system configuration schema+ * Uses passthrough() to accept unknown extra keys from user configs+ * without failing validation (e.g., simple key-value pairs, custom fields).*/export const SystemConfigSchema = z.object({orchestrator: OrchestratorConfigSchema,memory: MemoryConfigSchema.optional(),mcp: MCPServerConfigSchema.optional(),swarm: SwarmConfigSchema.optional(),-});+}).passthrough();/*** Export schema types