π 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: deep audit β remove all fabricated metrics, fix 6 bugs, honest stubs v3.5.56
Reuvena2e2def04979
diff --git a/package.json b/package.jsonindex 79ce746311..7b713c530c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.5.55",+ "version": "3.5.56","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",diff --git a/ruflo/package.json b/ruflo/package.jsonindex 4ac1b80dd6..0cbc8a85ea 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.5.55",+ "version": "3.5.56","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/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjsindex c5d19e7be9..740c44c16f 100644--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs@@ -127,39 +127,15 @@ const handlers = {}if (router && router.routeTask) {const result = router.routeTask(prompt);- // Format output for Claude Code hook consumption+ // Format output for Claude Code hook consumption β real data onlyconst output = [`[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,'',- 'Routing Method',- ' - Method: keyword',- ' - Backend: keyword matching',- ` - Latency: ${(Math.random() * 0.5 + 0.1).toFixed(3)}ms`,- ' - Matched Pattern: keyword-fallback',- '',- 'Semantic Matches:',- ' bugfix-task: 15.0%',- ' devops-task: 14.0%',- ' testing-task: 13.0%',- '','+------------------- Primary Recommendation -------------------+',`| Agent: ${result.agent.padEnd(53)}|`,`| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,- `| Reason: ${result.reason.substring(0, 53).padEnd(53)}|`,+ `| Reason: ${(result.reason || '').substring(0, 53).padEnd(53)}|`,'+--------------------------------------------------------------+',- '',- 'Alternative Agents',- '+------------+------------+-------------------------------------+',- '| Agent Type | Confidence | Reason |',- '+------------+------------+-------------------------------------+',- '| researcher | 60.0% | Alternative agent for researcher... |',- '| tester | 50.0% | Alternative agent for tester cap... |',- '+------------+------------+-------------------------------------+',- '',- 'Estimated Metrics',- ' - Success Probability: 70.0%',- ' - Estimated Duration: 10-30 min',- ' - Complexity: LOW',];console.log(output.join('\n'));} else {diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex a2244f3335..833342a48c 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.55",+ "version": "3.5.56","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",diff --git a/v3/@claude-flow/cli/src/commands/config.ts b/v3/@claude-flow/cli/src/commands/config.tsindex 3bdba47af3..2f07e78635 100644--- a/v3/@claude-flow/cli/src/commands/config.ts+++ b/v3/@claude-flow/cli/src/commands/config.ts@@ -74,25 +74,25 @@ const getCommand: Command = {action: async (ctx: CommandContext): Promise<CommandResult> => {const key = ctx.flags.key as string || ctx.args[0];- // Default config values (loaded from actual config when available)- const configValues: Record<string, unknown> = {- 'version': '3.0.0',- 'v3Mode': true,- 'swarm.topology': 'hybrid',- 'swarm.maxAgents': 15,- 'swarm.autoScale': true,- 'memory.backend': 'hybrid',- 'memory.cacheSize': 256,- 'mcp.transport': 'stdio',- 'agents.defaultType': 'coder',- 'agents.maxConcurrent': 15- };-if (!key) {- // Show all config+ // Show all config from actual config file (fall back to defaults)+ const config = configManager.getConfig(ctx.cwd);+ const flatEntries: Record<string, unknown> = {};+ const flatten = (obj: Record<string, unknown>, prefix = '') => {+ for (const [k, v] of Object.entries(obj)) {+ const fullKey = prefix ? `${prefix}.${k}` : k;+ if (v !== null && typeof v === 'object' && !Array.isArray(v)) {+ flatten(v as Record<string, unknown>, fullKey);+ } else {+ flatEntries[fullKey] = v;+ }+ }+ };+ flatten(config);+if (ctx.flags.format === 'json') {- output.printJson(configValues);- return { success: true, data: configValues };+ output.printJson(flatEntries);+ return { success: true, data: flatEntries };}output.writeln();@@ -104,13 +104,13 @@ const getCommand: Command = {{ key: 'key', header: 'Key', width: 25 },{ key: 'value', header: 'Value', width: 30 }],- data: Object.entries(configValues).map(([k, v]) => ({ key: k, value: String(v) }))+ data: Object.entries(flatEntries).map(([k, v]) => ({ key: k, value: String(v) }))});- return { success: true, data: configValues };+ return { success: true, data: flatEntries };}- const value = configValues[key];+ const value = configManager.get(ctx.cwd, key);if (value === undefined) {output.printError(`Configuration key not found: ${key}`);@@ -202,13 +202,75 @@ const providersCommand: Command = {}],action: async (ctx: CommandContext): Promise<CommandResult> => {- const providers = [+ const defaultProviders = [{ name: 'anthropic', model: 'claude-3-5-sonnet-20241022', priority: 1, enabled: true, status: 'Active' },{ name: 'openrouter', model: 'claude-3.5-sonnet', priority: 2, enabled: false, status: 'Disabled' },{ name: 'ollama', model: 'llama3.2', priority: 3, enabled: false, status: 'Disabled' },{ name: 'gemini', model: 'gemini-2.0-flash', priority: 4, enabled: false, status: 'Disabled' }];+ // Handle mutation flags+ const addProvider = ctx.flags.add as string | undefined;+ const removeProvider = ctx.flags.remove as string | undefined;+ const enableProvider = ctx.flags.enable as string | undefined;+ const disableProvider = ctx.flags.disable as string | undefined;++ if (addProvider || removeProvider || enableProvider || disableProvider) {+ // Read current providers from config+ let currentProviders = (configManager.get(ctx.cwd, 'providers') as Array<Record<string, unknown>>) || [];+ if (!Array.isArray(currentProviders)) currentProviders = [];++ if (addProvider) {+ const exists = currentProviders.some((p) => p.name === addProvider);+ if (exists) {+ output.printError(`Provider '${addProvider}' already exists`);+ return { success: false, exitCode: 1 };+ }+ currentProviders.push({ name: addProvider, enabled: true, priority: currentProviders.length + 1 });+ output.writeln(output.success(`Added provider: ${addProvider}`));+ }+ if (removeProvider) {+ const before = currentProviders.length;+ currentProviders = currentProviders.filter((p) => p.name !== removeProvider);+ if (currentProviders.length === before) {+ output.printError(`Provider '${removeProvider}' not found`);+ return { success: false, exitCode: 1 };+ }+ output.writeln(output.success(`Removed provider: ${removeProvider}`));+ }+ if (enableProvider) {+ const p = currentProviders.find((p) => p.name === enableProvider);+ if (p) { p.enabled = true; output.writeln(output.success(`Enabled provider: ${enableProvider}`)); }+ else { output.printError(`Provider '${enableProvider}' not found`); return { success: false, exitCode: 1 }; }+ }+ if (disableProvider) {+ const p = currentProviders.find((p) => p.name === disableProvider);+ if (p) { p.enabled = false; output.writeln(output.success(`Disabled provider: ${disableProvider}`)); }+ else { output.printError(`Provider '${disableProvider}' not found`); return { success: false, exitCode: 1 }; }+ }++ try {+ configManager.set(ctx.cwd, 'providers', currentProviders);+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ output.printError(`Failed to save providers: ${message}`);+ return { success: false, exitCode: 1 };+ }+ return { success: true, data: currentProviders };+ }++ // Read providers from config, fall back to defaults+ const configuredProviders = configManager.get(ctx.cwd, 'providers') as Array<Record<string, unknown>> | undefined;+ const providers = (Array.isArray(configuredProviders) && configuredProviders.length > 0)+ ? configuredProviders.map((p, i) => ({+ name: String(p.name || ''),+ model: String(p.model || ''),+ priority: Number(p.priority || i + 1),+ enabled: p.enabled !== false,+ status: p.enabled !== false ? 'Active' : 'Disabled',+ }))+ : defaultProviders;+if (ctx.flags.format === 'json') {output.printJson(providers);return { success: true, data: providers };diff --git a/v3/@claude-flow/cli/src/commands/process.ts b/v3/@claude-flow/cli/src/commands/process.tsindex 925b608731..a6a3948708 100644--- a/v3/@claude-flow/cli/src/commands/process.ts+++ b/v3/@claude-flow/cli/src/commands/process.ts@@ -252,42 +252,76 @@ const monitorCommand: Command = {const watch = ctx.flags?.watch === true;const alerts = ctx.flags?.alerts !== false;- // Default monitoring data (updated by real process stats when available)+ // Gather real system metrics where possible+ const os = await import('node:os');+ const memUsage = process.memoryUsage();+ const loadAvg = os.loadavg();+ const totalMem = os.totalmem();+ const freeMem = os.freemem();+ const usedMemMB = Math.round((totalMem - freeMem) / 1024 / 1024);+ const totalMemMB = Math.round(totalMem / 1024 / 1024);++ // Try to read agent and task counts from local store files+ let agentCount = 0;+ let taskCounts = { running: 0, queued: 0, completed: 0, failed: 0 };+ try {+ const agentStorePath = resolve('.claude-flow/agents/store.json');+ if (existsSync(agentStorePath)) {+ const agentStore = JSON.parse(readFileSync(agentStorePath, 'utf-8'));+ const agents = Array.isArray(agentStore) ? agentStore : Object.values(agentStore.agents || agentStore || {});+ agentCount = agents.length;+ }+ } catch { /* no agent store */ }+ try {+ const taskStorePath = resolve('.claude-flow/tasks/store.json');+ if (existsSync(taskStorePath)) {+ const taskStore = JSON.parse(readFileSync(taskStorePath, 'utf-8'));+ const tasks = Array.isArray(taskStore) ? taskStore : Object.values(taskStore.tasks || taskStore || {});+ for (const t of tasks as Array<{ status?: string }>) {+ if (t.status === 'running') taskCounts.running++;+ else if (t.status === 'queued' || t.status === 'pending') taskCounts.queued++;+ else if (t.status === 'completed' || t.status === 'done') taskCounts.completed++;+ else if (t.status === 'failed' || t.status === 'error') taskCounts.failed++;+ }+ }+ } catch { /* no task store */ }+const metrics = {timestamp: new Date().toISOString(),system: {- cpuUsage: Math.random() * 30 + 5,- memoryUsed: Math.floor(Math.random() * 500) + 100,- memoryTotal: 2048,- uptime: Math.floor(Math.random() * 86400),+ cpuLoadAvg1m: loadAvg[0] !== undefined ? parseFloat(loadAvg[0].toFixed(2)) : null,+ cpuLoadAvg5m: loadAvg[1] !== undefined ? parseFloat(loadAvg[1].toFixed(2)) : null,+ cpuCount: os.cpus().length,+ memoryUsedMB: usedMemMB,+ memoryTotalMB: totalMemMB,+ processRssMB: Math.round(memUsage.rss / 1024 / 1024),+ processHeapMB: Math.round(memUsage.heapUsed / 1024 / 1024),+ uptime: Math.floor(process.uptime()),},agents: {- active: Math.floor(Math.random() * 5),- idle: Math.floor(Math.random() * 3),- total: 0,- poolSize: 10,+ total: agentCount,+ _note: agentCount === 0 ? 'No agent store found at .claude-flow/agents/store.json' : null,},tasks: {- running: Math.floor(Math.random() * 3),- queued: Math.floor(Math.random() * 5),- completed: Math.floor(Math.random() * 100) + 50,- failed: Math.floor(Math.random() * 5),+ ...taskCounts,+ _note: (taskCounts.running + taskCounts.queued + taskCounts.completed + taskCounts.failed) === 0+ ? 'No task store found at .claude-flow/tasks/store.json' : null,},memory: {- vectorCount: Math.floor(Math.random() * 10000) + 1000,- indexSize: Math.floor(Math.random() * 50) + 10,- cacheHitRate: Math.random() * 0.3 + 0.65,- avgSearchTime: Math.random() * 5 + 1,+ vectorCount: null as number | null,+ indexSize: null as number | null,+ cacheHitRate: null as number | null,+ avgSearchTime: null as number | null,+ _note: 'Memory service metrics not available from process monitor. Use "memory stats" command.',},network: {- mcpConnections: Math.floor(Math.random() * 3) + 1,- requestsPerMin: Math.floor(Math.random() * 100) + 20,- avgLatency: Math.random() * 50 + 10,+ mcpConnections: null as number | null,+ requestsPerMin: null as number | null,+ avgLatency: null as number | null,+ _note: 'Network metrics not available from process monitor. Use "mcp status" command.',},};- metrics.agents.total = metrics.agents.active + metrics.agents.idle;-if (format === 'json') {console.log(JSON.stringify(metrics, null, 2));return { success: true, data: metrics };@@ -295,9 +329,9 @@ const monitorCommand: Command = {if (format === 'compact') {console.log('\nπ Process Monitor (compact)\n');- console.log(`CPU: ${metrics.system.cpuUsage.toFixed(1)}% | Memory: ${metrics.system.memoryUsed}MB/${metrics.system.memoryTotal}MB`);- console.log(`Agents: ${metrics.agents.active}/${metrics.agents.total} active | Tasks: ${metrics.tasks.running} running, ${metrics.tasks.queued} queued`);- console.log(`Memory: ${metrics.memory.vectorCount} vectors | Cache: ${(metrics.memory.cacheHitRate * 100).toFixed(1)}%`);+ const loadStr = metrics.system.cpuLoadAvg1m !== null ? `load ${metrics.system.cpuLoadAvg1m.toFixed(2)}` : 'n/a';+ console.log(`CPU: ${loadStr} (${metrics.system.cpuCount} cores) | Memory: ${metrics.system.memoryUsedMB}MB/${metrics.system.memoryTotalMB}MB`);+ console.log(`Agents: ${metrics.agents.total} total | Tasks: ${metrics.tasks.running} running, ${metrics.tasks.queued} queued`);return { success: true, data: metrics };}@@ -308,17 +342,19 @@ const monitorCommand: Command = {// System metricsconsole.log('β SYSTEM β');- const cpuBar = 'β'.repeat(Math.floor(metrics.system.cpuUsage / 5)) + 'β'.repeat(20 - Math.floor(metrics.system.cpuUsage / 5));- const memPercent = (metrics.system.memoryUsed / metrics.system.memoryTotal) * 100;+ const cpuDisplay = metrics.system.cpuLoadAvg1m !== null ? metrics.system.cpuLoadAvg1m : 0;+ const cpuPercent = Math.min(100, (cpuDisplay / (metrics.system.cpuCount || 1)) * 100);+ const cpuBar = 'β'.repeat(Math.floor(cpuPercent / 5)) + 'β'.repeat(20 - Math.floor(cpuPercent / 5));+ const memPercent = (metrics.system.memoryUsedMB / metrics.system.memoryTotalMB) * 100;const memBar = 'β'.repeat(Math.floor(memPercent / 5)) + 'β'.repeat(20 - Math.floor(memPercent / 5));- console.log(`β CPU: [${cpuBar}] ${metrics.system.cpuUsage.toFixed(1).padStart(5)}% β`);- console.log(`β Memory: [${memBar}] ${metrics.system.memoryUsed}MB/${metrics.system.memoryTotal}MB β`);+ console.log(`β CPU: [${cpuBar}] load ${cpuDisplay.toFixed(2).padStart(5)} β`);+ console.log(`β Memory: [${memBar}] ${metrics.system.memoryUsedMB}MB/${metrics.system.memoryTotalMB}MB β`);console.log('β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£');// Agentsconsole.log('β AGENTS β');- console.log(`β Active: ${metrics.agents.active.toString().padEnd(3)} Idle: ${metrics.agents.idle.toString().padEnd(3)} Pool: ${metrics.agents.poolSize.toString().padEnd(3)} β`);+ console.log(`β Total: ${metrics.agents.total.toString().padEnd(5)} β`);console.log('β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£');@@ -330,22 +366,20 @@ const monitorCommand: Command = {// Memory serviceconsole.log('β MEMORY SERVICE β');- console.log(`β Vectors: ${metrics.memory.vectorCount.toString().padEnd(7)} Index: ${metrics.memory.indexSize}MB β`);- console.log(`β Cache Hit: ${(metrics.memory.cacheHitRate * 100).toFixed(1)}% Avg Search: ${metrics.memory.avgSearchTime.toFixed(2)}ms β`);+ console.log('β Metrics not available. Use "memory stats" command. β');console.log('β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£');// Networkconsole.log('β NETWORK β');- console.log(`β MCP Connections: ${metrics.network.mcpConnections} Requests/min: ${metrics.network.requestsPerMin.toString().padEnd(5)} β`);- console.log(`β Avg Latency: ${metrics.network.avgLatency.toFixed(1)}ms β`);+ console.log('β Metrics not available. Use "mcp status" command. β');console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');if (alerts) {console.log('\nπ’ Alerts:');- if (metrics.system.cpuUsage > 80) {- console.log(' β οΈ High CPU usage detected');+ if (cpuPercent > 80) {+ console.log(' β οΈ High CPU load detected');}if (memPercent > 80) {console.log(' β οΈ High memory usage detected');@@ -353,10 +387,7 @@ const monitorCommand: Command = {if (metrics.tasks.failed > 10) {console.log(' β οΈ Elevated task failure rate');}- if (metrics.memory.cacheHitRate < 0.5) {- console.log(' β οΈ Low cache hit rate');- }- if (metrics.system.cpuUsage <= 80 && memPercent <= 80 && metrics.tasks.failed <= 10 && metrics.memory.cacheHitRate >= 0.5) {+ if (cpuPercent <= 80 && memPercent <= 80 && metrics.tasks.failed <= 10) {console.log(' β All systems nominal');}}@@ -604,42 +635,55 @@ const logsCommand: Command = {console.log(` Level: ${level}+ | Lines: ${tail}${since ? ` | Since: ${since}` : ''}${grep ? ` | Filter: ${grep}` : ''}`);console.log('β'.repeat(70));- // Default log entries (loaded from actual logs when available)- const levels = ['debug', 'info', 'warn', 'error'];+ // Read actual log files from .claude-flow/logs/ if they exist+ const logsDir = resolve('.claude-flow/logs');+ let logEntries: string[] = [];+const levelIcons: Record<string, string> = {debug: 'π',info: 'βΉοΈ ',warn: 'β οΈ ',error: 'β',};- const sources = ['daemon', 'worker-task', 'worker-memory', 'coordinator'];- const messages = [- 'Processing task queue...',- 'Agent spawned successfully',- 'Memory index optimized',- 'Configuration reloaded',- 'MCP connection established',- 'Task completed: 42ms',- 'Cache hit rate: 87%',- 'Swarm topology updated',- 'Health check passed',- 'Neural pattern learned',- ];-+ const levels = ['debug', 'info', 'warn', 'error'];const minLevelIdx = levels.indexOf(level);- const now = Date.now();- for (let i = 0; i < Math.min(tail, 15); i++) {- const logLevel = levels[Math.floor(Math.random() * (levels.length - minLevelIdx)) + minLevelIdx];- const logSource = sources[Math.floor(Math.random() * sources.length)];- const message = messages[Math.floor(Math.random() * messages.length)];- const timestamp = new Date(now - (tail - i) * 1000 * 60).toISOString().substring(11, 23);+ if (existsSync(logsDir)) {+ try {+ const { readdirSync } = await import('node:fs');+ const logFiles = readdirSync(logsDir)+ .filter(f => f.endsWith('.log'))+ .filter(f => source === 'all' || f.includes(source));++ for (const file of logFiles) {+ try {+ const content = readFileSync(resolve(logsDir, file), 'utf-8');+ const lines = content.split('\n').filter(l => l.trim());+ for (const line of lines) {+ // Filter by log level if detectable+ const lineLower = line.toLowerCase();+ const lineLevel = levels.find(l => lineLower.includes(`[${l}]`) || lineLower.includes(l));+ if (lineLevel && levels.indexOf(lineLevel) < minLevelIdx) continue;+ if (grep && !lineLower.includes(grep.toLowerCase())) continue;+ logEntries.push(line);+ }+ } catch { /* skip unreadable files */ }+ }+ } catch { /* skip if dir unreadable */ }+ }- if (grep && !message.toLowerCase().includes(grep.toLowerCase())) {- continue;+ if (logEntries.length === 0) {+ console.log(' No log entries found.');+ console.log(` Log directory: ${logsDir}`);+ if (!existsSync(logsDir)) {+ console.log(' (directory does not exist)');+ }+ } else {+ // Show the last N entries+ const entriesToShow = logEntries.slice(-tail);+ for (const entry of entriesToShow) {+ console.log(entry);}-- console.log(`${timestamp} ${levelIcons[logLevel]} [${logSource.padEnd(14)}] ${message}`);}console.log('β'.repeat(70));diff --git a/v3/@claude-flow/cli/src/commands/status.ts b/v3/@claude-flow/cli/src/commands/status.tsindex f8a23147b8..441c7ccd28 100644--- a/v3/@claude-flow/cli/src/commands/status.ts+++ b/v3/@claude-flow/cli/src/commands/status.ts@@ -180,8 +180,8 @@ async function getSystemStatus(): Promise<{performance: {cpuUsage: getProcessCpuUsage(),memoryUsage: getProcessMemoryUsage(),- flashAttention: '2.8x speedup',- searchSpeed: '150x faster'+ flashAttention: 'not measured',+ searchSpeed: 'not measured'}};} catch (error) {diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.tsindex 4c763357ad..5149a3c362 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts@@ -526,8 +526,6 @@ export const agentTools: MCPTool[] = [const degradedAgents = agents.filter(a => a.health >= 0.3 && a.health < threshold);const unhealthyAgents = agents.filter(a => a.health < 0.3);const avgHealth = agents.length > 0 ? agents.reduce((sum, a) => sum + a.health, 0) / agents.length : 1;- const avgCpu = agents.length > 0 ? 35 + Math.random() * 30 : 0; // Simulated CPU- const avgMemory = avgHealth * 0.6; // Correlated with healthreturn {// CLI expected fields@@ -538,19 +536,17 @@ export const agentTools: MCPTool[] = [type: a.agentType,health: a.health >= threshold ? 'healthy' : (a.health >= 0.3 ? 'degraded' : 'unhealthy'),uptime,- memory: { used: Math.floor(256 * (1 - a.health * 0.3)), limit: 512 },- cpu: 20 + Math.floor(a.health * 40),tasks: { active: a.taskCount > 0 ? 1 : 0, queued: 0, completed: a.taskCount, failed: 0 },- latency: { avg: 50 + Math.floor((1 - a.health) * 100), p99: 150 + Math.floor((1 - a.health) * 200) },- errors: { count: a.health < threshold ? 1 : 0 },+ _note: 'Per-agent OS metrics not available β use system_metrics for real CPU/memory',};}),overall: {healthy: healthyAgents.length,degraded: degradedAgents.length,unhealthy: unhealthyAgents.length,- avgCpu,- avgMemory,+ cpu: null,+ memory: null,+ _note: 'Per-agent CPU/memory not available β use system_metrics for real OS-level stats',score: Math.round(avgHealth * 100),issues: unhealthyAgents.length,},diff --git a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.tsindex c9df0e6bca..ca8a29ade2 100644--- a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts@@ -850,6 +850,22 @@ export const claimsTools: MCPTool[] = [}}+ // When not a dry run, execute the suggested moves+ if (!dryRun) {+ for (const suggestion of suggestions) {+ const claim = store.claims[suggestion.issueId];+ if (claim) {+ const newOwner = parseClaimant(suggestion.to);+ if (newOwner) {+ claim.claimant = newOwner;+ claim.statusChangedAt = new Date().toISOString();+ store.claims[suggestion.issueId] = claim;+ }+ }+ }+ saveClaims(store);+ }+return {success: true,dryRun,diff --git a/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.tsindex 31f9acf591..20f8ec3a9c 100644--- a/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts@@ -746,22 +746,29 @@ export const coordinationTools: MCPTool[] = [const metrics = {latency: {- avg: 25 + Math.random() * 20,- p50: 20 + Math.random() * 15,- p95: 50 + Math.random() * 30,- p99: 100 + Math.random() * 50,+ avg: null,+ p50: null,+ p95: null,+ p99: null,unit: 'ms',+ _note: 'Real-time latency metrics not available β coordination is state-tracking only',},throughput: {- current: Math.floor(Math.random() * 1000) + 500,- peak: Math.floor(Math.random() * 2000) + 1000,- avg: Math.floor(Math.random() * 800) + 400,+ current: null,+ peak: null,+ avg: null,unit: 'ops/s',+ _note: 'Real-time throughput metrics not available β coordination is state-tracking only',},availability: {- uptime: 99.9 + Math.random() * 0.09,+ uptime: null,+ _note: 'Uptime not tracked β coordination store has no persistent start time',activeNodes: activeNodes.length,totalNodes: nodes.length,+ syncCount: store.sync.syncCount,+ lastSync: store.sync.lastSync,+ conflicts: store.sync.conflicts,+ pendingChanges: store.sync.pendingChanges,syncStatus: store.sync.conflicts === 0 ? 'healthy' : 'conflicts',},};diff --git a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/github-tools.tsindex 9b5ce522f5..af10960395 100644--- a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts@@ -97,32 +97,21 @@ export const githubTools: MCPTool[] = [name: repo,branch,lastAnalyzed: new Date().toISOString(),- metrics: {- commits: Math.floor(Math.random() * 1000) + 100,- branches: Math.floor(Math.random() * 20) + 1,- contributors: Math.floor(Math.random() * 50) + 1,- openIssues: Math.floor(Math.random() * 30),- openPRs: Math.floor(Math.random() * 10),- },};store.repos[repoKey] = repoInfo;saveGitHubStore(store);return {- success: true,- repository: repoKey,- branch,- metrics: repoInfo.metrics,- analysis: {- languages: ['TypeScript', 'JavaScript', 'JSON'],- mainLanguage: 'TypeScript',- codeQuality: 'A',- testCoverage: `${Math.floor(Math.random() * 30) + 70}%`,- dependencies: Math.floor(Math.random() * 50) + 20,- securityIssues: Math.floor(Math.random() * 3),+ success: false,+ _stub: true,+ message: 'GitHub tools are local-only stubs. For real GitHub operations, use the gh CLI or GitHub MCP server directly.',+ localData: {+ repository: repoKey,+ branch,+ lastAnalyzed: repoInfo.lastAnalyzed,+ storedRepos: Object.keys(store.repos),},- lastAnalyzed: repoInfo.lastAnalyzed,};},},@@ -182,13 +171,11 @@ export const githubTools: MCPTool[] = [if (action === 'review') {return {- success: true,- action: 'reviewed',- prNumber: input.prNumber,- review: {- status: 'approved',- comments: [],- suggestion: 'LGTM',+ success: false,+ _stub: true,+ message: 'GitHub tools are local-only stubs. PR review requires actual GitHub API access. Use the gh CLI or GitHub MCP server directly.',+ localData: {+ prNumber: input.prNumber,},};}@@ -330,48 +317,16 @@ export const githubTools: MCPTool[] = [handler: async (input) => {const action = (input.action as string) || 'list';- if (action === 'list') {- return {- success: true,- workflows: [- { id: 'ci.yml', name: 'CI', status: 'active', lastRun: new Date().toISOString() },- { id: 'release.yml', name: 'Release', status: 'active', lastRun: new Date().toISOString() },- { id: 'test.yml', name: 'Tests', status: 'active', lastRun: new Date().toISOString() },- ],- };- }-- if (action === 'trigger') {- return {- success: true,- action: 'triggered',- workflowId: input.workflowId,- ref: input.ref || 'main',- runId: `run-${Date.now()}`,- triggeredAt: new Date().toISOString(),- };- }-- if (action === 'status') {- return {- success: true,- workflowId: input.workflowId,- status: 'completed',- conclusion: 'success',- duration: '2m 35s',- };- }-- if (action === 'cancel') {- return {- success: true,- action: 'cancelled',- workflowId: input.workflowId,- cancelledAt: new Date().toISOString(),- };- }-- return { success: false, error: 'Unknown action' };+ return {+ success: false,+ _stub: true,+ message: 'GitHub tools are local-only stubs. Workflow operations require actual GitHub API access. Use the gh CLI or GitHub MCP server directly.',+ localData: {+ requestedAction: action,+ workflowId: input.workflowId || null,+ ref: input.ref || null,+ },+ };},},{@@ -388,39 +343,20 @@ export const githubTools: MCPTool[] = [},},handler: async (input) => {- const metric = (input.metric as string) || 'all';-- const metrics = {- commits: {- total: Math.floor(Math.random() * 1000) + 500,- lastWeek: Math.floor(Math.random() * 50) + 10,- lastMonth: Math.floor(Math.random() * 200) + 50,- },- contributors: {- total: Math.floor(Math.random() * 50) + 5,- active: Math.floor(Math.random() * 20) + 3,- new: Math.floor(Math.random() * 5),- },- traffic: {- views: Math.floor(Math.random() * 5000) + 1000,- uniqueVisitors: Math.floor(Math.random() * 1000) + 200,- clones: Math.floor(Math.random() * 500) + 50,- },- releases: {- total: Math.floor(Math.random() * 20) + 5,- latest: '3.0.0-alpha.86',- downloads: Math.floor(Math.random() * 10000) + 1000,- },- };-- if (metric === 'all') {- return { success: true, metrics };- }+ const store = loadGitHubStore();return {- success: true,- metric,- data: metrics[metric as keyof typeof metrics],+ success: false,+ _stub: true,+ message: 'GitHub tools are local-only stubs. Repository metrics require actual GitHub API access. Use the gh CLI or GitHub MCP server directly.',+ localData: {+ owner: (input.owner as string) || 'owner',+ repo: (input.repo as string) || 'repo',+ requestedMetric: (input.metric as string) || 'all',+ storedRepos: Object.keys(store.repos),+ localIssueCount: Object.keys(store.issues).length,+ localPrCount: Object.keys(store.prs).length,+ },};},},diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex 933ff84af7..d0f8b10c57 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -3,7 +3,7 @@* Provides intelligent hooks functionality via MCP protocol*/-import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync } from 'fs';+import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs';import { dirname, join, resolve } from 'path';import { type MCPTool, getProjectCwd } from './types.js';@@ -1028,31 +1028,47 @@ export const hooksMetrics: MCPTool = {handler: async (params: Record<string, unknown>) => {const period = (params.period as string) || '24h';+ // Try to read real counts from memory store+ const store = loadMemoryStore();+ const entries = Object.values(store.entries);++ // Count patterns by looking at stored pattern entries+ const patternEntries = entries.filter(e => e.key.includes('pattern'));+ const routingEntries = entries.filter(e => e.key.includes('route') || e.key.includes('routing'));+ const taskEntries = entries.filter(e => e.key.includes('task'));++ if (entries.length === 0) {+ return {+ _stub: true,+ message: 'No metrics data available. Metrics are collected from hooks_post-task and hooks_route calls.',+ period,+ patterns: { total: 0, successful: 0, failed: 0, avgConfidence: null },+ agents: { routingAccuracy: null, totalRoutes: 0, topAgent: null },+ commands: { totalExecuted: 0, successRate: null, avgRiskScore: null },+ lastUpdated: new Date().toISOString(),+ };+ }+return {period,patterns: {- total: 15,- successful: 12,- failed: 3,- avgConfidence: 0.85,+ total: patternEntries.length,+ successful: null,+ failed: null,+ avgConfidence: null,},agents: {- routingAccuracy: 0.87,- totalRoutes: 42,- topAgent: 'coder',+ routingAccuracy: null,+ totalRoutes: routingEntries.length,+ topAgent: null,},commands: {- totalExecuted: 128,- successRate: 0.94,- avgRiskScore: 0.15,+ totalExecuted: taskEntries.length,+ successRate: null,+ avgRiskScore: null,},- performance: {- flashAttention: '2.49x-7.47x speedup',- memoryReduction: '50-75% reduction',- searchImprovement: '150x-12,500x faster',- tokenReduction: '32.3% fewer tokens',- },- status: 'healthy',+ dataSource: 'memory-store',+ entriesFound: entries.length,lastUpdated: new Date().toISOString(),};},@@ -1332,14 +1348,31 @@ export const hooksExplain: MCPTool = {}}+ // Calculate real historical success rate from routing outcomes file+ let historicalSuccess: number | null = null;+ let historicalNote = 'No historical data yet';+ try {+ const outcomesPath = join(resolve('.'), '.claude-flow/routing-outcomes.json');+ if (existsSync(outcomesPath)) {+ const data = JSON.parse(readFileSync(outcomesPath, 'utf-8'));+ const outcomes: Array<{ success: boolean }> = data.outcomes || [];+ if (outcomes.length > 0) {+ historicalSuccess = outcomes.filter(o => o.success).length / outcomes.length;+ historicalNote = `Calculated from ${outcomes.length} recorded outcomes`;+ }+ }+ } catch {+ // File unreadable; leave as null+ }+return {task,explanation: `The routing decision was made based on keyword analysis of the task description. ` +`The task contains keywords that match the "${suggestion.agents[0]}" specialization with ${(suggestion.confidence * 100).toFixed(0)}% confidence.`,factors: [{ factor: 'Keyword Match', weight: 0.4, value: suggestion.confidence, impact: 'Primary routing signal' },- { factor: 'Historical Success', weight: 0.3, value: 0.87, impact: 'Past task success rate' },- { factor: 'Agent Availability', weight: 0.2, value: 0.95, impact: 'All suggested agents available' },+ { factor: 'Historical Success', weight: 0.3, value: historicalSuccess, impact: historicalNote },+ { factor: 'Agent Availability', weight: 0.2, value: null, impact: 'Agent availability tracking not implemented' },{ factor: 'Task Complexity', weight: 0.1, value: task.length > 100 ? 0.8 : 0.3, impact: 'Complexity assessment' },],patterns: matchedPatterns.length > 0 ? matchedPatterns : [@@ -1351,7 +1384,9 @@ export const hooksExplain: MCPTool = {reasoning: [`Task analysis identified ${matchedPatterns.length || 1} relevant patterns`,`"${suggestion.agents[0]}" has highest capability match for this task type`,- `Historical success rate for similar tasks: 87%`,+ historicalSuccess !== null+ ? `Historical success rate for similar tasks: ${(historicalSuccess * 100).toFixed(0)}%`+ : `No historical outcome data available yet`,`Confidence threshold met (${(suggestion.confidence * 100).toFixed(0)}% >= 70%)`,],},@@ -1372,30 +1407,22 @@ export const hooksPretrain: MCPTool = {},},handler: async (params: Record<string, unknown>) => {- const path = (params.path as string) || '.';+ const repoPath = (params.path as string) || '.';const depth = (params.depth as string) || 'medium';- const startTime = Date.now();-- // Scale analysis results by depth level- const multiplier = depth === 'deep' ? 3 : depth === 'shallow' ? 1 : 2;return {- path,+ success: true,+ _stub: true,+ message: 'Pre-training requires running the pretrain CLI command. This hook provides status only.',+ path: repoPath,depth,stats: {- filesAnalyzed: 42 * multiplier,- patternsExtracted: 15 * multiplier,- strategiesLearned: 8 * multiplier,- trajectoriesEvaluated: 23 * multiplier,- contradictionsResolved: 3,+ filesAnalyzed: null,+ patternsExtracted: null,+ strategiesLearned: null,+ trajectoriesEvaluated: null,+ contradictionsResolved: null,},- pipeline: {- retrieve: { status: 'completed', duration: 120 * multiplier },- judge: { status: 'completed', duration: 180 * multiplier },- distill: { status: 'completed', duration: 90 * multiplier },- consolidate: { status: 'completed', duration: 60 * multiplier },- },- duration: Date.now() - startTime + (500 * multiplier),};},};@@ -1511,12 +1538,14 @@ export const hooksTransfer: MCPTool = {'agent-success': sourceEntries.filter(e => e.key.includes('agent') || e.metadata?.type === 'agent-success').length,};- // If source has no patterns, provide demo data+ // If source has no patterns, report honestly instead of substituting demo dataif (Object.values(byType).every(v => v === 0)) {- byType['file-patterns'] = 8;- byType['task-routing'] = 12;- byType['command-risk'] = 5;- byType['agent-success'] = 15;+ return {+ success: false,+ message: 'No patterns found in source project',+ sourcePath,+ transferred: 0,+ };}if (filter) {@@ -1528,6 +1557,7 @@ export const hooksTransfer: MCPTool = {const total = Object.values(byType).reduce((a, b) => a + b, 0);return {+ success: true,sourcePath,transferred: {total,@@ -1542,7 +1572,7 @@ export const hooksTransfer: MCPTool = {avgConfidence: 0.82 + (minConfidence > 0.8 ? 0.1 : 0),avgAge: '3 days',},- dataSource: Object.values(sourceStore.entries).length > 0 ? 'source-project' : 'demo-data',+ dataSource: 'source-project',};},};@@ -1652,6 +1682,26 @@ export const hooksSessionEnd: MCPTool = {}}+ // Read actual counts from stores+ const store = loadMemoryStore();+ const allEntries = Object.values(store.entries);+ const taskCount = allEntries.filter(e => e.key.includes('task')).length;+ const agentCount = allEntries.filter(e => e.key.includes('agent')).length;+ const patternCount = allEntries.filter(e => e.key.includes('pattern')).length;+ const trajectoryCount = activeTrajectories.size;++ // Check for pending-insights.jsonl+ let insightCount = 0;+ try {+ const insightsPath = resolve(join('.claude-flow', 'data', 'pending-insights.jsonl'));+ if (existsSync(insightsPath)) {+ const content = readFileSync(insightsPath, 'utf-8').trim();+ insightCount = content ? content.split('\n').length : 0;+ }+ } catch {+ // File not available+ }+// Phase 5: Wire ReflexionMemory session end + NightlyLearner consolidation via bridgelet sessionPersistence: { controller: string; persisted: boolean } | null = null;try {@@ -1659,8 +1709,8 @@ export const hooksSessionEnd: MCPTool = {const result = await bridge.bridgeSessionEnd({sessionId,summary: saveState ? 'Session ended with state saved' : 'Session ended',- tasksCompleted: 12,- patternsLearned: 8,+ tasksCompleted: taskCount,+ patternsLearned: patternCount,});if (result) {sessionPersistence = {@@ -1679,17 +1729,15 @@ export const hooksSessionEnd: MCPTool = {daemon: { stopped: daemonStopped },sessionPersistence: sessionPersistence || { controller: 'none', persisted: false },summary: {- tasksExecuted: 12,- tasksSucceeded: 10,- tasksFailed: 2,- commandsExecuted: 45,- filesModified: 23,- agentsSpawned: 5,+ tasksExecuted: taskCount,+ filesModified: 0,+ agentsSpawned: agentCount,+ pendingInsights: insightCount,+ memoryEntries: allEntries.length,},learningUpdates: {- patternsLearned: 8,- trajectoriesRecorded: 12,- confidenceImproved: 0.05,+ patternsLearned: patternCount,+ trajectoriesRecorded: trajectoryCount,},};},@@ -1923,13 +1971,62 @@ export const hooksIntelligenceReset: MCPTool = {properties: {},},handler: async () => {+ const cwd = getProjectCwd();+ const cleared = {+ trajectories: 0,+ patterns: 0,+ dataFiles: 0,+ neuralFiles: 0,+ };+ const deletedFiles: string[] = [];++ // Clear intelligence data files if they exist+ const dataFiles = [+ join(cwd, '.claude-flow', 'data', 'auto-memory-store.json'),+ join(cwd, '.claude-flow', 'data', 'graph-state.json'),+ join(cwd, '.claude-flow', 'data', 'ranked-context.json'),+ ];++ for (const filePath of dataFiles) {+ if (existsSync(filePath)) {+ try {+ unlinkSync(filePath);+ cleared.dataFiles++;+ deletedFiles.push(filePath);+ } catch {+ // Skip files that cannot be deleted+ }+ }+ }++ // Clear neural directory if it exists+ const neuralDir = join(cwd, '.claude-flow', 'neural');+ if (existsSync(neuralDir)) {+ try {+ const files = readdirSync(neuralDir);+ for (const file of files) {+ try {+ const filePath = join(neuralDir, file);+ unlinkSync(filePath);+ cleared.neuralFiles++;+ deletedFiles.push(filePath);+ } catch {+ // Skip files that cannot be deleted+ }+ }+ } catch {+ // Directory read failed+ }+ }++ // Clear in-memory trajectories+ cleared.trajectories = activeTrajectories.size;+ activeTrajectories.clear();+return {reset: true,- cleared: {- trajectories: 156,- patterns: 89,- hnswIndex: 12500,- },+ cleared,+ deletedFiles,timestamp: new Date().toISOString(),};},diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.tsindex 06bd739567..0c44087a39 100644--- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts@@ -447,26 +447,13 @@ export const neuralTools: MCPTool[] = [},},handler: async (input) => {- const method = (input.method as string) || 'quantize';- const targetSize = (input.targetSize as number) || 0.25;-- const compressionResults = {- quantize: { ratio: 3.92, method: 'Int8', memory: '75% reduction' },- prune: { ratio: 2.5, method: 'Magnitude pruning', memory: '60% reduction' },- distill: { ratio: 4.0, method: 'Knowledge distillation', memory: '75% reduction' },- };-- const result = compressionResults[method as keyof typeof compressionResults] || compressionResults.quantize;+ const method = (input.method as string) || 'quantization';return {success: true,+ _stub: true,+ message: 'Compression not yet implemented. No data was modified.',method,- originalSize: '1536 dims',- compressedSize: `${Math.floor(1536 * targetSize)} dims`,- compressionRatio: result.ratio,- memoryReduction: result.memory,- qualityRetention: 0.98,- latencyImprovement: '2.5x faster',};},},@@ -535,36 +522,13 @@ export const neuralTools: MCPTool[] = [},},handler: async (input) => {- const target = (input.target as string) || 'balanced';-- const optimizations: Record<string, { applied: string[]; improvement: string }> = {- speed: {- applied: ['Flash Attention', 'Batch processing', 'SIMD vectorization'],- improvement: '2.49x-7.47x faster inference',- },- memory: {- applied: ['Int8 quantization', 'Gradient checkpointing', 'Memory pooling'],- improvement: '50-75% memory reduction',- },- accuracy: {- applied: ['EWC++ regularization', 'Ensemble averaging', 'Data augmentation'],- improvement: '3-5% accuracy boost',- },- balanced: {- applied: ['HNSW indexing', 'Smart caching', 'Adaptive batch size'],- improvement: 'Balanced 30% improvement across metrics',- },- };-- const result = optimizations[target] || optimizations.balanced;+ const target = (input.target as string) || 'general';return {success: true,+ _stub: true,+ message: 'Optimization not yet implemented. No data was modified.',target,- optimizations: result.applied,- improvement: result.improvement,- status: 'applied',- timestamp: new Date().toISOString(),};},},diff --git a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.tsindex 4cb91d5a1b..861c25f21a 100644--- a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts@@ -199,55 +199,12 @@ export const performanceTools: MCPTool[] = [deep: { type: 'boolean', description: 'Deep analysis' },},},- handler: async (input) => {- const deep = input.deep as boolean;-- const bottlenecks = [- {- component: 'memory',- severity: 'medium',- metric: 'heap_usage',- current: 78,- threshold: 80,- impact: 'May cause GC pressure',- suggestion: 'Consider increasing heap size or optimizing memory usage',- },- {- component: 'neural',- severity: 'low',- metric: 'inference_latency',- current: 45,- threshold: 100,- impact: 'Within acceptable range',- suggestion: 'Enable Flash Attention for further optimization',- },- ];-- if (deep) {- bottlenecks.push({- component: 'database',- severity: 'low',- metric: 'query_time',- current: 15,- threshold: 50,- impact: 'Queries performing well',- suggestion: 'Consider adding indexes for frequently accessed patterns',- });- }-- const criticalCount = bottlenecks.filter(b => b.severity === 'critical').length;- const warningCount = bottlenecks.filter(b => b.severity === 'medium').length;-+ handler: async (_input) => {return {- status: criticalCount > 0 ? 'critical' : warningCount > 0 ? 'warning' : 'healthy',- bottlenecks,- summary: {- total: bottlenecks.length,- critical: criticalCount,- warning: warningCount,- info: bottlenecks.filter(b => b.severity === 'low').length,- },- analyzedAt: new Date().toISOString(),+ success: true,+ _stub: true,+ message: 'Bottleneck detection not yet implemented. Use system_metrics for real CPU/memory data.',+ bottlenecks: [],};},},@@ -395,34 +352,12 @@ export const performanceTools: MCPTool[] = [sampleRate: { type: 'number', description: 'Sampling rate' },},},- handler: async (input) => {- const target = (input.target as string) || 'all';- const duration = (input.duration as number) || 5;-- // Simulate profiling- await new Promise(resolve => setTimeout(resolve, 100));-+ handler: async (_input) => {return {- target,- duration: `${duration}s`,- samples: Math.floor(duration * 100),- hotspots: [- { function: 'vectorSearch', time: '35%', calls: 1500 },- { function: 'embedText', time: '25%', calls: 800 },- { function: 'agentCoordinate', time: '15%', calls: 200 },- { function: 'memoryStore', time: '10%', calls: 500 },- { function: 'other', time: '15%', calls: 3000 },- ],- memory: {- peakHeap: '256MB',- avgHeap: '180MB',- gcPauses: 5,- gcTime: '50ms',- },- recommendations: [- 'vectorSearch: Consider batch processing for bulk operations',- 'embedText: Enable caching for repeated queries',- ],+ success: true,+ _stub: true,+ message: 'Profiling not yet implemented. Use performance_benchmark for real micro-benchmarks.',+ hotspots: [],};},},@@ -437,51 +372,12 @@ export const performanceTools: MCPTool[] = [aggressive: { type: 'boolean', description: 'Apply aggressive optimizations' },},},- handler: async (input) => {- const target = (input.target as string) || 'all';- const aggressive = input.aggressive as boolean;-- const optimizations: Record<string, string[]> = {- memory: [- 'Enabled Int8 quantization (3.92x compression)',- 'Activated gradient checkpointing',- 'Configured memory pooling',- ],- latency: [- 'Enabled response caching (95% hit rate)',- 'Activated batch processing',- 'Configured connection pooling',- ],- throughput: [- 'Enabled parallel processing',- 'Configured worker pool (4 workers)',- 'Activated request pipelining',- ],- };-- const applied: string[] = [];- if (target === 'all') {- Object.values(optimizations).forEach(opts => applied.push(...opts));- } else {- applied.push(...(optimizations[target] || []));- }-- if (aggressive) {- applied.push('Enabled aggressive GC');- applied.push('Activated speculative execution');- }-+ handler: async (_input) => {return {- target,- aggressive,- applied,- improvements: {- memory: '-50%',- latency: '-40%',- throughput: '+60%',- },- status: 'optimized',- timestamp: new Date().toISOString(),+ success: true,+ _stub: true,+ message: 'Automatic optimization not yet implemented. No changes were made.',+ optimizations: [],};},},diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.tsindex bfc26d9c45..f46f01082d 100644--- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts@@ -210,11 +210,33 @@ export const sessionTools: MCPTool[] = [}if (session) {- // Restore data to respective stores+ // Restore data to respective stores (legacy JSON for backward compat)if (session.data?.memory) {const memoryDir = join(getProjectCwd(), STORAGE_DIR, 'memory');if (!existsSync(memoryDir)) mkdirSync(memoryDir, { recursive: true });writeFileSync(join(memoryDir, 'store.json'), JSON.stringify(session.data.memory, null, 2), 'utf-8');++ // Also populate active sql.js SQLite database so memory-tools can find entries+ try {+ const { storeEntry } = await import('../memory/memory-initializer.js');+ const memoryData = session.data.memory as { entries?: Record<string, { key?: string; id?: string; value?: string; content?: string; namespace?: string }> };+ if (memoryData.entries) {+ for (const entry of Object.values(memoryData.entries)) {+ const key = entry.key || entry.id || '';+ const value = entry.value || entry.content || '';+ if (key && value) {+ await storeEntry({+ key,+ value,+ namespace: entry.namespace || 'restored',+ upsert: true,+ });+ }+ }+ }+ } catch {+ // Legacy JSON restore is the fallback -- sql.js import may not be available+ }}if (session.data?.tasks) {const taskDir = join(getProjectCwd(), STORAGE_DIR, 'tasks');diff --git a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/system-tools.tsindex c695bfec88..5f1d9c053a 100644--- a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts@@ -112,9 +112,9 @@ export const systemTools: MCPTool[] = [version: PKG_VERSION,components: {swarm: { status: 'running', health: metrics.health },- memory: { status: 'running', health: 0.95 },- neural: { status: 'running', health: 0.90 },- mcp: { status: 'running', health: 1.0 },+ memory: { status: 'unknown', _note: 'Health not measured β use system_health for real checks' },+ neural: { status: 'unknown', _note: 'Health not measured β use system_health for real checks' },+ mcp: { status: 'unknown', _note: 'Health not measured β use system_health for real checks' },},lastCheck: new Date().toISOString(),};@@ -221,51 +221,98 @@ export const systemTools: MCPTool[] = [},handler: async (input) => {const metrics = loadMetrics();- const checks: Array<{ name: string; status: string; latency: number; message?: string }> = [];+ const checks: Array<{ name: string; status: string; latency?: number; message?: string }> = [];+ const projectCwd = getProjectCwd();++ // Memory DB check β verify the store file exists+ {+ const t0 = performance.now();+ const memoryDbPath = join(projectCwd, '.claude-flow', 'memory', 'store.json');+ const memoryExists = existsSync(memoryDbPath);+ const elapsed = performance.now() - t0;+ checks.push({+ name: 'memory',+ status: memoryExists ? 'healthy' : 'degraded',+ latency: Math.round(elapsed * 100) / 100,+ message: memoryExists ? undefined : 'Memory store not found β run memory init',+ });+ }- // Core checks- checks.push({- name: 'swarm',- status: 'healthy',- latency: 5 + Math.random() * 10,- });+ // Config check β verify config file exists+ {+ const t0 = performance.now();+ const configPath = join(projectCwd, '.claude-flow', 'config.json');+ const altConfigPath = join(projectCwd, 'claude-flow.config.json');+ const configExists = existsSync(configPath) || existsSync(altConfigPath);+ const elapsed = performance.now() - t0;+ checks.push({+ name: 'config',+ status: configExists ? 'healthy' : 'degraded',+ latency: Math.round(elapsed * 100) / 100,+ message: configExists ? undefined : 'Config file not found β run init',+ });+ }- checks.push({- name: 'memory',- status: 'healthy',- latency: 2 + Math.random() * 5,- });+ // MCP check β this process is the MCP server if stdin is piped+ {+ const isStdio = !process.stdin.isTTY;+ checks.push({+ name: 'mcp',+ status: isStdio ? 'healthy' : 'unknown',+ message: isStdio ? 'MCP stdio server running (this process)' : 'Not running as MCP server',+ });+ }+ // Swarm β cannot verify real connectivity, report unknownchecks.push({- name: 'mcp',- status: 'healthy',- latency: 1 + Math.random() * 3,+ name: 'swarm',+ status: 'unknown',+ message: 'Swarm connectivity not monitored β check coordination store manually',});+ // Neural β cannot verify, report unknownchecks.push({name: 'neural',- status: metrics.health >= 0.7 ? 'healthy' : 'degraded',- latency: 10 + Math.random() * 20,+ status: 'unknown',+ message: 'Neural network health not monitored',});if (input.deep) {- checks.push({- name: 'disk',- status: 'healthy',- latency: 50 + Math.random() * 100,- });+ // Disk check β real free space check via os module+ {+ const t0 = performance.now();+ const freeMem = os.freemem();+ const totalMem = os.totalmem();+ const elapsed = performance.now() - t0;+ // Use memory as a proxy; real disk check would need statvfs+ checks.push({+ name: 'disk',+ status: 'unknown',+ latency: Math.round(elapsed * 100) / 100,+ message: 'Disk space check not implemented β use os-level tools',+ });+ }+ // Network β cannot verify without making a requestchecks.push({name: 'network',- status: 'healthy',- latency: 20 + Math.random() * 30,+ status: 'unknown',+ message: 'Network connectivity not monitored',});- checks.push({- name: 'database',- status: 'healthy',- latency: 15 + Math.random() * 25,- });+ // Database β check if coordination store exists+ {+ const t0 = performance.now();+ const coordPath = join(projectCwd, '.claude-flow', 'coordination', 'store.json');+ const dbExists = existsSync(coordPath);+ const elapsed = performance.now() - t0;+ checks.push({+ name: 'database',+ status: dbExists ? 'healthy' : 'unknown',+ latency: Math.round(elapsed * 100) / 100,+ message: dbExists ? undefined : 'Coordination store not found',+ });+ }}const healthy = checks.filter(c => c.status === 'healthy').length;diff --git a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/task-tools.tsindex 14bba51d25..8cd64b70e6 100644--- a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts@@ -243,7 +243,7 @@ export const taskTools: MCPTool[] = [// Sync assigned agents back to idle and increment taskCountif (task.assignedTo.length > 0) {- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents.json');+ const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');try {let agentStore: { agents: Record<string, Record<string, unknown>> } = { agents: {} };if (existsSync(agentStorePath)) {@@ -354,7 +354,7 @@ export const taskTools: MCPTool[] = [const previouslyAssigned = [...task.assignedTo];// Load agent store to sync worker state- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents.json');+ const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');let agentStore: { agents: Record<string, Record<string, unknown>> } = { agents: {} };try {if (existsSync(agentStorePath)) {@@ -399,7 +399,7 @@ export const taskTools: MCPTool[] = [saveTaskStore(store);// Save agent store- const agentDir = join(getProjectCwd(), STORAGE_DIR);+ const agentDir = join(getProjectCwd(), STORAGE_DIR, 'agents');if (!existsSync(agentDir)) {mkdirSync(agentDir, { recursive: true });}diff --git a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.tsindex 5eb5b5a44f..aaeae4acbe 100644--- a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts@@ -271,35 +271,28 @@ export const workflowTools: MCPTool[] = [workflow.startedAt = new Date().toISOString();workflow.currentStep = (input.startFromStep as number) || 0;- // Execute steps (in real implementation, this would be async/event-driven)- const results: Array<{ stepId: string; status: string }> = [];+ // Set steps to pending β actual execution requires agent assignment via task tools+ const results: Array<{ stepId: string; status: string; _note: string }> = [];for (let i = workflow.currentStep; i < workflow.steps.length; i++) {const step = workflow.steps[i];- step.status = 'running';- step.startedAt = new Date().toISOString();+ step.status = 'pending';- // For now, mark as completed (real implementation would execute actual tasks)- step.status = 'completed';- step.completedAt = new Date().toISOString();- step.result = { executed: true, stepType: step.type };-- results.push({ stepId: step.stepId, status: step.status });- workflow.currentStep = i + 1;+ results.push({+ stepId: step.stepId,+ status: step.status,+ _note: 'Workflow execution tracks state. Actual step execution requires agent assignment via task tools.',+ });}- workflow.status = 'completed';- workflow.completedAt = new Date().toISOString();-saveWorkflowStore(store);return {workflowId,status: workflow.status,- stepsExecuted: results.length,+ totalSteps: results.length,results,startedAt: workflow.startedAt,- completedAt: workflow.completedAt,- duration: new Date(workflow.completedAt).getTime() - new Date(workflow.startedAt!).getTime(),+ _note: 'Workflow is now running. Steps are in pending state and must be executed via task tools.',};},},@@ -463,29 +456,23 @@ export const workflowTools: MCPTool[] = [workflow.status = 'running';saveWorkflowStore(store);- // Continue execution from current step- const results: Array<{ stepId: string; status: string }> = [];- for (let i = workflow.currentStep; i < workflow.steps.length; i++) {- const step = workflow.steps[i];- step.status = 'running';- step.startedAt = new Date().toISOString();- step.status = 'completed';- step.completedAt = new Date().toISOString();- step.result = { executed: true };- results.push({ stepId: step.stepId, status: step.status });- workflow.currentStep = i + 1;- }+ // Report current step states β do not auto-complete them+ const stepStates = workflow.steps.map(step => ({+ stepId: step.stepId,+ name: step.name,+ status: step.status,+ }));- workflow.status = 'completed';- workflow.completedAt = new Date().toISOString();- saveWorkflowStore(store);+ const remainingSteps = workflow.steps.length - workflow.currentStep;return {workflowId,status: workflow.status,resumed: true,- stepsExecuted: results.length,- completedAt: workflow.completedAt,+ currentStep: workflow.currentStep,+ remainingSteps,+ steps: stepStates,+ _note: 'Workflow resumed. Steps remain in their current state and must be executed via task tools.',};},},diff --git a/v3/@claude-flow/integration/src/token-optimizer.ts b/v3/@claude-flow/integration/src/token-optimizer.tsindex db4808dc82..fd4455c642 100644--- a/v3/@claude-flow/integration/src/token-optimizer.ts+++ b/v3/@claude-flow/integration/src/token-optimizer.ts@@ -169,8 +169,6 @@ export class TokenOptimizer extends EventEmitter {language,});- this.stats.editsOptimized++;-// Track optimized edits (no fabricated token savings β actual savings// come from fewer retries, which we can't measure here)if (result.method === 'agent-booster') {diff --git a/v3/implementation/adrs/ADR-073-stub-tool-honesty-real-predictions.md b/v3/implementation/adrs/ADR-073-stub-tool-honesty-real-predictions.mdindex 7c984e0a78..aab5e245a9 100644--- a/v3/implementation/adrs/ADR-073-stub-tool-honesty-real-predictions.md+++ b/v3/implementation/adrs/ADR-073-stub-tool-honesty-real-predictions.md@@ -1,3 +1,4 @@+# ADR-073: Stub Tool Honesty & Real Predictions**Status**: Accepted