diff --git a/package-lock.json b/package-lock.json index 4ed0f0c55c..cbab435410 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-flow", - "version": "3.5.71", + "version": "3.5.72", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-flow", - "version": "3.5.71", + "version": "3.5.72", "license": "MIT", "dependencies": { "semver": "^7.6.0", diff --git a/package.json b/package.json index 7e2d89238b..f6b8acec49 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-flow", - "version": "3.5.71", + "version": "3.5.72", "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.json index 0c0906aeab..3101b87b83 100644 --- a/ruflo/package.json +++ b/ruflo/package.json @@ -1,6 +1,6 @@ { "name": "ruflo", - "version": "3.5.71", + "version": "3.5.72", "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/package.json b/v3/@claude-flow/cli/package.json index 8fb0ef825f..7dd471265a 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.71", + "version": "3.5.72", "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/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts index 074685c1c2..2003e97910 100644 --- a/v3/@claude-flow/cli/src/commands/plugins.ts +++ b/v3/@claude-flow/cli/src/commands/plugins.ts @@ -139,11 +139,13 @@ const listCommand: Command = { // Fetch real ratings from Cloud Function (non-blocking) let realRatings: Record = {}; + let ratingsSource: 'live' | 'cached' | 'unavailable' = 'live'; try { const pluginIds = plugins.map(p => p.name); realRatings = await getBulkRatings(pluginIds, 'plugin'); } catch { // Fall back to static ratings if Cloud Function unavailable + ratingsSource = 'unavailable'; } if (ctx.flags.format === 'json') { @@ -152,6 +154,7 @@ const listCommand: Command = { ...p, rating: realRatings[p.name]?.average || p.rating, ratingCount: realRatings[p.name]?.count || 0, + ...(ratingsSource === 'unavailable' ? { ratingsSource: 'cached' as const } : {}), })); output.printJson(pluginsWithRatings); return { success: true, data: pluginsWithRatings }; @@ -185,6 +188,9 @@ const listCommand: Command = { }); output.writeln(); + if (ratingsSource === 'unavailable') { + output.writeln(output.dim('(ratings: cached — cloud unavailable)')); + } output.writeln(output.dim(`Source: ${result.source}${result.fromCache ? ' (cached)' : ''}`)); if (result.cid) { output.writeln(output.dim(`Registry CID: ${result.cid.slice(0, 30)}...`)); diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.ts index cf9fabc9f1..45e0bd449c 100644 --- a/v3/@claude-flow/cli/src/commands/security.ts +++ b/v3/@claude-flow/cli/src/commands/security.ts @@ -298,34 +298,235 @@ const threatsCommand: Command = { ], action: async (ctx: CommandContext): Promise => { const model = ctx.flags.model as string || 'stride'; + const scope = ctx.flags.scope as string || '.'; + const exportFormat = ctx.flags.export as string | undefined; output.writeln(); output.writeln(output.bold(`Threat Model: ${model.toUpperCase()}`)); output.writeln(output.dim('─'.repeat(50))); - output.writeln(output.warning('⚠ Automated threat modeling is not yet implemented.')); - output.writeln(output.dim('The table below is a STRIDE reference template, not an analysis of your code.')); - output.writeln(); + const spinner = output.createSpinner({ text: `Scanning ${scope} for threat indicators...`, spinner: 'dots' }); + spinner.start(); + const fs = await import('fs'); + const path = await import('path'); + + const rootDir = path.resolve(scope); + const findings: Array<{ category: string; severity: string; location: string; description: string }> = []; + const extensions = new Set(['.ts', '.js', '.json', '.yaml', '.yml', '.tsx', '.jsx']); + const skipDirs = new Set(['node_modules', 'dist', '.git']); + let filesScanned = 0; + const MAX_FILES = 500; + + // Threat indicator patterns mapped to STRIDE categories + const threatPatterns: Array<{ pattern: RegExp; category: string; severity: string; description: string }> = [ + // Spoofing — weak/missing authentication + { pattern: /(?:app|router|server)\s*\.\s*(?:get|post|put|patch|delete)\s*\(\s*['"][^'"]+['"]\s*,\s*(?:async\s+)?\(?(?:req|request)/g, category: 'Spoofing', severity: 'medium', description: 'HTTP endpoint without auth middleware' }, + + // Tampering — code injection vectors + { pattern: /\beval\s*\(/g, category: 'Tampering', severity: 'high', description: 'eval() usage — arbitrary code execution risk' }, + { pattern: /\bexecSync\s*\(/g, category: 'Tampering', severity: 'high', description: 'execSync() usage — command injection risk' }, + { pattern: /\bexec\s*\(\s*[^)]*\$\{/g, category: 'Tampering', severity: 'high', description: 'exec() with template literal — injection risk' }, + { pattern: /child_process.*\bexec\b/g, category: 'Tampering', severity: 'medium', description: 'child_process exec import — review for injection' }, + { pattern: /new\s+Function\s*\(/g, category: 'Tampering', severity: 'high', description: 'new Function() — dynamic code execution risk' }, + + // Repudiation — missing audit/logging + // (checked via absence of logging imports, handled separately) + + // Info Disclosure — secrets and data leaks + { pattern: /(?:api[_-]?key|secret|token|password|passwd|credential)\s*[:=]\s*['"][^'"]{8,}['"]/gi, category: 'Info Disclosure', severity: 'high', description: 'Hardcoded credential or secret' }, + { pattern: /AKIA[0-9A-Z]{16}/g, category: 'Info Disclosure', severity: 'critical', description: 'AWS Access Key ID detected' }, + { pattern: /gh[ps]_[A-Za-z0-9_]{36,}/g, category: 'Info Disclosure', severity: 'high', description: 'GitHub token detected' }, + { pattern: /-----BEGIN (?:RSA|EC|DSA|OPENSSH) PRIVATE KEY-----/g, category: 'Info Disclosure', severity: 'critical', description: 'Private key detected' }, + { pattern: /http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0)/g, category: 'Info Disclosure', severity: 'medium', description: 'Non-localhost HTTP URL — should use HTTPS' }, + + // DoS — missing rate limiting / resource protection + { pattern: /require\s*\(\s*['"]express['"]\s*\)/g, category: 'DoS', severity: 'low', description: 'Express detected — verify rate-limiting is configured' }, + { pattern: /require\s*\(\s*['"]fastify['"]\s*\)/g, category: 'DoS', severity: 'low', description: 'Fastify detected — verify rate-limiting is configured' }, + + // Elevation of privilege — unsafe deserialization, prototype pollution + { pattern: /JSON\.parse\s*\(\s*(?:req\.|request\.)/g, category: 'Elevation', severity: 'medium', description: 'Unsanitized JSON.parse from request — validate input' }, + { pattern: /\.__proto__/g, category: 'Elevation', severity: 'high', description: '__proto__ access — prototype pollution risk' }, + { pattern: /Object\.assign\s*\(\s*\{\s*\}\s*,\s*(?:req|request)\./g, category: 'Elevation', severity: 'medium', description: 'Object.assign from request — prototype pollution risk' }, + ]; + + // Check for .env files committed to git + const checkEnvInGit = () => { + try { + const { execSync } = require('child_process'); + const tracked = execSync('git ls-files --cached', { cwd: rootDir, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }); + const envFiles = tracked.split('\n').filter((f: string) => /(?:^|\/)\.env(?:\.|$)/.test(f)); + for (const envFile of envFiles) { + findings.push({ + category: 'Info Disclosure', + severity: output.error('CRITICAL'), + location: envFile, + description: '.env file tracked in git — secrets may be exposed', + }); + } + } catch { /* not a git repo or git not available */ } + }; + + // Recursive file scanner + const scanDir = (dir: string) => { + if (filesScanned >= MAX_FILES) return; + let entries: import('fs').Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { return; } + + for (const entry of entries) { + if (filesScanned >= MAX_FILES) break; + if (skipDirs.has(entry.name) || entry.name.startsWith('.')) continue; + + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + scanDir(fullPath); + } else if (entry.isFile() && extensions.has(path.extname(entry.name)) && !entry.name.endsWith('.d.ts')) { + filesScanned++; + try { + const stat = fs.statSync(fullPath); + if (stat.size > 1024 * 1024) continue; // skip files > 1MB + const content = fs.readFileSync(fullPath, 'utf-8'); + const lines = content.split('\n'); + const relPath = path.relative(rootDir, fullPath); + + for (let i = 0; i < lines.length; i++) { + for (const tp of threatPatterns) { + tp.pattern.lastIndex = 0; + if (tp.pattern.test(lines[i])) { + const sevLabel = tp.severity === 'critical' ? output.error('CRITICAL') : + tp.severity === 'high' ? output.warning('HIGH') : + tp.severity === 'medium' ? output.warning('MEDIUM') : output.info('LOW'); + findings.push({ + category: tp.category, + severity: sevLabel, + location: `${relPath}:${i + 1}`, + description: tp.description, + }); + tp.pattern.lastIndex = 0; + } + } + } + } catch { /* file read error */ } + } + } + }; + + // Check for missing security middleware in Express/Fastify apps + const checkMissingMiddleware = () => { + const serverFiles: string[] = []; + const collectServerFiles = (dir: string, depth: number) => { + if (depth <= 0 || filesScanned >= MAX_FILES) return; + try { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + if (skipDirs.has(entry.name) || entry.name.startsWith('.')) continue; + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + collectServerFiles(fullPath, depth - 1); + } else if (/\.(ts|js)$/.test(entry.name) && !entry.name.endsWith('.d.ts')) { + try { + const content = fs.readFileSync(fullPath, 'utf-8'); + if (/require\s*\(\s*['"](?:express|fastify)['"]\s*\)/.test(content) || /from\s+['"](?:express|fastify)['"]/.test(content)) { + serverFiles.push(fullPath); + const relPath = path.relative(rootDir, fullPath); + if (!/(?:helmet|lusca)/.test(content)) { + findings.push({ category: 'Tampering', severity: output.warning('MEDIUM'), location: relPath, description: 'No helmet/lusca security headers middleware' }); + } + if (!/(?:cors)/.test(content)) { + findings.push({ category: 'Spoofing', severity: output.info('LOW'), location: relPath, description: 'No CORS middleware detected' }); + } + if (!/(?:rate.?limit|throttle)/.test(content)) { + findings.push({ category: 'DoS', severity: output.warning('MEDIUM'), location: relPath, description: 'No rate-limiting middleware detected' }); + } + } + } catch { /* skip */ } + } + } + } catch { /* skip */ } + }; + collectServerFiles(rootDir, 5); + }; + + checkEnvInGit(); + scanDir(rootDir); + checkMissingMiddleware(); + + spinner.succeed(`Scanned ${filesScanned} files`); + + // STRIDE reference framework + const strideRef = [ + { category: 'Spoofing', description: 'Can an attacker impersonate a user or service?', example: 'Strong authentication, mTLS' }, + { category: 'Tampering', description: 'Can data or code be modified without detection?', example: 'Input validation, integrity checks' }, + { category: 'Repudiation', description: 'Can actions be performed without accountability?', example: 'Audit logging, signed commits' }, + { category: 'Info Disclosure', description: 'Can sensitive data leak to unauthorized parties?', example: 'Encryption at rest and in transit' }, + { category: 'DoS', description: 'Can service availability be degraded?', example: 'Rate limiting, resource quotas' }, + { category: 'Elevation', description: 'Can privileges be escalated beyond granted level?', example: 'RBAC, principle of least privilege' }, + ]; + + // Display real findings + output.writeln(); + if (findings.length > 0) { + output.writeln(output.bold(`Findings (${findings.length}):`)); + output.writeln(); + output.printTable({ + columns: [ + { key: 'category', header: 'STRIDE Category', width: 18 }, + { key: 'severity', header: 'Severity', width: 12 }, + { key: 'location', header: 'Location', width: 30 }, + { key: 'description', header: 'Description', width: 40 }, + ], + data: findings.slice(0, 30), + }); + if (findings.length > 30) { + output.writeln(output.dim(`... and ${findings.length - 30} more findings`)); + } + + // Summary by STRIDE category + const byCat: Record = {}; + for (const f of findings) byCat[f.category] = (byCat[f.category] || 0) + 1; + output.writeln(); + output.writeln(output.bold('Summary by STRIDE category:')); + for (const [cat, count] of Object.entries(byCat).sort((a, b) => b[1] - a[1])) { + output.writeln(` ${cat}: ${count} finding${count === 1 ? '' : 's'}`); + } + } else { + output.writeln(output.success('No threat indicators detected in scanned files.')); + } + + // Always show STRIDE reference + output.writeln(); + output.writeln(output.bold(`${model.toUpperCase()} Reference Framework${findings.length === 0 ? ' (reference only — no issues detected)' : ''}:`)); + output.writeln(); output.printTable({ columns: [ { key: 'category', header: `${model.toUpperCase()} Category`, width: 20 }, { key: 'description', header: 'What to Assess', width: 40 }, { key: 'example', header: 'Example Mitigation', width: 30 }, ], - data: [ - { category: 'Spoofing', description: 'Can an attacker impersonate a user or service?', example: 'Strong authentication, mTLS' }, - { category: 'Tampering', description: 'Can data or code be modified without detection?', example: 'Input validation, integrity checks' }, - { category: 'Repudiation', description: 'Can actions be performed without accountability?', example: 'Audit logging, signed commits' }, - { category: 'Info Disclosure', description: 'Can sensitive data leak to unauthorized parties?', example: 'Encryption at rest and in transit' }, - { category: 'DoS', description: 'Can service availability be degraded?', example: 'Rate limiting, resource quotas' }, - { category: 'Elevation', description: 'Can privileges be escalated beyond granted level?', example: 'RBAC, principle of least privilege' }, - ], + data: strideRef, }); + // Export if requested + if (exportFormat && findings.length > 0) { + const exportData = { + model: model.toUpperCase(), + timestamp: new Date().toISOString(), + scope, + filesScanned, + totalFindings: findings.length, + findings: findings.map(f => ({ ...f, severity: f.severity.replace(/\x1b\[[0-9;]*m/g, '') })), + strideReference: strideRef, + }; + if (exportFormat === 'json') { + output.writeln(); + output.writeln(JSON.stringify(exportData, null, 2)); + } + } + output.writeln(); - output.writeln(output.dim('For real threat modeling, review your architecture manually using this framework.')); - output.writeln(output.dim('Run "claude-flow security scan" for automated vulnerability detection.')); + output.writeln(output.dim(`Files scanned: ${filesScanned} (max ${MAX_FILES})`)); return { success: true }; }, @@ -418,37 +619,157 @@ const secretsCommand: Command = { { command: 'claude-flow security secrets -a rotate', description: 'Rotate compromised secrets' }, ], action: async (ctx: CommandContext): Promise => { - const path = ctx.flags.path as string || '.'; + const scanPath = ctx.flags.path as string || '.'; + const ignorePatterns = ctx.flags.ignore as string | undefined; output.writeln(); output.writeln(output.bold('Secret Detection')); output.writeln(output.dim('─'.repeat(50))); - const spinner = output.createSpinner({ text: 'Scanning for secrets...', spinner: 'dots' }); + const spinner = output.createSpinner({ text: `Scanning ${scanPath} for secrets...`, spinner: 'dots' }); spinner.start(); - await new Promise(r => setTimeout(r, 800)); - spinner.succeed('Scan complete'); + + const fs = await import('fs'); + const path = await import('path'); + + const rootDir = path.resolve(scanPath); + const skipDirs = new Set(['node_modules', 'dist', '.git']); + const extensions = new Set(['.ts', '.js', '.json', '.yaml', '.yml', '.tsx', '.jsx', '.env', '.toml', '.cfg', '.conf', '.ini', '.properties', '.sh', '.bash', '.zsh']); + const ignoreList = ignorePatterns ? ignorePatterns.split(',').map(p => p.trim()) : []; + + const secretPatterns: Array<{ pattern: RegExp; type: string; risk: string; action: string }> = [ + { pattern: /AKIA[0-9A-Z]{16}/g, type: 'AWS Access Key', risk: 'Critical', action: 'Rotate immediately' }, + { pattern: /gh[ps]_[A-Za-z0-9_]{36,}/g, type: 'GitHub Token', risk: 'Critical', action: 'Revoke and rotate' }, + { pattern: /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, type: 'JWT Token', risk: 'High', action: 'Remove from source' }, + { pattern: /-----BEGIN (?:RSA|EC|DSA|OPENSSH) PRIVATE KEY-----/g, type: 'Private Key', risk: 'Critical', action: 'Remove and regenerate' }, + { pattern: /(?:mongodb|postgres|mysql|redis):\/\/[^\s'"]+/g, type: 'Connection String', risk: 'High', action: 'Use env variable' }, + { pattern: /['"](?:sk-|sk_live_|sk_test_)[a-zA-Z0-9]{20,}['"]/g, type: 'API Key (Stripe/OpenAI)', risk: 'Critical', action: 'Rotate immediately' }, + { pattern: /['"]xox[baprs]-[a-zA-Z0-9-]+['"]/g, type: 'Slack Token', risk: 'High', action: 'Revoke and rotate' }, + { pattern: /[a-zA-Z0-9_-]*(?:api[_-]?key|secret[_-]?key|auth[_-]?token|access[_-]?token|private[_-]?key)\s*[:=]\s*['"][^'"]{8,}['"]/gi, type: 'Generic Secret/API Key', risk: 'High', action: 'Use env variable' }, + { pattern: /(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi, type: 'Hardcoded Password', risk: 'High', action: 'Use secrets manager' }, + ]; + + const findings: Array<{ type: string; location: string; risk: string; action: string; line: string }> = []; + let filesScanned = 0; + const MAX_FILES = 500; + + const shouldIgnore = (filePath: string): boolean => { + return ignoreList.some(p => filePath.includes(p)); + }; + + const scanDir = (dir: string) => { + if (filesScanned >= MAX_FILES) return; + let entries: import('fs').Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { return; } + + for (const entry of entries) { + if (filesScanned >= MAX_FILES) break; + if (skipDirs.has(entry.name)) continue; + // Allow dotfiles like .env but skip .git + const fullPath = path.join(dir, entry.name); + + if (entry.isDirectory()) { + if (entry.name.startsWith('.') && entry.name !== '.env') continue; + scanDir(fullPath); + } else if (entry.isFile()) { + const ext = path.extname(entry.name); + const isEnvFile = entry.name.startsWith('.env'); + if (!extensions.has(ext) && !isEnvFile) continue; + if (entry.name.endsWith('.d.ts')) continue; + + const relPath = path.relative(rootDir, fullPath); + if (shouldIgnore(relPath)) continue; + + filesScanned++; + try { + const stat = fs.statSync(fullPath); + if (stat.size > 1024 * 1024) continue; // skip files > 1MB + + const content = fs.readFileSync(fullPath, 'utf-8'); + // Quick binary check — skip if null bytes present + if (content.includes('\0')) continue; + + const lines = content.split('\n'); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + for (const sp of secretPatterns) { + sp.pattern.lastIndex = 0; + const match = sp.pattern.exec(line); + if (match) { + // Mask the matched secret for safe display + const matched = match[0]; + const masked = matched.length > 12 + ? matched.substring(0, 6) + '***' + matched.substring(matched.length - 3) + : '***'; + + findings.push({ + type: sp.type, + location: `${relPath}:${i + 1}`, + risk: sp.risk, + action: sp.action, + line: masked, + }); + sp.pattern.lastIndex = 0; + } + } + } + } catch { /* file read error */ } + } + } + }; + + scanDir(rootDir); + spinner.succeed(`Scanned ${filesScanned} files`); output.writeln(); - output.writeln(output.warning('⚠ No real secrets scan performed. Showing example findings.')); - output.writeln(output.dim('Run "claude-flow security scan --depth full" for real secret detection.')); - output.writeln(); - output.printTable({ - columns: [ - { key: 'type', header: 'Secret Type (Example)', width: 25 }, - { key: 'location', header: 'Location', width: 30 }, - { key: 'risk', header: 'Risk', width: 12 }, - { key: 'action', header: 'Recommended', width: 20 }, - ], - data: [ - { type: 'AWS Access Key', location: 'example/config.ts:15', risk: output.error('Critical'), action: 'Rotate immediately' }, - { type: 'GitHub Token', location: 'example/.env:8', risk: output.warning('High'), action: 'Remove from repo' }, - { type: 'JWT Secret', location: 'example/auth.ts:42', risk: output.warning('High'), action: 'Use env variable' }, - { type: 'DB Password', location: 'example/compose.yml:23', risk: output.warning('Medium'), action: 'Use secrets mgmt' }, - ], - }); + if (findings.length > 0) { + const criticalCount = findings.filter(f => f.risk === 'Critical').length; + const highCount = findings.filter(f => f.risk === 'High').length; + const mediumCount = findings.filter(f => f.risk === 'Medium').length; - return { success: true }; + output.printTable({ + columns: [ + { key: 'type', header: 'Secret Type', width: 25 }, + { key: 'location', header: 'Location', width: 35 }, + { key: 'risk', header: 'Risk', width: 12 }, + { key: 'action', header: 'Recommended', width: 22 }, + ], + data: findings.slice(0, 25).map(f => ({ + type: f.type, + location: f.location, + risk: f.risk === 'Critical' ? output.error(f.risk) : + f.risk === 'High' ? output.warning(f.risk) : + output.warning(f.risk), + action: f.action, + })), + }); + + if (findings.length > 25) { + output.writeln(output.dim(`... and ${findings.length - 25} more secrets found`)); + } + + output.writeln(); + output.printBox([ + `Path: ${scanPath}`, + `Files scanned: ${filesScanned}`, + ``, + `Critical: ${criticalCount} High: ${highCount} Medium: ${mediumCount}`, + `Total secrets found: ${findings.length}`, + ].join('\n'), 'Secrets Summary'); + } else { + output.writeln(output.success('No secrets detected.')); + output.writeln(); + output.printBox([ + `Path: ${scanPath}`, + `Files scanned: ${filesScanned}`, + ``, + `No hardcoded secrets, API keys, tokens, or credentials found.`, + ].join('\n'), 'Secrets Summary'); + } + + return { success: findings.length === 0 }; }, }; diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.ts index 1eb8a2d773..fc53a0a372 100644 --- a/v3/@claude-flow/cli/src/commands/swarm.ts +++ b/v3/@claude-flow/cli/src/commands/swarm.ts @@ -145,16 +145,80 @@ function getSwarmStatus(swarmId?: string) { pending: pendingTasks }, metrics: { - tokensUsed: 0, - avgResponseTime: '--', - successRate: totalTasks > 0 ? `${Math.round((completedTasks / totalTasks) * 100)}%` : '--', - elapsedTime: '--' - }, - coordination: { - consensusRounds: 0, - messagesSent: 0, - conflictsResolved: 0 + tokensUsed: (swarmState as Record)?.tokensUsed as number | null ?? null, + avgResponseTime: (() => { + // Calculate average response time from task files with startedAt/completedAt + const taskTimesMs: number[] = []; + if (fs.existsSync(tasksDir)) { + try { + const taskFiles = fs.readdirSync(tasksDir).filter(f => f.endsWith('.json')); + for (const file of taskFiles) { + try { + const task = JSON.parse(fs.readFileSync(path.join(tasksDir, file), 'utf-8')); + if (task.startedAt && task.completedAt) { + const elapsed = new Date(task.completedAt).getTime() - new Date(task.startedAt).getTime(); + if (elapsed > 0) taskTimesMs.push(elapsed); + } + } catch { /* skip malformed task files */ } + } + } catch { /* skip if dir unreadable */ } + } + if (taskTimesMs.length === 0) return null; + const avgMs = Math.round(taskTimesMs.reduce((a, b) => a + b, 0) / taskTimesMs.length); + return avgMs < 1000 ? `${avgMs}ms` : `${(avgMs / 1000).toFixed(1)}s`; + })(), + successRate: totalTasks > 0 ? `${Math.round((completedTasks / totalTasks) * 100)}%` : null, + elapsedTime: (() => { + // Calculate from swarm startedAt in state.json + const startedAt = (swarmState as Record)?.startedAt as string | undefined + || (swarmState as Record)?.initializedAt as string | undefined; + if (!startedAt) return null; + const elapsedMs = Date.now() - new Date(startedAt).getTime(); + if (elapsedMs < 0) return null; + const secs = Math.floor(elapsedMs / 1000); + if (secs < 60) return `${secs}s`; + const mins = Math.floor(secs / 60); + const remSecs = secs % 60; + if (mins < 60) return `${mins}m ${remSecs}s`; + const hrs = Math.floor(mins / 60); + const remMins = mins % 60; + return `${hrs}h ${remMins}m`; + })() }, + coordination: (() => { + // Read real coordination counts from .swarm/coordination/ directory + const coordDir = path.join(swarmDir, 'coordination'); + let consensusRounds = 0; + let messagesSent = 0; + let conflictsResolved = 0; + if (fs.existsSync(coordDir)) { + try { + const coordFiles = fs.readdirSync(coordDir).filter(f => f.endsWith('.json')); + for (const file of coordFiles) { + try { + const entry = JSON.parse(fs.readFileSync(path.join(coordDir, file), 'utf-8')); + if (entry.type === 'consensus') consensusRounds++; + else if (entry.type === 'message') messagesSent++; + else if (entry.type === 'conflict' || entry.type === 'conflict-resolution') conflictsResolved++; + // Also aggregate pre-counted fields if present + if (typeof entry.consensusRounds === 'number') consensusRounds += entry.consensusRounds; + if (typeof entry.messagesSent === 'number') messagesSent += entry.messagesSent; + if (typeof entry.conflictsResolved === 'number') conflictsResolved += entry.conflictsResolved; + } catch { /* skip malformed coordination files */ } + } + } catch { /* skip if dir unreadable */ } + } + // Also check state.json for aggregate coordination stats + if (swarmState) { + const coord = (swarmState as Record).coordination as Record | undefined; + if (coord) { + if (typeof coord.consensusRounds === 'number') consensusRounds += coord.consensusRounds; + if (typeof coord.messagesSent === 'number') messagesSent += coord.messagesSent; + if (typeof coord.conflictsResolved === 'number') conflictsResolved += coord.conflictsResolved; + } + } + return { consensusRounds, messagesSent, conflictsResolved }; + })(), hasActiveSwarm: !!swarmState || totalAgents > 0 }; } @@ -472,8 +536,10 @@ const startCommand: Command = { output.writeln(); output.printSuccess(`Swarm ${swarmId} initialized with ${totalAgents} agent slots`); - output.writeln(output.dim(' Note: Agents are registered but actual task execution requires')); - output.writeln(output.dim(' Claude Code Task tool or hive-mind spawn --claude to drive work.')); + output.writeln(output.dim(' This CLI coordinates agent state. Execution happens via:')); + output.writeln(output.dim(' - Claude Code Agent tool (interactive)')); + output.writeln(output.dim(' - claude -p (headless background)')); + output.writeln(output.dim(' - hive-mind spawn --claude (autonomous)')); output.writeln(output.dim(` Monitor: claude-flow swarm status ${swarmId}`)); return { success: true, data: executionState }; @@ -552,10 +618,10 @@ const statusCommand: Command = { // Metrics output.writeln(output.bold('Performance Metrics')); output.printList([ - `Tokens Used: ${status.metrics.tokensUsed.toLocaleString()}`, - `Avg Response Time: ${status.metrics.avgResponseTime}`, - `Success Rate: ${status.metrics.successRate}`, - `Elapsed Time: ${status.metrics.elapsedTime}` + `Tokens Used: ${status.metrics.tokensUsed != null ? status.metrics.tokensUsed.toLocaleString() : output.dim('unknown')}`, + `Avg Response Time: ${status.metrics.avgResponseTime ?? output.dim('no data')}`, + `Success Rate: ${status.metrics.successRate ?? output.dim('no data')}`, + `Elapsed Time: ${status.metrics.elapsedTime ?? output.dim('no data')}` ]); output.writeln(); diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts index ef5e98bf69..d00b56fafd 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts @@ -2942,20 +2942,62 @@ export const hooksIntelligenceAttention: MCPTool = { { const v = validateText(query, 'query'); if (!v.valid) return { success: false, error: v.error }; } let implementation = 'placeholder'; + let embeddingSource: 'onnx' | 'hash-fallback' | 'none' = 'none'; const results: Array<{ index: number; weight: number; pattern: string; expert?: string }> = []; + // Helper: generate query embedding, preferring real ONNX embeddings over hash fallback + async function getQueryEmbedding(text: string, dims: number): Promise<{ embedding: Float32Array; source: 'onnx' | 'hash-fallback' }> { + // Try ONNX via @claude-flow/embeddings + try { + const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null); + if (embeddingsModule?.createEmbeddingService) { + const service = embeddingsModule.createEmbeddingService({ provider: 'onnx' }); + const result = await service.embed(text); + const arr = new Float32Array(dims); + for (let i = 0; i < Math.min(dims, result.embedding.length); i++) { + arr[i] = result.embedding[i]; + } + return { embedding: arr, source: 'onnx' }; + } + } catch { + // ONNX not available, try agentic-flow + } + + // Try agentic-flow embeddings + try { + const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null); + if (embeddingsModule?.createEmbeddingService) { + const service = embeddingsModule.createEmbeddingService({ provider: 'agentic-flow' }); + const result = await service.embed(text); + const arr = new Float32Array(dims); + for (let i = 0; i < Math.min(dims, result.embedding.length); i++) { + arr[i] = result.embedding[i]; + } + return { embedding: arr, source: 'onnx' }; + } + } catch { + // agentic-flow not available + } + + // Hash-based fallback (deterministic but not semantic) + const arr = new Float32Array(dims); + let seed = text.split('').reduce((acc, char, i) => acc + char.charCodeAt(0) * (i + 1), 0); + for (let i = 0; i < dims; i++) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + arr[i] = (seed / 0x7fffffff) * 2 - 1; + } + return { embedding: arr, source: 'hash-fallback' }; + } + if (mode === 'moe') { // Try MoE routing const moe = await getMoERouter(); if (moe) { try { - // Generate a simple embedding from query (hash-based for demo) - const embedding = new Float32Array(384); - for (let i = 0; i < 384; i++) { - embedding[i] = Math.sin(query.charCodeAt(i % query.length) * (i + 1) * 0.01); - } + const embResult = await getQueryEmbedding(query, 384); + embeddingSource = embResult.source; - const routingResult = moe.route(embedding); + const routingResult = moe.route(embResult.embedding); for (let i = 0; i < Math.min(topK, routingResult.experts.length); i++) { const expert = routingResult.experts[i]; results.push({ @@ -2975,15 +3017,12 @@ export const hooksIntelligenceAttention: MCPTool = { const flash = await getFlashAttention(); if (flash) { try { - // Generate query/key/value embeddings - const q = new Float32Array(384); + const embResult = await getQueryEmbedding(query, 384); + embeddingSource = embResult.source; + const q = embResult.embedding; const keys: Float32Array[] = []; const values: Float32Array[] = []; - for (let i = 0; i < 384; i++) { - q[i] = Math.sin(query.charCodeAt(i % query.length) * (i + 1) * 0.01); - } - // Generate some keys/values for (let k = 0; k < topK; k++) { const key = new Float32Array(384); @@ -3029,10 +3068,13 @@ export const hooksIntelligenceAttention: MCPTool = { results, stats: { computeTimeMs, - speedup: implementation.startsWith('real-') ? (mode === 'flash' ? '2.49x-7.47x' : '1.5x-3x') : null, - memoryReduction: implementation.startsWith('real-') ? (mode === 'flash' ? '50-75%' : '25-40%') : null, + implementation, + _embeddingSource: embeddingSource, _stub: implementation === 'none', _note: implementation === 'none' ? 'No attention backend available. Install @ruvector/attention for real computation.' : undefined, + ...(embeddingSource === 'hash-fallback' && implementation !== 'none' + ? { _embeddingNote: 'Query embeddings are hash-based (not semantic). Install @claude-flow/embeddings for real ONNX embeddings.' } + : {}), }, implementation, }; diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts index d86005778b..6ea207de70 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts @@ -28,7 +28,7 @@ try { embeddingServiceName = 'agentic-flow/reasoningbank'; } - // Tier 2: @claude-flow/embeddings + // Tier 2: @claude-flow/embeddings with agentic-flow provider if (!realEmbeddings) { const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null); if (embeddingsModule?.createEmbeddingService) { @@ -42,6 +42,35 @@ try { }; embeddingServiceName = 'agentic-flow'; } catch { + // agentic-flow provider not available, try ONNX + } + } + } + + // Tier 3: @claude-flow/embeddings with ONNX provider + if (!realEmbeddings) { + const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null); + if (embeddingsModule?.createEmbeddingService) { + try { + const service = embeddingsModule.createEmbeddingService({ provider: 'onnx' }); + realEmbeddings = { + embed: async (text: string) => { + const result = await service.embed(text); + return Array.from(result.embedding); + }, + }; + embeddingServiceName = 'onnx'; + } catch { + // ONNX provider not available, fall through to mock + } + } + } + + // Tier 4: mock fallback (last resort — embeddings are not semantic) + if (!realEmbeddings) { + const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null); + if (embeddingsModule?.createEmbeddingService) { + try { const service = embeddingsModule.createEmbeddingService({ provider: 'mock' }); realEmbeddings = { embed: async (text: string) => { @@ -49,7 +78,9 @@ try { return Array.from(result.embedding); }, }; - embeddingServiceName = 'mock'; + embeddingServiceName = 'mock-fallback'; + } catch { + // No embedding service available at all } } } @@ -247,6 +278,7 @@ export const neuralTools: MCPTool[] = [ return { success: true, _realEmbedding: !!realEmbeddings, + embeddingProvider: embeddingServiceName, modelId, type: modelType, status: model.status, @@ -313,6 +345,7 @@ export const neuralTools: MCPTool[] = [ return { success: true, _realEmbedding: !!realEmbeddings, + embeddingProvider: embeddingServiceName, _hasStoredPatterns: storedPatterns.length > 0, modelId: model?.id || 'default', input: inputText, @@ -395,6 +428,7 @@ export const neuralTools: MCPTool[] = [ return { success: true, _realEmbedding: !!realEmbeddings, + embeddingProvider: embeddingServiceName, patternId, name: pattern.name, type: pattern.type, @@ -421,6 +455,7 @@ export const neuralTools: MCPTool[] = [ return { _realSimilarity: true, _realEmbedding: !!realEmbeddings, + embeddingProvider: embeddingServiceName, query, results: results.map(r => ({ id: r.id, @@ -492,6 +527,7 @@ export const neuralTools: MCPTool[] = [ saveNeuralStore(store); return { success: true, _real: true, method, + embeddingProvider: embeddingServiceName, patternsCompressed: totalCompressed, compressionRatio: '3.92x (Int8)', beforeBytes: beforeSize, @@ -513,6 +549,7 @@ export const neuralTools: MCPTool[] = [ saveNeuralStore(store); return { success: true, _real: true, method, + embeddingProvider: embeddingServiceName, threshold, patternsRemoved: toRemove.length, patternsBefore: beforeCount, @@ -545,6 +582,7 @@ export const neuralTools: MCPTool[] = [ saveNeuralStore(store); return { success: true, _real: true, method, + embeddingProvider: embeddingServiceName, patternsMerged: merged.length, patternsBefore: beforeCount, patternsAfter: Object.keys(store.patterns).length, @@ -703,6 +741,7 @@ export const neuralTools: MCPTool[] = [ return { success: true, _real: true, target, + embeddingProvider: embeddingServiceName, actions, patternsBefore: beforeCount, patternsAfter: Object.keys(store.patterns).length, diff --git a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts index 205fef81c2..14464fdd1c 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts @@ -279,15 +279,15 @@ export const performanceTools: MCPTool[] = [ const iterations = (input.iterations as number) || 100; const warmup = input.warmup !== false; - // REAL benchmark functions + // Synthetic data benchmarks — measures actual CPU/memory throughput const benchmarkFunctions: Record void> = { memory: () => { - // Real memory allocation benchmark + // Synthetic data benchmark — measures actual allocation + sort throughput const arr = new Array(1000).fill(0).map(() => Math.random()); arr.sort(); }, neural: () => { - // Real computation benchmark (matrix-like operations) + // Synthetic data benchmark — measures actual matrix multiplication throughput const size = 64; const a = Array.from({ length: size }, () => Array.from({ length: size }, () => Math.random())); const b = Array.from({ length: size }, () => Array.from({ length: size }, () => Math.random())); @@ -300,20 +300,20 @@ export const performanceTools: MCPTool[] = [ } }, swarm: () => { - // Real object creation and manipulation + // Synthetic data benchmark — measures actual object creation + manipulation throughput const agents = Array.from({ length: 10 }, (_, i) => ({ id: i, status: 'active', tasks: [] as number[] })); agents.forEach(a => { for (let i = 0; i < 100; i++) a.tasks.push(i); }); agents.sort((a, b) => a.tasks.length - b.tasks.length); }, io: () => { - // Real JSON serialization benchmark + // Synthetic data benchmark — measures actual JSON serialization throughput const data = { agents: Array.from({ length: 50 }, (_, i) => ({ id: i, name: `agent-${i}` })) }; const json = JSON.stringify(data); JSON.parse(json); }, }; - const results: Array<{ name: string; opsPerSec: number; avgLatency: string; memoryUsage: string; _real: boolean }> = []; + const results: Array<{ name: string; opsPerSec: number; avgLatency: string; memoryUsage: string; _real: boolean; _dataSource: 'synthetic' }> = []; const suitesToRun = suite === 'all' ? Object.keys(benchmarkFunctions) : [suite]; // Warmup phase @@ -363,6 +363,7 @@ export const performanceTools: MCPTool[] = [ avgLatency: `${avgLatencyMs.toFixed(3)}ms`, memoryUsage: `${Math.abs(memoryDelta)}KB`, _real: true, + _dataSource: 'synthetic' as const, }); } } @@ -384,6 +385,7 @@ export const performanceTools: MCPTool[] = [ return { _real: true, + _note: 'Benchmarks use synthetic workloads to measure throughput. Results reflect actual CPU/memory performance.', suite, iterations, warmup, diff --git a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts index 1f74160dee..b556c5e038 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts @@ -11,10 +11,11 @@ import { type MCPTool, getProjectCwd } from './types.js'; import { validateIdentifier } from './validate-input.js'; -import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync, mkdirSync, statfsSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import * as os from 'node:os'; +import * as dns from 'node:dns'; // Read version dynamically from package.json function getPackageVersion(): string { @@ -359,27 +360,59 @@ export const systemTools: MCPTool[] = [ }); if (input.deep) { - // Disk check — real free space check via os module + // Disk check — real free space via statfsSync (Node 18.15+) { 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', - }); + try { + const stats = statfsSync(projectCwd); + const totalBytes = stats.blocks * stats.bsize; + const freeBytes = stats.bfree * stats.bsize; + const totalGB = Math.round((totalBytes / (1024 ** 3)) * 10) / 10; + const freeGB = Math.round((freeBytes / (1024 ** 3)) * 10) / 10; + const freePercent = Math.round((freeBytes / totalBytes) * 100); + const elapsed = performance.now() - t0; + checks.push({ + name: 'disk', + status: freePercent > 10 ? 'healthy' : 'warning', + latency: Math.round(elapsed * 100) / 100, + message: `${freeGB}GB free of ${totalGB}GB (${freePercent}%)`, + }); + } catch { + const elapsed = performance.now() - t0; + checks.push({ + name: 'disk', + status: 'unknown', + latency: Math.round(elapsed * 100) / 100, + message: 'Disk space check failed — statfsSync unavailable', + }); + } } - // Network — cannot verify without making a request - checks.push({ - name: 'network', - status: 'unknown', - message: 'Network connectivity not monitored', - }); + // Network — DNS resolution check with timeout + { + const t0 = performance.now(); + try { + await Promise.race([ + dns.promises.lookup('registry.npmjs.org'), + new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 3000)), + ]); + const elapsed = performance.now() - t0; + checks.push({ + name: 'network', + status: 'healthy', + latency: Math.round(elapsed * 100) / 100, + message: 'DNS resolution working', + }); + } catch { + const elapsed = performance.now() - t0; + checks.push({ + name: 'network', + status: 'warning', + latency: Math.round(elapsed * 100) / 100, + message: 'DNS resolution failed — check network', + }); + } + } // Database — check if coordination store exists { diff --git a/v3/package-lock.json b/v3/package-lock.json index 8425845984..4a9d854c56 100644 --- a/v3/package-lock.json +++ b/v3/package-lock.json @@ -1789,7 +1789,7 @@ } }, "@claude-flow/cli": { - "version": "3.5.71", + "version": "3.5.72", "hasInstallScript": true, "license": "MIT", "dependencies": {