Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

Checkpoint: File edits

rUv079afa6fb0f8
diff --git a/v3/@claude-flow/cli/src/commands/analyze.ts b/v3/@claude-flow/cli/src/commands/analyze.ts
new file mode 100644
index 0000000000..7fc15a327c
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/analyze.ts
@@ -0,0 +1,462 @@
+/**
+ * V3 CLI Analyze Command
+ * Code analysis, diff classification, AST analysis, and change risk assessment
+ *
+ * Features:
+ * - AST analysis using ruvector (tree-sitter) with graceful fallback
+ * - Symbol extraction (functions, classes, variables, types)
+ * - Cyclomatic complexity scoring
+ * - Diff classification and risk assessment
+ * - Graph boundaries using MinCut algorithm
+ * - Module communities using Louvain algorithm
+ * - Circular dependency detection
+ *
+ * Created with ruv.io
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import { callMCPTool, MCPClientError } from '../mcp-client.js';
+import * as path from 'path';
+import * as fs from 'fs/promises';
+import { writeFile } from 'fs/promises';
+import { resolve } from 'path';
+
+// Dynamic import for AST analyzer
+async function getASTAnalyzer() {
+ try {
+ return await import('../ruvector/ast-analyzer.js');
+ } catch {
+ return null;
+ }
+}
+
+// Dynamic import for graph analyzer
+async function getGraphAnalyzer() {
+ try {
+ return await import('../ruvector/graph-analyzer.js');
+ } catch {
+ return null;
+ }
+}
+
+// Diff subcommand
+const diffCommand: Command = {
+ name: 'diff',
+ description: 'Analyze git diff for change risk assessment and classification',
+ options: [
+ {
+ name: 'risk',
+ short: 'r',
+ description: 'Show risk assessment',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'classify',
+ short: 'c',
+ description: 'Classify change type',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'reviewers',
+ description: 'Show recommended reviewers',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format: text, json, table',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json', 'table'],
+ },
+ {
+ name: 'verbose',
+ short: 'v',
+ description: 'Show detailed file-level analysis',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze diff --risk', description: 'Analyze current diff with risk assessment' },
+ { command: 'claude-flow analyze diff HEAD~1 --classify', description: 'Classify changes from last commit' },
+ { command: 'claude-flow analyze diff main..feature --format json', description: 'Compare branches with JSON output' },
+ { command: 'claude-flow analyze diff --reviewers', description: 'Get recommended reviewers for changes' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const ref = ctx.args[0] || 'HEAD';
+ const showRisk = ctx.flags.risk as boolean;
+ const showClassify = ctx.flags.classify as boolean;
+ const showReviewers = ctx.flags.reviewers as boolean;
+ const formatType = ctx.flags.format as string || 'text';
+ const verbose = ctx.flags.verbose as boolean;
+
+ // If no specific flag, show all
+ const showAll = !showRisk && !showClassify && !showReviewers;
+
+ output.printInfo(`Analyzing diff: ${output.highlight(ref)}`);
+
+ try {
+ // Call MCP tool for diff analysis
+ const result = await callMCPTool<{
+ ref: string;
+ timestamp: string;
+ files: Array<{
+ path: string;
+ status: string;
+ additions: number;
+ deletions: number;
+ binary: boolean;
+ }>;
+ risk: {
+ overall: string;
+ score: number;
+ breakdown: {
+ fileCount: number;
+ totalChanges: number;
+ highRiskFiles: string[];
+ securityConcerns: string[];
+ breakingChanges: string[];
+ testCoverage: string;
+ };
+ };
+ classification: {
+ category: string;
+ subcategory?: string;
+ confidence: number;
+ reasoning: string;
+ };
+ fileRisks: Array<{
+ path: string;
+ risk: string;
+ score: number;
+ reasons: string[];
+ }>;
+ recommendedReviewers: string[];
+ summary: string;
+ }>('analyze/diff', {
+ ref,
+ includeFileRisks: verbose,
+ includeReviewers: showReviewers || showAll,
+ });
+
+ // JSON output
+ if (formatType === 'json') {
+ output.printJson(result);
+ return { success: true, data: result };
+ }
+
+ output.writeln();
+
+ // Summary box
+ output.printBox(
+ [
+ `Ref: ${result.ref}`,
+ `Files: ${result.files.length}`,
+ `Risk: ${getRiskDisplay(result.risk.overall)} (${result.risk.score}/100)`,
+ `Type: ${result.classification.category}${result.classification.subcategory ? ` (${result.classification.subcategory})` : ''}`,
+ ``,
+ result.summary,
+ ].join('\n'),
+ 'Diff Analysis'
+ );
+
+ // Risk assessment
+ if (showRisk || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Risk Assessment'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printTable({
+ columns: [
+ { key: 'metric', header: 'Metric', width: 25 },
+ { key: 'value', header: 'Value', width: 30 },
+ ],
+ data: [
+ { metric: 'Overall Risk', value: getRiskDisplay(result.risk.overall) },
+ { metric: 'Risk Score', value: `${result.risk.score}/100` },
+ { metric: 'Files Changed', value: result.risk.breakdown.fileCount },
+ { metric: 'Total Lines Changed', value: result.risk.breakdown.totalChanges },
+ { metric: 'Test Coverage', value: result.risk.breakdown.testCoverage },
+ ],
+ });
+
+ // Security concerns
+ if (result.risk.breakdown.securityConcerns.length > 0) {
+ output.writeln();
+ output.writeln(output.bold(output.warning('Security Concerns')));
+ output.printList(result.risk.breakdown.securityConcerns.map(c => output.warning(c)));
+ }
+
+ // Breaking changes
+ if (result.risk.breakdown.breakingChanges.length > 0) {
+ output.writeln();
+ output.writeln(output.bold(output.error('Potential Breaking Changes')));
+ output.printList(result.risk.breakdown.breakingChanges.map(c => output.error(c)));
+ }
+
+ // High risk files
+ if (result.risk.breakdown.highRiskFiles.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('High Risk Files'));
+ output.printList(result.risk.breakdown.highRiskFiles.map(f => output.warning(f)));
+ }
+ }
+
+ // Classification
+ if (showClassify || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Classification'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printTable({
+ columns: [
+ { key: 'field', header: 'Field', width: 15 },
+ { key: 'value', header: 'Value', width: 40 },
+ ],
+ data: [
+ { field: 'Category', value: result.classification.category },
+ { field: 'Subcategory', value: result.classification.subcategory || '-' },
+ { field: 'Confidence', value: `${(result.classification.confidence * 100).toFixed(0)}%` },
+ ],
+ });
+
+ output.writeln();
+ output.writeln(output.dim(`Reasoning: ${result.classification.reasoning}`));
+ }
+
+ // Reviewers
+ if (showReviewers || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Recommended Reviewers'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ if (result.recommendedReviewers.length > 0) {
+ output.printNumberedList(result.recommendedReviewers.map(r => output.highlight(r)));
+ } else {
+ output.writeln(output.dim('No specific reviewers recommended'));
+ }
+ }
+
+ // Verbose file-level details
+ if (verbose && result.fileRisks) {
+ output.writeln();
+ output.writeln(output.bold('File-Level Analysis'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printTable({
+ columns: [
+ { key: 'path', header: 'File', width: 40 },
+ { key: 'risk', header: 'Risk', width: 12, format: (v) => getRiskDisplay(String(v)) },
+ { key: 'score', header: 'Score', width: 8, align: 'right' },
+ { key: 'reasons', header: 'Reasons', width: 30, format: (v) => {
+ const reasons = v as string[];
+ return reasons.slice(0, 2).join('; ');
+ }},
+ ],
+ data: result.fileRisks,
+ });
+ }
+
+ // Files changed table
+ if (formatType === 'table' || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Files Changed'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printTable({
+ columns: [
+ { key: 'status', header: 'Status', width: 10, format: (v) => getStatusDisplay(String(v)) },
+ { key: 'path', header: 'File', width: 45 },
+ { key: 'additions', header: '+', width: 8, align: 'right', format: (v) => output.success(`+${v}`) },
+ { key: 'deletions', header: '-', width: 8, align: 'right', format: (v) => output.error(`-${v}`) },
+ ],
+ data: result.files.slice(0, 20),
+ });
+
+ if (result.files.length > 20) {
+ output.writeln(output.dim(` ... and ${result.files.length - 20} more files`));
+ }
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ if (error instanceof MCPClientError) {
+ output.printError(`Diff analysis failed: ${error.message}`);
+ } else {
+ output.printError(`Unexpected error: ${String(error)}`);
+ }
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// Code subcommand (placeholder for future code analysis)
+const codeCommand: Command = {
+ name: 'code',
+ description: 'Static code analysis and quality assessment',
+ options: [
+ { name: 'path', short: 'p', type: 'string', description: 'Path to analyze', default: '.' },
+ { name: 'type', short: 't', type: 'string', description: 'Analysis type: quality, complexity, security', default: 'quality' },
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
+ ],
+ examples: [
+ { command: 'claude-flow analyze code -p ./src', description: 'Analyze source directory' },
+ { command: 'claude-flow analyze code --type complexity', description: 'Run complexity analysis' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const path = ctx.flags.path as string || '.';
+ const analysisType = ctx.flags.type as string || 'quality';
+
+ output.writeln();
+ output.writeln(output.bold('Code Analysis'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printInfo(`Analyzing ${path} for ${analysisType}...`);
+ output.writeln();
+
+ // Placeholder - would integrate with actual code analysis tools
+ output.printBox(
+ [
+ `Path: ${path}`,
+ `Type: ${analysisType}`,
+ `Status: Feature in development`,
+ ``,
+ `Code analysis capabilities coming soon.`,
+ `Use 'analyze diff' for change analysis.`,
+ ].join('\n'),
+ 'Code Analysis'
+ );
+
+ return { success: true };
+ },
+};
+
+// Dependencies subcommand
+const depsCommand: Command = {
+ name: 'deps',
+ description: 'Analyze project dependencies',
+ options: [
+ { name: 'outdated', short: 'o', type: 'boolean', description: 'Show only outdated dependencies' },
+ { name: 'security', short: 's', type: 'boolean', description: 'Check for security vulnerabilities' },
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
+ ],
+ examples: [
+ { command: 'claude-flow analyze deps --outdated', description: 'Show outdated dependencies' },
+ { command: 'claude-flow analyze deps --security', description: 'Check for vulnerabilities' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const showOutdated = ctx.flags.outdated as boolean;
+ const checkSecurity = ctx.flags.security as boolean;
+
+ output.writeln();
+ output.writeln(output.bold('Dependency Analysis'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printInfo('Analyzing dependencies...');
+ output.writeln();
+
+ // Placeholder - would integrate with npm/yarn audit
+ output.printBox(
+ [
+ `Outdated Check: ${showOutdated ? 'Enabled' : 'Disabled'}`,
+ `Security Check: ${checkSecurity ? 'Enabled' : 'Disabled'}`,
+ `Status: Feature in development`,
+ ``,
+ `Dependency analysis capabilities coming soon.`,
+ `Use 'security scan --type deps' for security scanning.`,
+ ].join('\n'),
+ 'Dependency Analysis'
+ );
+
+ return { success: true };
+ },
+};
+
+// Helper functions
+function getRiskDisplay(risk: string): string {
+ switch (risk) {
+ case 'critical':
+ return output.color(output.bold('CRITICAL'), 'bgRed' as never, 'white' as never);
+ case 'high-risk':
+ return output.error('HIGH');
+ case 'medium-risk':
+ return output.warning('MEDIUM');
+ case 'low-risk':
+ return output.success('LOW');
+ default:
+ return risk;
+ }
+}
+
+function getStatusDisplay(status: string): string {
+ switch (status) {
+ case 'added':
+ return output.success('A');
+ case 'modified':
+ return output.warning('M');
+ case 'deleted':
+ return output.error('D');
+ case 'renamed':
+ return output.info('R');
+ default:
+ return status;
+ }
+}
+
+// Main analyze command
+export const analyzeCommand: Command = {
+ name: 'analyze',
+ description: 'Code analysis, diff classification, and change risk assessment',
+ aliases: ['an'],
+ subcommands: [
+ diffCommand,
+ codeCommand,
+ depsCommand,
+ ],
+ options: [
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format: text, json, table',
+ type: 'string',
+ default: 'text',
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze diff --risk', description: 'Analyze diff with risk assessment' },
+ { command: 'claude-flow analyze diff HEAD~1 --classify', description: 'Classify changes from last commit' },
+ { command: 'claude-flow analyze diff main..feature --format json', description: 'Compare branches with JSON output' },
+ { command: 'claude-flow analyze code -p ./src', description: 'Run code analysis' },
+ { command: 'claude-flow analyze deps --security', description: 'Check dependency vulnerabilities' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ // If no subcommand, show help
+ output.writeln();
+ output.writeln(output.bold('Analyze Commands'));
+ output.writeln(output.dim('-'.repeat(50)));
+ output.writeln();
+
+ output.writeln(output.bold('Available subcommands:'));
+ output.writeln();
+ output.writeln(` ${output.highlight('diff')} Analyze git diff for change risk and classification`);
+ output.writeln(` ${output.highlight('code')} Static code analysis and quality assessment`);
+ output.writeln(` ${output.highlight('deps')} Analyze project dependencies`);
+ output.writeln();
+
+ output.writeln(output.bold('Examples:'));
+ output.writeln();
+ output.writeln(` ${output.dim('claude-flow analyze diff --risk')} # Risk assessment`);
+ output.writeln(` ${output.dim('claude-flow analyze diff HEAD~1 --classify')} # Classify changes`);
+ output.writeln(` ${output.dim('claude-flow analyze diff main..feature')} # Compare branches`);
+ output.writeln();
+
+ return { success: true };
+ },
+};
+
+export default analyzeCommand;
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 9fda0b2aa0..2a989584b9 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -2472,6 +2472,418 @@ function formatWorkerStatus(status: string): string {
}
}
+// ============================================================================
+// Coverage-Aware Routing Commands
+// ============================================================================
+
+// Coverage route subcommand
+const coverageRouteCommand: Command = {
+ name: 'coverage-route',
+ description: 'Route task to agents based on test coverage gaps (ruvector integration)',
+ options: [
+ {
+ name: 'task',
+ short: 't',
+ description: 'Task description to route',
+ type: 'string',
+ required: true
+ },
+ {
+ name: 'threshold',
+ description: 'Coverage threshold percentage (default: 80)',
+ type: 'number',
+ default: 80
+ },
+ {
+ name: 'no-ruvector',
+ description: 'Disable ruvector integration',
+ type: 'boolean',
+ default: false
+ }
+ ],
+ examples: [
+ { command: 'claude-flow hooks coverage-route -t "fix bug in auth"', description: 'Route with coverage awareness' },
+ { command: 'claude-flow hooks coverage-route -t "add tests" --threshold 90', description: 'Route with custom threshold' }
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const task = ctx.args[0] || ctx.flags.task as string;
+ const threshold = ctx.flags.threshold as number || 80;
+ const useRuvector = !ctx.flags['no-ruvector'];
+
+ if (!task) {
+ output.printError('Task description is required. Use --task or -t flag.');
+ return { success: false, exitCode: 1 };
+ }
+
+ const spinner = output.createSpinner('Analyzing coverage and routing task...');
+ spinner.start();
+
+ try {
+ const result = await callMCPTool<{
+ success: boolean;
+ task: string;
+ coverageAware: boolean;
+ gaps: Array<{
+ filePath: string;
+ coveragePercent: number;
+ gapType: string;
+ priority: number;
+ suggestedAgents: string[];
+ reason: string;
+ }>;
+ routing: {
+ primaryAgent: string;
+ confidence: number;
+ reason: string;
+ coverageImpact: string;
+ };
+ suggestions: string[];
+ metrics: {
+ filesAnalyzed: number;
+ totalGaps: number;
+ criticalGaps: number;
+ avgCoverage: number;
+ };
+ }>('hooks/coverage-route', {
+ task,
+ threshold,
+ useRuvector,
+ });
+
+ spinner.stop();
+
+ if (ctx.flags.format === 'json') {
+ output.printJson(result);
+ return { success: true, data: result };
+ }
+
+ output.writeln();
+ output.printBox(
+ [
+ `Agent: ${output.highlight(result.routing.primaryAgent)}`,
+ `Confidence: ${(result.routing.confidence * 100).toFixed(1)}%`,
+ `Coverage-Aware: ${result.coverageAware ? output.success('Yes') : output.dim('No coverage data')}`,
+ `Reason: ${result.routing.reason}`
+ ].join('\n'),
+ 'Coverage-Aware Routing'
+ );
+
+ if (result.gaps.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Priority Coverage Gaps'));
+ output.printTable({
+ columns: [
+ { key: 'filePath', header: 'File', width: 35, format: (v) => {
+ const s = String(v);
+ return s.length > 32 ? '...' + s.slice(-32) : s;
+ }},
+ { key: 'coveragePercent', header: 'Coverage', width: 10, align: 'right', format: (v) => `${Number(v).toFixed(1)}%` },
+ { key: 'gapType', header: 'Type', width: 10 },
+ { key: 'suggestedAgents', header: 'Agent', width: 15, format: (v) => Array.isArray(v) ? v[0] || '' : String(v) }
+ ],
+ data: result.gaps.slice(0, 8)
+ });
+ }
+
+ if (result.metrics.filesAnalyzed > 0) {
+ output.writeln();
+ output.writeln(output.bold('Coverage Metrics'));
+ output.printList([
+ `Files Analyzed: ${result.metrics.filesAnalyzed}`,
+ `Total Gaps: ${result.metrics.totalGaps}`,
+ `Critical Gaps: ${result.metrics.criticalGaps}`,
+ `Average Coverage: ${result.metrics.avgCoverage.toFixed(1)}%`
+ ]);
+ }
+
+ if (result.suggestions.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Suggestions'));
+ output.printList(result.suggestions.map(s => output.dim(s)));
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.fail('Coverage routing failed');
+ if (error instanceof MCPClientError) {
+ output.printError(`Error: ${error.message}`);
+ } else {
+ output.printError(`Unexpected error: ${String(error)}`);
+ }
+ return { success: false, exitCode: 1 };
+ }
+ }
+};
+
+// Coverage suggest subcommand
+const coverageSuggestCommand: Command = {
+ name: 'coverage-suggest',
+ description: 'Suggest coverage improvements for a path (ruvector integration)',
+ options: [
+ {
+ name: 'path',
+ short: 'p',
+ description: 'Path to analyze for coverage suggestions',
+ type: 'string',
+ required: true
+ },
+ {
+ name: 'threshold',
+ description: 'Coverage threshold percentage (default: 80)',
+ type: 'number',
+ default: 80
+ },
+ {
+ name: 'limit',
+ short: 'l',
+ description: 'Maximum number of suggestions (default: 20)',
+ type: 'number',
+ default: 20
+ }
+ ],
+ examples: [
+ { command: 'claude-flow hooks coverage-suggest -p src/', description: 'Suggest improvements for src/' },
+ { command: 'claude-flow hooks coverage-suggest -p src/services --threshold 90', description: 'Stricter threshold' }
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const path = ctx.args[0] || ctx.flags.path as string;
+ const threshold = ctx.flags.threshold as number || 80;
+ const limit = ctx.flags.limit as number || 20;
+
+ if (!path) {
+ output.printError('Path is required. Use --path or -p flag.');
+ return { success: false, exitCode: 1 };
+ }
+
+ const spinner = output.createSpinner(`Analyzing coverage for ${path}...`);
+ spinner.start();
+
+ try {
+ const result = await callMCPTool<{
+ success: boolean;
+ path: string;
+ suggestions: Array<{
+ filePath: string;
+ coveragePercent: number;
+ gapType: string;
+ priority: number;
+ suggestedAgents: string[];
+ reason: string;
+ }>;
+ summary: {
+ totalFiles: number;
+ overallLineCoverage: number;
+ overallBranchCoverage: number;
+ filesBelowThreshold: number;
+ };
+ prioritizedFiles: string[];
+ ruvectorAvailable: boolean;
+ }>('hooks/coverage-suggest', {
+ path,
+ threshold,
+ limit,
+ });
+
+ spinner.stop();
+
+ if (ctx.flags.format === 'json') {
+ output.printJson(result);
+ return { success: true, data: result };
+ }
+
+ output.writeln();
+ output.printBox(
+ [
+ `Path: ${output.highlight(result.path)}`,
+ `Files Analyzed: ${result.summary.totalFiles}`,
+ `Line Coverage: ${result.summary.overallLineCoverage.toFixed(1)}%`,
+ `Branch Coverage: ${result.summary.overallBranchCoverage.toFixed(1)}%`,
+ `Below Threshold: ${result.summary.filesBelowThreshold} files`,
+ `RuVector: ${result.ruvectorAvailable ? output.success('Available') : output.dim('Not installed')}`
+ ].join('\n'),
+ 'Coverage Summary'
+ );
+
+ if (result.suggestions.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Coverage Improvement Suggestions'));
+ output.printTable({
+ columns: [
+ { key: 'filePath', header: 'File', width: 40, format: (v) => {
+ const s = String(v);
+ return s.length > 37 ? '...' + s.slice(-37) : s;
+ }},
+ { key: 'coveragePercent', header: 'Coverage', width: 10, align: 'right', format: (v) => `${Number(v).toFixed(1)}%` },
+ { key: 'gapType', header: 'Priority', width: 10 },
+ { key: 'reason', header: 'Reason', width: 25 }
+ ],
+ data: result.suggestions.slice(0, 15)
+ });
+ } else {
+ output.writeln();
+ output.printSuccess('All files meet coverage threshold!');
+ }
+
+ if (result.prioritizedFiles.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Priority Files (Top 5)'));
+ output.printList(result.prioritizedFiles.slice(0, 5).map(f => output.highlight(f)));
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.fail('Coverage analysis failed');
+ if (error instanceof MCPClientError) {
+ output.printError(`Error: ${error.message}`);
+ } else {
+ output.printError(`Unexpected error: ${String(error)}`);
+ }
+ return { success: false, exitCode: 1 };
+ }
+ }
+};
+
+// Coverage gaps subcommand
+const coverageGapsCommand: Command = {
+ name: 'coverage-gaps',
+ description: 'List all coverage gaps with priority scoring and agent assignments',
+ options: [
+ {
+ name: 'threshold',
+ description: 'Coverage threshold percentage (default: 80)',
+ type: 'number',
+ default: 80
+ },
+ {
+ name: 'group-by-agent',
+ description: 'Group gaps by suggested agent (default: true)',
+ type: 'boolean',
+ default: true
+ },
+ {
+ name: 'critical-only',
+ description: 'Show only critical gaps',
+ type: 'boolean',
+ default: false
+ }
+ ],
+ examples: [
+ { command: 'claude-flow hooks coverage-gaps', description: 'List all coverage gaps' },
+ { command: 'claude-flow hooks coverage-gaps --critical-only', description: 'Only critical gaps' },
+ { command: 'claude-flow hooks coverage-gaps --threshold 90', description: 'Stricter threshold' }
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const threshold = ctx.flags.threshold as number || 80;
+ const groupByAgent = ctx.flags['group-by-agent'] !== false;
+ const criticalOnly = ctx.flags['critical-only'] as boolean || false;
+
+ const spinner = output.createSpinner('Analyzing project coverage gaps...');
+ spinner.start();
+
+ try {
+ const result = await callMCPTool<{
+ success: boolean;
+ gaps: Array<{
+ filePath: string;
+ coveragePercent: number;
+ gapType: string;
+ complexity: number;
+ priority: number;
+ suggestedAgents: string[];
+ reason: string;
+ }>;
+ summary: {
+ totalFiles: number;
+ overallLineCoverage: number;
+ overallBranchCoverage: number;
+ filesBelowThreshold: number;
+ coverageThreshold: number;
+ };
+ agentAssignments: Record<string, string[]>;
+ ruvectorAvailable: boolean;
+ }>('hooks/coverage-gaps', {
+ threshold,
+ groupByAgent,
+ });
+
+ spinner.stop();
+
+ // Filter if critical-only
+ const gaps = criticalOnly
+ ? result.gaps.filter(g => g.gapType === 'critical')
+ : result.gaps;
+
+ if (ctx.flags.format === 'json') {
+ output.printJson({ ...result, gaps });
+ return { success: true, data: result };
+ }
+
+ output.writeln();
+ output.printBox(
+ [
+ `Total Files: ${result.summary.totalFiles}`,
+ `Line Coverage: ${result.summary.overallLineCoverage.toFixed(1)}%`,
+ `Branch Coverage: ${result.summary.overallBranchCoverage.toFixed(1)}%`,
+ `Below ${result.summary.coverageThreshold}%: ${result.summary.filesBelowThreshold} files`,
+ `RuVector: ${result.ruvectorAvailable ? output.success('Available') : output.dim('Not installed')}`
+ ].join('\n'),
+ 'Coverage Gap Analysis'
+ );
+
+ if (gaps.length > 0) {
+ output.writeln();
+ output.writeln(output.bold(`Coverage Gaps (${gaps.length} files)`));
+ output.printTable({
+ columns: [
+ { key: 'filePath', header: 'File', width: 35, format: (v) => {
+ const s = String(v);
+ return s.length > 32 ? '...' + s.slice(-32) : s;
+ }},
+ { key: 'coveragePercent', header: 'Coverage', width: 10, align: 'right', format: (v) => `${Number(v).toFixed(1)}%` },
+ { key: 'gapType', header: 'Type', width: 10, format: (v) => {
+ const t = String(v);
+ if (t === 'critical') return output.error(t);
+ if (t === 'high') return output.warning(t);
+ return t;
+ }},
+ { key: 'priority', header: 'Priority', width: 8, align: 'right' },
+ { key: 'suggestedAgents', header: 'Agent', width: 12, format: (v) => Array.isArray(v) ? v[0] || '' : String(v) }
+ ],
+ data: gaps.slice(0, 20)
+ });
+ } else {
+ output.writeln();
+ output.printSuccess('No coverage gaps found! All files meet threshold.');
+ }
+
+ if (groupByAgent && Object.keys(result.agentAssignments).length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Agent Assignments'));
+ for (const [agent, files] of Object.entries(result.agentAssignments)) {
+ output.writeln();
+ output.writeln(` ${output.highlight(agent)} (${files.length} files)`);
+ files.slice(0, 3).forEach(f => {
+ output.writeln(` - ${output.dim(f)}`);
+ });
+ if (files.length > 3) {
+ output.writeln(` ... and ${files.length - 3} more`);
+ }
+ }
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.fail('Coverage gap analysis failed');
+ if (error instanceof MCPClientError) {
+ output.printError(`Error: ${error.message}`);
+ } else {
+ output.printError(`Unexpected error: ${String(error)}`);
+ }
+ return { success: false, exitCode: 1 };
+ }
+ }
+};
+
// Worker parent command
const workerCommand: Command = {
name: 'worker',
@@ -2548,6 +2960,10 @@ export const hooksCommand: Command = {
listCommand,
intelligenceCommand,
workerCommand,
+ // Coverage-aware routing commands
+ coverageRouteCommand,
+ coverageSuggestCommand,
+ coverageGapsCommand,
],
options: [],
examples: [
@@ -2581,7 +2997,10 @@ export const hooksCommand: Command = {
`${output.highlight('metrics')} - View learning metrics dashboard`,
`${output.highlight('transfer')} - Transfer patterns from another project`,
`${output.highlight('list')} - List all registered hooks`,
- `${output.highlight('worker')} - Background worker management (12 workers)`
+ `${output.highlight('worker')} - Background worker management (12 workers)`,
+ `${output.highlight('coverage-route')} - Route tasks based on coverage gaps (ruvector)`,
+ `${output.highlight('coverage-suggest')}- Suggest coverage improvements`,
+ `${output.highlight('coverage-gaps')} - List all coverage gaps with agents`
]);
output.writeln();
output.writeln('Run "claude-flow hooks <subcommand> --help" for subcommand help');
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index dc1f0a5c6c..391671e206 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -33,6 +33,10 @@ import { embeddingsCommand } from './embeddings.js';
// P0 Commands
import { completionsCommand } from './completions.js';
import { doctorCommand } from './doctor.js';
+// Analysis Commands
+import { analyzeCommand } from './analyze.js';
+// Q-Learning Routing Commands
+import { routeCommand } from './route.js';
// Export all commands
export { agentCommand } from './agent.js';
@@ -64,6 +68,10 @@ export { embeddingsCommand } from './embeddings.js';
// P0 Commands
export { completionsCommand } from './completions.js';
export { doctorCommand } from './doctor.js';
+// Analysis Commands
+export { analyzeCommand } from './analyze.js';
+// Q-Learning Routing Commands
+export { routeCommand } from './route.js';
/**
* All available commands
@@ -99,6 +107,8 @@ export const commands: Command[] = [
// P0 Commands
completionsCommand,
doctorCommand,
+ // Analysis Commands
+ analyzeCommand,
];
/**
diff --git a/v3/@claude-flow/cli/src/commands/route.ts b/v3/@claude-flow/cli/src/commands/route.ts
new file mode 100644
index 0000000000..6d21ee8869
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/route.ts
@@ -0,0 +1,593 @@
+/**
+ * V3 CLI Route Command
+ * Intelligent task-to-agent routing using Q-Learning
+ *
+ * Features:
+ * - Q-Learning based agent selection
+ * - Semantic task understanding
+ * - Confidence scoring
+ * - Learning from feedback
+ *
+ * Created with love by ruv.io
+ */
+
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+
+// ============================================================================
+// Helper Functions (avoid top-level await)
+// ============================================================================
+
+async function getRouterModule() {
+ try {
+ return await import('../ruvector/q-learning-router.js');
+ } catch {
+ return null;
+ }
+}
+
+async function getRuVectorModule() {
+ try {
+ return await import('../ruvector/index.js');
+ } catch {
+ return null;
+ }
+}
+
+// ============================================================================
+// Route Subcommand
+// ============================================================================
+
+const routeTaskCommand: Command = {
+ name: 'task',
+ description: 'Route a task to the optimal agent using Q-Learning',
+ options: [
+ {
+ name: 'q-learning',
+ short: 'q',
+ description: 'Use Q-Learning for agent selection (default: true)',
+ type: 'boolean',
+ default: true,
+ },
+ {
+ name: 'agent',
+ short: 'a',
+ description: 'Force specific agent (bypasses Q-Learning)',
+ type: 'string',
+ },
+ {
+ name: 'explore',
+ short: 'e',
+ description: 'Enable exploration (random selection chance)',
+ type: 'boolean',
+ default: true,
+ },
+ {
+ name: 'json',
+ short: 'j',
+ description: 'Output in JSON format',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route task "implement authentication"', description: 'Route task to best agent' },
+ { command: 'claude-flow route task "write unit tests" --q-learning', description: 'Use Q-Learning routing' },
+ { command: 'claude-flow route task "review code" --agent reviewer', description: 'Force specific agent' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const taskDescription = ctx.args[0];
+ const forceAgent = ctx.flags.agent as string | undefined;
+ const useExploration = ctx.flags.explore as boolean;
+ const jsonOutput = ctx.flags.json as boolean;
+
+ if (!taskDescription) {
+ output.printError('Task description is required');
+ output.writeln(output.dim('Usage: claude-flow route task "task description"'));
+ return { success: false, exitCode: 1 };
+ }
+
+ const routerModule = await getRouterModule();
+ if (!routerModule) {
+ output.printError('Router module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ const spinner = output.createSpinner({ text: 'Analyzing task...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ if (forceAgent) {
+ // Bypass Q-Learning, use specified agent
+ const agents = await routerModule.listAgentTypes();
+ const agent = agents.find(a => a.id === forceAgent || a.name.toLowerCase() === forceAgent.toLowerCase());
+
+ if (!agent) {
+ spinner.fail(`Agent "${forceAgent}" not found`);
+ output.writeln();
+ output.writeln('Available agents:');
+ output.printList(agents.map(a => `${output.highlight(a.id)} - ${a.description}`));
+ return { success: false, exitCode: 1 };
+ }
+
+ spinner.succeed(`Routed to ${agent.name}`);
+
+ if (jsonOutput) {
+ output.printJson({
+ task: taskDescription,
+ agentId: agent.id,
+ agentName: agent.name,
+ confidence: 1.0,
+ method: 'forced',
+ });
+ } else {
+ output.writeln();
+ output.printBox([
+ `Task: ${taskDescription}`,
+ `Agent: ${output.highlight(agent.name)} (${agent.id})`,
+ `Confidence: ${output.success('100%')} (forced)`,
+ `Description: ${agent.description}`,
+ ].join('\n'), 'Routing Result');
+ }
+
+ return { success: true, data: { agentId: agent.id, agentName: agent.name } };
+ }
+
+ // Use Q-Learning routing
+ const result = await routerModule.routeTask(taskDescription, useExploration);
+
+ spinner.succeed(`Routed to ${result.agentType.name}`);
+
+ if (jsonOutput) {
+ output.printJson({
+ task: taskDescription,
+ agentId: result.agentId,
+ agentName: result.agentType.name,
+ confidence: result.confidence,
+ qValue: result.qValue,
+ explorationUsed: result.explorationUsed,
+ alternatives: result.alternatives.map(a => ({
+ agentId: a.agentId,
+ agentName: a.agentType.name,
+ confidence: a.confidence,
+ qValue: a.qValue,
+ })),
+ });
+ } else {
+ output.writeln();
+
+ const confidenceColor = result.confidence >= 0.7
+ ? output.success
+ : result.confidence >= 0.4
+ ? output.warning
+ : output.error;
+
+ output.printBox([
+ `Task: ${taskDescription}`,
+ ``,
+ `Agent: ${output.highlight(result.agentType.name)} (${result.agentId})`,
+ `Confidence: ${confidenceColor(`${(result.confidence * 100).toFixed(1)}%`)}`,
+ `Q-Value: ${result.qValue.toFixed(3)}`,
+ `Exploration: ${result.explorationUsed ? output.warning('Yes') : 'No'}`,
+ ``,
+ `Description: ${result.agentType.description}`,
+ `Capabilities: ${result.agentType.capabilities.join(', ')}`,
+ ].join('\n'), 'Q-Learning Routing');
+
+ if (result.alternatives.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Alternatives:'));
+ output.printTable({
+ columns: [
+ { key: 'agent', header: 'Agent', width: 20 },
+ { key: 'confidence', header: 'Confidence', width: 12, align: 'right' },
+ { key: 'qValue', header: 'Q-Value', width: 10, align: 'right' },
+ ],
+ data: result.alternatives.map(a => ({
+ agent: a.agentType.name,
+ confidence: `${(a.confidence * 100).toFixed(1)}%`,
+ qValue: a.qValue.toFixed(3),
+ })),
+ });
+ }
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.fail('Routing failed');
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// List Agents Subcommand
+// ============================================================================
+
+const listAgentsCommand: Command = {
+ name: 'list-agents',
+ aliases: ['agents', 'ls'],
+ description: 'List all available agent types for routing',
+ options: [
+ {
+ name: 'json',
+ short: 'j',
+ description: 'Output in JSON format',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route list-agents', description: 'List all agents' },
+ { command: 'claude-flow route agents --json', description: 'List agents as JSON' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const jsonOutput = ctx.flags.json as boolean;
+
+ const routerModule = await getRouterModule();
+ if (!routerModule) {
+ output.printError('Router module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ try {
+ const agents = await routerModule.listAgentTypes();
+
+ if (jsonOutput) {
+ output.printJson(agents);
+ } else {
+ output.writeln();
+ output.writeln(output.bold('Available Agent Types'));
+ output.writeln(output.dim('Ordered by priority (highest first)'));
+ output.writeln();
+
+ output.printTable({
+ columns: [
+ { key: 'id', header: 'ID', width: 20 },
+ { key: 'name', header: 'Name', width: 20 },
+ { key: 'priority', header: 'Priority', width: 10, align: 'right' },
+ { key: 'description', header: 'Description', width: 40 },
+ ],
+ data: agents.map(a => ({
+ id: output.highlight(a.id),
+ name: a.name,
+ priority: String(a.priority),
+ description: a.description,
+ })),
+ });
+
+ output.writeln();
+ output.writeln(output.dim(`Total: ${agents.length} agent types`));
+ }
+
+ return { success: true, data: agents };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// Stats Subcommand
+// ============================================================================
+
+const statsCommand: Command = {
+ name: 'stats',
+ description: 'Show Q-Learning router statistics',
+ options: [
+ {
+ name: 'json',
+ short: 'j',
+ description: 'Output in JSON format',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route stats', description: 'Show routing statistics' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const jsonOutput = ctx.flags.json as boolean;
+
+ const routerModule = await getRouterModule();
+ const ruvectorModule = await getRuVectorModule();
+
+ if (!routerModule) {
+ output.printError('Router module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ try {
+ const stats = await routerModule.getRouterStats();
+ const ruvectorStatus = ruvectorModule?.getStatus?.() ?? {
+ available: false,
+ wasmAccelerated: false,
+ backend: 'fallback',
+ };
+
+ if (jsonOutput) {
+ output.printJson({ stats, ruvector: ruvectorStatus });
+ } else {
+ output.writeln();
+ output.writeln(output.bold('Q-Learning Router Statistics'));
+ output.writeln();
+
+ output.printTable({
+ columns: [
+ { key: 'metric', header: 'Metric', width: 25 },
+ { key: 'value', header: 'Value', width: 20, align: 'right' },
+ ],
+ data: [
+ { metric: 'Total Routes', value: String(stats.totalRoutes) },
+ { metric: 'Successful Routes', value: String(stats.successfulRoutes) },
+ { metric: 'Success Rate', value: stats.totalRoutes > 0
+ ? `${((stats.successfulRoutes / stats.totalRoutes) * 100).toFixed(1)}%`
+ : 'N/A' },
+ { metric: 'Avg Confidence', value: `${(stats.avgConfidence * 100).toFixed(1)}%` },
+ { metric: 'Avg Execution Time', value: `${stats.avgExecutionTime.toFixed(0)}ms` },
+ { metric: 'Q-Table Size', value: String(stats.qTableSize) },
+ { metric: 'Epsilon', value: stats.epsilon.toFixed(3) },
+ { metric: 'Backend', value: stats.backend },
+ ],
+ });
+
+ if (Object.keys(stats.agentUsage).length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Agent Usage'));
+ output.printTable({
+ columns: [
+ { key: 'agent', header: 'Agent', width: 20 },
+ { key: 'count', header: 'Routes', width: 10, align: 'right' },
+ { key: 'percentage', header: '%', width: 10, align: 'right' },
+ ],
+ data: Object.entries(stats.agentUsage)
+ .sort((a, b) => b[1] - a[1])
+ .map(([agent, count]) => ({
+ agent,
+ count: String(count),
+ percentage: `${((count / stats.totalRoutes) * 100).toFixed(1)}%`,
+ })),
+ });
+ }
+
+ output.writeln();
+ output.writeln(output.bold('RuVector Status'));
+ output.printList([
+ `Available: ${ruvectorStatus.available ? output.success('Yes') : output.warning('No (using fallback)')}`,
+ `WASM Accelerated: ${ruvectorStatus.wasmAccelerated ? output.success('Yes') : 'No'}`,
+ `Backend: ${ruvectorStatus.backend}`,
+ ]);
+ }
+
+ return { success: true, data: { stats, ruvector: ruvectorStatus } };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// Feedback Subcommand
+// ============================================================================
+
+const feedbackCommand: Command = {
+ name: 'feedback',
+ description: 'Provide feedback on a routing decision',
+ options: [
+ {
+ name: 'task-id',
+ short: 't',
+ description: 'Task identifier',
+ type: 'string',
+ required: true,
+ },
+ {
+ name: 'agent',
+ short: 'a',
+ description: 'Agent that was used',
+ type: 'string',
+ required: true,
+ },
+ {
+ name: 'success',
+ short: 's',
+ description: 'Whether the routing was successful',
+ type: 'boolean',
+ default: true,
+ },
+ {
+ name: 'quality',
+ short: 'q',
+ description: 'Quality score (0-1)',
+ type: 'number',
+ default: 0.8,
+ },
+ {
+ name: 'time',
+ description: 'Execution time in milliseconds',
+ type: 'number',
+ default: 1000,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route feedback -t "auth-impl" -a coder -s true -q 0.9', description: 'Positive feedback' },
+ { command: 'claude-flow route feedback -t "test-write" -a tester -s false', description: 'Negative feedback' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const taskId = ctx.flags['task-id'] as string;
+ const agentId = ctx.flags.agent as string;
+ const success = ctx.flags.success as boolean;
+ const quality = ctx.flags.quality as number;
+ const executionTime = ctx.flags.time as number;
+
+ if (!taskId || !agentId) {
+ output.printError('Task ID and agent are required');
+ return { success: false, exitCode: 1 };
+ }
+
+ const routerModule = await getRouterModule();
+ if (!routerModule) {
+ output.printError('Router module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ try {
+ await routerModule.provideFeedback({
+ taskId,
+ agentId,
+ success,
+ quality: Math.max(0, Math.min(1, quality)),
+ executionTimeMs: executionTime,
+ });
+
+ output.printSuccess(`Feedback recorded for task "${taskId}"`);
+ output.writeln();
+ output.printBox([
+ `Task: ${taskId}`,
+ `Agent: ${agentId}`,
+ `Success: ${success ? output.success('Yes') : output.error('No')}`,
+ `Quality: ${(quality * 100).toFixed(0)}%`,
+ `Time: ${executionTime}ms`,
+ ].join('\n'), 'Feedback Recorded');
+
+ return { success: true };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// Reset Subcommand
+// ============================================================================
+
+const resetCommand: Command = {
+ name: 'reset',
+ description: 'Reset the Q-Learning router state',
+ options: [
+ {
+ name: 'force',
+ short: 'f',
+ description: 'Force reset without confirmation',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route reset', description: 'Reset router state' },
+ { command: 'claude-flow route reset --force', description: 'Force reset' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const force = ctx.flags.force as boolean;
+
+ if (!force && ctx.interactive) {
+ output.printWarning('This will reset all learned Q-values and statistics.');
+ output.writeln(output.dim('Use --force to skip this confirmation.'));
+ return { success: false, exitCode: 1 };
+ }
+
+ const routerModule = await getRouterModule();
+ if (!routerModule) {
+ output.printError('Router module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ try {
+ const router = await routerModule.getRouter();
+ router.reset();
+ output.printSuccess('Q-Learning router state has been reset');
+ return { success: true };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// Main Route Command
+// ============================================================================
+
+export const routeCommand: Command = {
+ name: 'route',
+ description: 'Intelligent task-to-agent routing using Q-Learning',
+ subcommands: [routeTaskCommand, listAgentsCommand, statsCommand, feedbackCommand, resetCommand],
+ options: [
+ {
+ name: 'q-learning',
+ short: 'q',
+ description: 'Use Q-Learning for agent selection',
+ type: 'boolean',
+ default: true,
+ },
+ {
+ name: 'agent',
+ short: 'a',
+ description: 'Force specific agent',
+ type: 'string',
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route "implement feature"', description: 'Route task to best agent' },
+ { command: 'claude-flow route "write tests" --q-learning', description: 'Use Q-Learning routing' },
+ { command: 'claude-flow route --agent coder "fix bug"', description: 'Force specific agent' },
+ { command: 'claude-flow route list-agents', description: 'List available agents' },
+ { command: 'claude-flow route stats', description: 'Show routing statistics' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ // If task description provided directly, route it
+ if (ctx.args.length > 0) {
+ return routeTaskCommand.action!(ctx);
+ }
+
+ // Show help
+ output.writeln();
+ output.writeln(output.bold('Q-Learning Agent Router'));
+ output.writeln(output.dim('Intelligent task-to-agent routing using reinforcement learning'));
+ output.writeln();
+
+ output.writeln('Usage: claude-flow route <task> [options]');
+ output.writeln(' claude-flow route <subcommand>');
+ output.writeln();
+
+ output.writeln(output.bold('Subcommands:'));
+ output.printList([
+ `${output.highlight('task')} - Route a task to optimal agent`,
+ `${output.highlight('list-agents')} - List available agent types`,
+ `${output.highlight('stats')} - Show router statistics`,
+ `${output.highlight('feedback')} - Provide routing feedback`,
+ `${output.highlight('reset')} - Reset router state`,
+ ]);
+ output.writeln();
+
+ output.writeln(output.bold('How It Works:'));
+ output.printList([
+ 'Analyzes task description using semantic embeddings',
+ 'Uses Q-Learning to learn from routing outcomes',
+ 'Epsilon-greedy exploration for continuous improvement',
+ 'Provides confidence scores and alternatives',
+ ]);
+ output.writeln();
+
+ // Show quick status
+ const ruvectorModule = await getRuVectorModule();
+ const status = ruvectorModule?.getStatus?.() ?? { available: false, backend: 'fallback' };
+
+ output.writeln(output.bold('Backend Status:'));
+ output.printList([
+ `RuVector: ${status.available ? output.success('Available') : output.warning('Fallback mode')}`,
+ `Backend: ${status.backend}`,
+ ]);
+ output.writeln();
+
+ output.writeln(output.dim('Run "claude-flow route <subcommand> --help" for more info'));
+
+ return { success: true };
+ },
+};
+
+export default routeCommand;
diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.ts
index e613bb0e24..bd24b63fb5 100644
--- a/v3/@claude-flow/cli/src/mcp-client.ts
+++ b/v3/@claude-flow/cli/src/mcp-client.ts
@@ -20,6 +20,7 @@ import { taskTools } from './mcp-tools/task-tools.js';
import { sessionTools } from './mcp-tools/session-tools.js';
import { hiveMindTools } from './mcp-tools/hive-mind-tools.js';
import { workflowTools } from './mcp-tools/workflow-tools.js';
+import { analyzeTools } from './mcp-tools/analyze-tools.js';
/**
* MCP Tool Registry
@@ -45,6 +46,7 @@ registerTools([
...sessionTools,
...hiveMindTools,
...workflowTools,
+ ...analyzeTools,
]);
/**
diff --git a/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts
new file mode 100644
index 0000000000..a62bd1a565
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts
@@ -0,0 +1,346 @@
+/**
+ * Analyze MCP Tools
+ * Provides diff analysis and classification via MCP protocol
+ */
+
+import type { MCPTool } from './types.js';
+import {
+ analyzeDiff,
+ assessFileRisk,
+ assessOverallRisk,
+ classifyDiff,
+ suggestReviewers,
+ getGitDiffNumstat,
+ type DiffFile,
+ type RiskLevel,
+} from '../ruvector/diff-classifier.js';
+
+/**
+ * Diff Analysis Tool
+ * Analyzes git diffs for change risk assessment and classification
+ */
+export const analyzeDiffTool: MCPTool = {
+ name: 'analyze/diff',
+ description: 'Analyze git diff for change risk assessment and classification',
+ category: 'analyze',
+ tags: ['diff', 'risk', 'classification', 'git'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ref: {
+ type: 'string',
+ description: 'Git ref to compare against (e.g., HEAD~1, main..feature, commit hash)',
+ default: 'HEAD',
+ },
+ includeFileRisks: {
+ type: 'boolean',
+ description: 'Include detailed file-level risk analysis',
+ default: false,
+ },
+ includeReviewers: {
+ type: 'boolean',
+ description: 'Include recommended reviewers',
+ default: true,
+ },
+ useRuVector: {
+ type: 'boolean',
+ description: 'Attempt to use ruvector for analysis (graceful fallback if unavailable)',
+ default: true,
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const ref = (params.ref as string) || 'HEAD';
+ const includeFileRisks = params.includeFileRisks !== false;
+ const includeReviewers = params.includeReviewers !== false;
+ const useRuVector = params.useRuVector !== false;
+
+ try {
+ const result = await analyzeDiff({
+ ref,
+ useRuVector,
+ });
+
+ // Build response
+ const response: Record<string, unknown> = {
+ ref: result.ref,
+ timestamp: result.timestamp,
+ files: result.files,
+ risk: result.risk,
+ classification: result.classification,
+ summary: result.summary,
+ };
+
+ if (includeFileRisks) {
+ response.fileRisks = result.fileRisks;
+ }
+
+ if (includeReviewers) {
+ response.recommendedReviewers = result.recommendedReviewers;
+ }
+
+ return response;
+ } catch (error) {
+ return {
+ error: true,
+ message: error instanceof Error ? error.message : String(error),
+ ref,
+ };
+ }
+ },
+};
+
+/**
+ * Diff Risk Assessment Tool
+ * Focused risk assessment without full analysis
+ */
+export const diffRiskTool: MCPTool = {
+ name: 'analyze/diff-risk',
+ description: 'Quick risk assessment for git diff',
+ category: 'analyze',
+ tags: ['diff', 'risk', 'git'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ref: {
+ type: 'string',
+ description: 'Git ref to compare against',
+ default: 'HEAD',
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const ref = (params.ref as string) || 'HEAD';
+
+ try {
+ const files = getGitDiffNumstat(ref);
+ const fileRisks = files.map(assessFileRisk);
+ const risk = assessOverallRisk(files, fileRisks);
+
+ return {
+ ref,
+ risk,
+ summary: `${risk.overall} risk (score: ${risk.score}/100) - ${files.length} files changed`,
+ };
+ } catch (error) {
+ return {
+ error: true,
+ message: error instanceof Error ? error.message : String(error),
+ ref,
+ };
+ }
+ },
+};
+
+/**
+ * Diff Classification Tool
+ * Classify change type without full analysis
+ */
+export const diffClassifyTool: MCPTool = {
+ name: 'analyze/diff-classify',
+ description: 'Classify git diff change type',
+ category: 'analyze',
+ tags: ['diff', 'classification', 'git'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ref: {
+ type: 'string',
+ description: 'Git ref to compare against',
+ default: 'HEAD',
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const ref = (params.ref as string) || 'HEAD';
+
+ try {
+ const files = getGitDiffNumstat(ref);
+ const classification = classifyDiff(files);
+
+ return {
+ ref,
+ classification,
+ files: files.length,
+ };
+ } catch (error) {
+ return {
+ error: true,
+ message: error instanceof Error ? error.message : String(error),
+ ref,
+ };
+ }
+ },
+};
+
+/**
+ * Diff Reviewers Tool
+ * Suggest reviewers for changes
+ */
+export const diffReviewersTool: MCPTool = {
+ name: 'analyze/diff-reviewers',
+ description: 'Suggest reviewers for git diff changes',
+ category: 'analyze',
+ tags: ['diff', 'reviewers', 'git'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ref: {
+ type: 'string',
+ description: 'Git ref to compare against',
+ default: 'HEAD',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of reviewers to suggest',
+ default: 5,
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const ref = (params.ref as string) || 'HEAD';
+ const limit = (params.limit as number) || 5;
+
+ try {
+ const files = getGitDiffNumstat(ref);
+ const fileRisks = files.map(assessFileRisk);
+ const reviewers = suggestReviewers(files, fileRisks);
+
+ return {
+ ref,
+ recommendedReviewers: reviewers.slice(0, limit),
+ filesAnalyzed: files.length,
+ };
+ } catch (error) {
+ return {
+ error: true,
+ message: error instanceof Error ? error.message : String(error),
+ ref,
+ };
+ }
+ },
+};
+
+/**
+ * File Risk Tool
+ * Assess risk for a specific file path
+ */
+export const fileRiskTool: MCPTool = {
+ name: 'analyze/file-risk',
+ description: 'Assess risk for a specific file change',
+ category: 'analyze',
+ tags: ['file', 'risk'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: {
+ type: 'string',
+ description: 'File path to assess',
+ },
+ additions: {
+ type: 'number',
+ description: 'Number of lines added',
+ default: 0,
+ },
+ deletions: {
+ type: 'number',
+ description: 'Number of lines deleted',
+ default: 0,
+ },
+ status: {
+ type: 'string',
+ description: 'File status: added, modified, deleted, renamed',
+ default: 'modified',
+ },
+ },
+ required: ['path'],
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const file: DiffFile = {
+ path: params.path as string,
+ status: (params.status as DiffFile['status']) || 'modified',
+ additions: (params.additions as number) || 0,
+ deletions: (params.deletions as number) || 0,
+ hunks: 1,
+ binary: false,
+ };
+
+ const risk = assessFileRisk(file);
+
+ return {
+ file: file.path,
+ risk: risk.risk,
+ score: risk.score,
+ reasons: risk.reasons,
+ };
+ },
+};
+
+/**
+ * Diff Stats Tool
+ * Get quick diff statistics
+ */
+export const diffStatsTool: MCPTool = {
+ name: 'analyze/diff-stats',
+ description: 'Get quick statistics for git diff',
+ category: 'analyze',
+ tags: ['diff', 'stats', 'git'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ref: {
+ type: 'string',
+ description: 'Git ref to compare against',
+ default: 'HEAD',
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>) => {
+ const ref = (params.ref as string) || 'HEAD';
+
+ try {
+ const files = getGitDiffNumstat(ref);
+
+ const totalAdditions = files.reduce((sum, f) => sum + f.additions, 0);
+ const totalDeletions = files.reduce((sum, f) => sum + f.deletions, 0);
+ const addedFiles = files.filter(f => f.status === 'added').length;
+ const modifiedFiles = files.filter(f => f.status === 'modified').length;
+ const deletedFiles = files.filter(f => f.status === 'deleted').length;
+ const renamedFiles = files.filter(f => f.status === 'renamed').length;
+ const binaryFiles = files.filter(f => f.binary).length;
+
+ return {
+ ref,
+ totalFiles: files.length,
+ totalAdditions,
+ totalDeletions,
+ totalChanges: totalAdditions + totalDeletions,
+ byStatus: {
+ added: addedFiles,
+ modified: modifiedFiles,
+ deleted: deletedFiles,
+ renamed: renamedFiles,
+ },
+ binaryFiles,
+ };
+ } catch (error) {
+ return {
+ error: true,
+ message: error instanceof Error ? error.message : String(error),
+ ref,
+ };
+ }
+ },
+};
+
+// Export all analyze tools
+export const analyzeTools: MCPTool[] = [
+ analyzeDiffTool,
+ diffRiskTool,
+ diffClassifyTool,
+ diffReviewersTool,
+ fileRiskTool,
+ diffStatsTool,
+];
+
+export default analyzeTools;
diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.ts
index d87ea577fe..b9a7e84479 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts
@@ -14,3 +14,5 @@ export { taskTools } from './task-tools.js';
export { sessionTools } from './session-tools.js';
export { hiveMindTools } from './hive-mind-tools.js';
export { workflowTools } from './workflow-tools.js';
+export { coverageRouterTools } from '../ruvector/coverage-tools.js';
+export { analyzeTools } from './analyze-tools.js';
diff --git a/v3/@claude-flow/cli/src/ruvector/README.md b/v3/@claude-flow/cli/src/ruvector/README.md
new file mode 100644
index 0000000000..737447c531
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/README.md
@@ -0,0 +1,673 @@
+# RuVector NPM Package API Documentation
+
+Version: 0.1.95
+Package: `ruvector`
+Repository: https://github.com/ruvnet/ruvector
+
+## Overview
+
+RuVector is a high-performance vector database for Node.js with automatic native/WASM fallback. It provides self-learning intelligence for Claude Code with Q-learning optimization, vector memory, and automatic agent routing.
+
+## Installation
+
+```bash
+npm install ruvector
+```
+
+## MCP Server Integration
+
+Add to Claude Code:
+
+```bash
+claude mcp add ruvector-mcp -- npx ruvector mcp-server
+```
+
+---
+
+## Hooks API Reference
+
+The hooks API provides 30+ MCP tools for intelligent agent routing, code analysis, and self-learning capabilities.
+
+### Core Routing Functions
+
+#### `hooks_route`
+
+Routes a task to the best agent based on learned patterns.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `task` | string | Yes | Task description to route |
+| `file` | string | No | File path for context-aware routing |
+
+**Return Type:**
+```typescript
+interface RouteResult {
+ success: boolean;
+ task: string;
+ file?: string;
+ agent: string; // Recommended agent (e.g., "typescript-developer")
+ confidence: number; // Confidence score 0.0-1.0
+ reason: string; // Explanation for routing decision
+ alternates?: string[]; // Alternative agent suggestions
+ sonaPatterns?: number; // Number of SONA patterns used (if engine enabled)
+ engineRouted?: boolean; // Whether full engine was used
+}
+```
+
+**Example Usage:**
+```javascript
+// MCP Tool Call
+const result = await mcp.call('hooks_route', {
+ task: 'implement user authentication',
+ file: 'src/auth/login.ts'
+});
+
+// CLI Usage
+npx ruvector hooks route "implement user login"
+```
+
+**Error Handling:**
+- Returns default agent mapping if no patterns learned
+- Falls back to file extension-based routing if task unclear
+
+---
+
+#### `hooks_route_enhanced`
+
+Enhanced routing using AST complexity, coverage, and diff analysis signals.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `task` | string | Yes | Task description |
+| `file` | string | No | File context for analysis |
+
+**Return Type:**
+```typescript
+interface EnhancedRouteResult {
+ success: boolean;
+ agent: string;
+ confidence: number;
+ signals: {
+ complexity?: number; // Cyclomatic complexity
+ coverage?: number; // Test coverage percentage
+ riskScore?: number; // Change risk assessment
+ diffCategory?: string; // feature/bugfix/refactor
+ };
+ explanation: string;
+}
+```
+
+**Example Usage:**
+```javascript
+const result = await mcp.call('hooks_route_enhanced', {
+ task: 'refactor authentication module',
+ file: 'src/auth/handlers.ts'
+});
+```
+
+---
+
+### AST Analysis Functions
+
+#### `hooks_ast_analyze`
+
+Parses file AST and extracts symbols, imports, and complexity metrics.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `file` | string | Yes | File path to analyze |
+
+**Return Type:**
+```typescript
+interface FileAnalysis {
+ file: string;
+ language: string; // TypeScript, JavaScript, Python, etc.
+ imports: ImportInfo[]; // Import statements
+ exports: ExportInfo[]; // Export statements
+ functions: FunctionInfo[]; // Function definitions
+ classes: ClassInfo[]; // Class definitions
+ variables: string[]; // Variable declarations
+ types: string[]; // Type definitions
+ complexity: number; // Overall complexity score
+ lines: number; // Total lines
+ parseTime: number; // Parse duration in ms
+}
+
+interface FunctionInfo {
+ name: string;
+ params: string[];
+ returnType?: string;
+ async: boolean;
+ exported: boolean;
+ startLine: number;
+ endLine: number;
+ complexity: number;
+ calls: string[]; // Functions called within
+}
+
+interface ClassInfo {
+ name: string;
+ extends?: string;
+ implements: string[];
+ methods: FunctionInfo[];
+ properties: string[];
+ exported: boolean;
+ startLine: number;
+ endLine: number;
+}
+
+interface ImportInfo {
+ source: string;
+ default?: string;
+ named: string[];
+ namespace?: string;
+ type: 'esm' | 'commonjs' | 'dynamic';
+}
+```
+
+**Example Usage:**
+```javascript
+const analysis = await mcp.call('hooks_ast_analyze', {
+ file: 'src/api/routes.ts'
+});
+
+// CLI Usage
+npx ruvector hooks ast-analyze src/api/routes.ts --json
+```
+
+**Error Handling:**
+- Returns `{ success: false, error: message }` if file not found
+- Falls back to regex-based analysis if tree-sitter unavailable
+
+---
+
+#### `hooks_ast_complexity`
+
+Calculates cyclomatic and cognitive complexity metrics for files.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `files` | string[] | Yes | Array of file paths to analyze |
+| `threshold` | number | No | Warn if complexity exceeds (default: 10) |
+
+**Return Type:**
+```typescript
+interface ComplexityResult {
+ success: boolean;
+ files: Array<{
+ file: string;
+ complexity: number;
+ functions: Array<{
+ name: string;
+ complexity: number;
+ exceeds: boolean;
+ }>;
+ }>;
+ warnings: string[];
+ averageComplexity: number;
+}
+```
+
+**Example Usage:**
+```javascript
+const result = await mcp.call('hooks_ast_complexity', {
+ files: ['src/auth/*.ts'],
+ threshold: 15
+});
+```
+
+---
+
+### Diff Analysis Functions
+
+#### `hooks_diff_analyze`
+
+Analyzes git diff with semantic embeddings and risk scoring.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `commit` | string | No | Commit hash (defaults to staged changes) |
+
+**Return Type:**
+```typescript
+interface CommitAnalysis {
+ hash: string;
+ message: string;
+ author: string;
+ date: string;
+ files: DiffAnalysis[];
+ totalAdditions: number;
+ totalDeletions: number;
+ riskScore: number; // 0.0-1.0 risk assessment
+ embedding?: number[]; // Semantic embedding
+}
+
+interface DiffAnalysis {
+ file: string;
+ hunks: DiffHunk[];
+ totalAdditions: number;
+ totalDeletions: number;
+ complexity: number;
+ riskScore: number;
+ category: 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'config' | 'unknown';
+ embedding?: number[];
+}
+
+interface DiffHunk {
+ file: string;
+ oldStart: number;
+ oldLines: number;
+ newStart: number;
+ newLines: number;
+ content: string;
+ additions: string[];
+ deletions: string[];
+}
+```
+
+**Example Usage:**
+```javascript
+// Analyze staged changes
+const staged = await mcp.call('hooks_diff_analyze', {});
+
+// Analyze specific commit
+const commit = await mcp.call('hooks_diff_analyze', {
+ commit: 'abc123'
+});
+
+// CLI Usage
+npx ruvector hooks diff-analyze --json
+npx ruvector hooks diff-analyze abc123 --json
+```
+
+**Error Handling:**
+- Returns empty analysis if no changes found
+- Handles merge commits and binary files gracefully
+
+---
+
+#### `hooks_diff_classify`
+
+Classifies change type based on diff patterns.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `commit` | string | No | Commit hash (defaults to HEAD) |
+
+**Return Type:**
+```typescript
+interface ClassifyResult {
+ success: boolean;
+ category: 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'config' | 'unknown';
+ confidence: number;
+ indicators: string[]; // Patterns that led to classification
+}
+```
+
+**Example Usage:**
+```javascript
+const classification = await mcp.call('hooks_diff_classify', {
+ commit: 'HEAD~1'
+});
+```
+
+---
+
+### Coverage Analysis Functions
+
+#### `hooks_coverage_route`
+
+Gets coverage-aware agent routing for a file.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `file` | string | Yes | File to analyze |
+
+**Return Type:**
+```typescript
+interface CoverageRouteResult {
+ success: boolean;
+ file: string;
+ route: boolean; // Whether to route to tester
+ reason: string; // Explanation
+ coverage: number; // Coverage percentage (0-100)
+ weights: {
+ coder: number; // Weight for coder agent
+ tester: number; // Weight for tester agent
+ reviewer: number; // Weight for reviewer agent
+ };
+}
+```
+
+**Example Usage:**
+```javascript
+const routing = await mcp.call('hooks_coverage_route', {
+ file: 'src/services/auth.ts'
+});
+
+// CLI Usage
+npx ruvector hooks coverage-route src/services/auth.ts
+```
+
+**Error Handling:**
+- Returns default weights if no coverage report found
+- Searches common locations: coverage/, .nyc_output/, lcov.info
+
+---
+
+#### `hooks_coverage_suggest`
+
+Suggests tests for files based on coverage data.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `files` | string[] | Yes | Files to analyze |
+
+**Return Type:**
+```typescript
+interface TestSuggestion {
+ file: string;
+ testFile: string; // Suggested test file path
+ reason: string;
+ priority: 'high' | 'medium' | 'low';
+ coverage: number; // Current coverage %
+ uncoveredFunctions: string[];
+}
+
+interface SuggestResult {
+ success: boolean;
+ suggestions: TestSuggestion[];
+ overall: {
+ lines: number;
+ functions: number;
+ branches: number;
+ };
+}
+```
+
+**Example Usage:**
+```javascript
+const suggestions = await mcp.call('hooks_coverage_suggest', {
+ files: ['src/api/*.ts', 'src/services/*.ts']
+});
+```
+
+---
+
+### Graph Analysis Functions
+
+#### `hooks_graph_mincut`
+
+Finds optimal code boundaries using MinCut algorithm (Stoer-Wagner).
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `files` | string[] | Yes | Files to analyze for module boundaries |
+
+**Return Type:**
+```typescript
+interface Partition {
+ groups: string[][]; // Two groups of files
+ cutWeight: number; // Weight of edges between groups
+ modularity: number; // Modularity score
+}
+
+interface MinCutResult {
+ success: boolean;
+ partition: Partition;
+ bridges: Array<{ // Critical connections
+ from: string;
+ to: string;
+ }>;
+ articulationPoints: string[]; // Critical nodes
+}
+```
+
+**Example Usage:**
+```javascript
+const boundaries = await mcp.call('hooks_graph_mincut', {
+ files: ['src/**/*.ts']
+});
+
+// CLI Usage
+npx ruvector hooks graph-mincut src/**/*.ts
+```
+
+**Error Handling:**
+- Requires at least 2 connected files
+- Returns empty partition for disconnected graphs
+
+---
+
+#### `hooks_graph_cluster`
+
+Detects code communities using spectral or Louvain clustering.
+
+**Input Parameters:**
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `files` | string[] | Yes | Files to analyze |
+| `method` | string | No | 'spectral' or 'louvain' (default: 'louvain') |
+| `clusters` | number | No | Number of clusters for spectral (default: 3) |
+
+**Return Type:**
+```typescript
+interface ClusterResult {
+ success: boolean;
+ method: string;
+ clusters: Map<string, number>; // file -> cluster ID
+ numClusters: number;
+ modularity: number;
+ // For spectral method only:
+ eigenvalues?: number[];
+ coordinates?: Map<string, number[]>;
+}
+```
+
+**Example Usage:**
+```javascript
+// Louvain community detection (automatic cluster count)
+const louvain = await mcp.call('hooks_graph_cluster', {
+ files: ['src/**/*.ts'],
+ method: 'louvain'
+});
+
+// Spectral clustering (specify cluster count)
+const spectral = await mcp.call('hooks_graph_cluster', {
+ files: ['src/**/*.ts'],
+ method: 'spectral',
+ clusters: 5
+});
+
+// CLI Usage
+npx ruvector hooks graph-cluster src/**/*.ts --method louvain
+npx ruvector hooks graph-cluster src/**/*.ts --method spectral --clusters 5
+```
+
+---
+
+## Additional MCP Tools
+
+### Memory Functions
+
+| Tool | Description |
+|------|-------------|
+| `hooks_remember` | Store context in vector memory |
+| `hooks_recall` | Search vector memory for relevant context |
+
+### Learning Functions
+
+| Tool | Description |
+|------|-------------|
+| `hooks_learn` | Combined learning: record experience and get recommendation |
+| `hooks_batch_learn` | Record multiple experiences in batch |
+| `hooks_learning_config` | Configure learning algorithms (9 algorithms available) |
+| `hooks_learning_stats` | Get learning statistics |
+
+### Trajectory Functions
+
+| Tool | Description |
+|------|-------------|
+| `hooks_trajectory_begin` | Begin tracking execution trajectory |
+| `hooks_trajectory_step` | Add step to current trajectory |
+| `hooks_trajectory_end` | End trajectory with quality score |
+
+### Security Functions
+
+| Tool | Description |
+|------|-------------|
+| `hooks_security_scan` | Parallel vulnerability pattern detection |
+
+### Neural Functions
+
+| Tool | Description |
+|------|-------------|
+| `hooks_attention_info` | Get available attention mechanisms |
+| `hooks_gnn_info` | Get GNN layer capabilities |
+| `hooks_rag_context` | RAG-enhanced context retrieval |
+
+---
+
+## Programmatic API
+
+### VectorDB
+
+```typescript
+import { VectorDb } from 'ruvector';
+
+const db = new VectorDb({
+ dimensions: 384, // Must match embedding model
+ maxElements: 10000,
+ storagePath: './vectors.db'
+});
+
+// Insert
+await db.insert({
+ id: 'doc1',
+ vector: new Float32Array(384),
+ metadata: { title: 'Document 1' }
+});
+
+// Search
+const results = await db.search({
+ vector: queryVector,
+ k: 5,
+ threshold: 0.7
+});
+
+// Get
+const doc = await db.get('doc1');
+
+// Delete
+await db.delete('doc1');
+```
+
+### Core Modules
+
+```typescript
+// AST Parser
+import { getCodeParser } from 'ruvector/dist/core/ast-parser';
+const parser = getCodeParser();
+await parser.init();
+const analysis = await parser.analyze('file.ts');
+
+// Diff Embeddings
+import diffEmbeddings from 'ruvector/dist/core/diff-embeddings';
+const commit = await diffEmbeddings.analyzeCommit('HEAD');
+const similar = await diffEmbeddings.findSimilarCommits(diff, 50, 5);
+
+// Coverage Router
+import coverage from 'ruvector/dist/core/coverage-router';
+const data = coverage.getFileCoverage('file.ts');
+const tests = coverage.suggestTests(['file.ts']);
+
+// Graph Algorithms
+import graph from 'ruvector/dist/core/graph-algorithms';
+const g = graph.buildGraph(nodes, edges);
+const partition = graph.minCut(g);
+const clusters = graph.louvainCommunities(g);
+```
+
+---
+
+## Performance Characteristics
+
+| Operation | Latency | Notes |
+|-----------|---------|-------|
+| ONNX inference | ~400ms | Initial embedding |
+| HNSW search | ~0.045ms | 8,800x faster than inference |
+| Memory cache | ~0.01ms | 40,000x speedup |
+| Native Rust | <0.5ms | p50 latency |
+| WASM fallback | 10-50ms | Universal compatibility |
+
+---
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `RUVECTOR_INTELLIGENCE_ENABLED` | `true` | Enable/disable intelligence |
+| `RUVECTOR_LEARNING_RATE` | `0.1` | Q-learning rate (0.0-1.0) |
+| `RUVECTOR_MEMORY_BACKEND` | `rvlite` | Memory storage backend |
+| `INTELLIGENCE_MODE` | `treatment` | A/B testing mode |
+
+---
+
+## CLI Commands
+
+```bash
+# Initialize hooks
+npx ruvector hooks init --pretrain --build-agents quality
+
+# Verify setup
+npx ruvector hooks verify
+npx ruvector hooks doctor --fix
+
+# Analysis
+npx ruvector hooks ast-analyze <file> --json
+npx ruvector hooks ast-complexity <files> --threshold 10
+npx ruvector hooks diff-analyze [commit] --json
+npx ruvector hooks diff-classify [commit]
+npx ruvector hooks coverage-route <file>
+npx ruvector hooks coverage-suggest <files>
+npx ruvector hooks graph-mincut <files>
+npx ruvector hooks graph-cluster <files> --method louvain
+
+# Memory
+npx ruvector hooks remember "context" -t project
+npx ruvector hooks recall "query"
+npx ruvector hooks route "task description"
+
+# Stats and export
+npx ruvector hooks stats
+npx ruvector hooks export -o backup.json
+npx ruvector hooks import backup.json --merge
+```
+
+---
+
+## Dependencies
+
+- `@modelcontextprotocol/sdk`: ^1.0.0
+- `@ruvector/attention`: ^0.1.3
+- `@ruvector/core`: ^0.1.25
+- `@ruvector/gnn`: ^0.1.22
+- `@ruvector/sona`: ^0.1.4
+- `@xenova/transformers`: ^2.17.2
+
+---
+
+## Links
+
+- [npm Package](https://www.npmjs.com/package/ruvector)
+- [GitHub Repository](https://github.com/ruvnet/ruvector)
+- [Hooks Documentation](https://github.com/ruvnet/ruvector/blob/main/npm/packages/ruvector/HOOKS.md)
diff --git a/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts
new file mode 100644
index 0000000000..8cbc76f7d5
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts
@@ -0,0 +1,608 @@
+/**
+ * AST Analyzer - Wrapper for ruvector's AST parsing capabilities
+ *
+ * Provides code analysis features:
+ * - Symbol extraction (functions, classes, variables)
+ * - Cyclomatic complexity scoring
+ * - Code structure analysis
+ * - Graceful fallback when ruvector not installed
+ *
+ * Created with ruv.io
+ */
+
+import * as fs from 'fs/promises';
+import * as path from 'path';
+
+// Type definitions matching ruvector's API
+export interface FunctionInfo {
+ name: string;
+ params: string[];
+ returnType?: string;
+ async: boolean;
+ exported: boolean;
+ startLine: number;
+ endLine: number;
+ complexity: number;
+ calls: string[];
+}
+
+export interface ClassInfo {
+ name: string;
+ extends?: string;
+ implements: string[];
+ methods: FunctionInfo[];
+ properties: string[];
+ exported: boolean;
+ startLine: number;
+ endLine: number;
+}
+
+export interface ImportInfo {
+ source: string;
+ default?: string;
+ named: string[];
+ namespace?: string;
+ type: 'esm' | 'commonjs' | 'dynamic';
+}
+
+export interface ExportInfo {
+ name: string;
+ type: 'default' | 'named' | 'all';
+ source?: string;
+}
+
+export interface FileAnalysis {
+ file: string;
+ language: string;
+ imports: ImportInfo[];
+ exports: ExportInfo[];
+ functions: FunctionInfo[];
+ classes: ClassInfo[];
+ variables: string[];
+ types: string[];
+ complexity: number;
+ lines: number;
+ parseTime: number;
+}
+
+export interface ComplexityResult {
+ file: string;
+ lines: number;
+ nonEmptyLines: number;
+ cyclomaticComplexity: number;
+ functions: number;
+ avgFunctionSize: number;
+ maxFunctionComplexity?: number;
+}
+
+export interface ASTAnalyzerOptions {
+ includeComplexity?: boolean;
+ recursive?: boolean;
+ extensions?: string[];
+ maxFiles?: number;
+}
+
+// Check if ruvector is available
+let ruvectorModule: any = null;
+let ruvectorAvailable = false;
+
+async function loadRuvector(): Promise<boolean> {
+ if (ruvectorModule !== null) {
+ return ruvectorAvailable;
+ }
+
+ try {
+ ruvectorModule = await import('ruvector');
+ ruvectorAvailable = true;
+ return true;
+ } catch {
+ ruvectorModule = {};
+ ruvectorAvailable = false;
+ return false;
+ }
+}
+
+/**
+ * Check if ruvector is available
+ */
+export async function isRuvectorAvailable(): Promise<boolean> {
+ return loadRuvector();
+}
+
+/**
+ * Get complexity rating from score
+ */
+export function getComplexityRating(complexity: number): 'low' | 'medium' | 'high' | 'critical' {
+ if (complexity <= 10) return 'low';
+ if (complexity <= 20) return 'medium';
+ if (complexity <= 30) return 'high';
+ return 'critical';
+}
+
+/**
+ * Detect language from file extension
+ */
+export function detectLanguage(file: string): string {
+ const ext = path.extname(file).toLowerCase();
+ const languageMap: Record<string, string> = {
+ '.ts': 'typescript',
+ '.tsx': 'typescript',
+ '.js': 'javascript',
+ '.jsx': 'javascript',
+ '.mjs': 'javascript',
+ '.cjs': 'javascript',
+ '.py': 'python',
+ '.rs': 'rust',
+ '.go': 'go',
+ '.java': 'java',
+ '.c': 'c',
+ '.cpp': 'cpp',
+ '.h': 'c',
+ '.hpp': 'cpp',
+ };
+ return languageMap[ext] || 'unknown';
+}
+
+/**
+ * Analyze a single file using ruvector's AST parser
+ */
+export async function analyzeFile(
+ filePath: string,
+ options: ASTAnalyzerOptions = {}
+): Promise<FileAnalysis | null> {
+ const available = await loadRuvector();
+
+ if (available && ruvectorModule.CodeParser) {
+ try {
+ const parser = ruvectorModule.getCodeParser?.() ?? new ruvectorModule.CodeParser();
+ await parser.init();
+ return await parser.analyze(filePath);
+ } catch (error) {
+ // Fall through to fallback
+ }
+ }
+
+ // Fallback: regex-based analysis
+ return await analyzeFileWithFallback(filePath);
+}
+
+/**
+ * Analyze complexity of a single file
+ */
+export async function analyzeComplexity(
+ filePath: string
+): Promise<ComplexityResult | null> {
+ const available = await loadRuvector();
+
+ if (available && ruvectorModule.analyzeFile) {
+ try {
+ return ruvectorModule.analyzeFile(filePath);
+ } catch {
+ // Fall through to fallback
+ }
+ }
+
+ // Fallback: simple complexity analysis
+ return await analyzeComplexityWithFallback(filePath);
+}
+
+/**
+ * Analyze multiple files
+ */
+export async function analyzeFiles(
+ files: string[],
+ options: ASTAnalyzerOptions = {}
+): Promise<FileAnalysis[]> {
+ const maxFiles = options.maxFiles ?? 100;
+ const filesToAnalyze = files.slice(0, maxFiles);
+ const results: FileAnalysis[] = [];
+
+ for (const file of filesToAnalyze) {
+ try {
+ const result = await analyzeFile(file, options);
+ if (result) {
+ results.push(result);
+ }
+ } catch {
+ // Skip files that fail to analyze
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Analyze complexity for multiple files
+ */
+export async function analyzeFilesComplexity(
+ files: string[],
+ options: ASTAnalyzerOptions = {}
+): Promise<ComplexityResult[]> {
+ const maxFiles = options.maxFiles ?? 100;
+ const filesToAnalyze = files.slice(0, maxFiles);
+ const results: ComplexityResult[] = [];
+
+ for (const file of filesToAnalyze) {
+ try {
+ const result = await analyzeComplexity(file);
+ if (result) {
+ results.push(result);
+ }
+ } catch {
+ // Skip files that fail to analyze
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Get all symbols from a file
+ */
+export async function getSymbols(filePath: string): Promise<string[]> {
+ const available = await loadRuvector();
+
+ if (available && ruvectorModule.CodeParser) {
+ try {
+ const parser = ruvectorModule.getCodeParser?.() ?? new ruvectorModule.CodeParser();
+ await parser.init();
+ return await parser.getSymbols(filePath);
+ } catch {
+ // Fall through to fallback
+ }
+ }
+
+ // Fallback: extract symbols with regex
+ const analysis = await analyzeFileWithFallback(filePath);
+ if (!analysis) return [];
+
+ return [
+ ...analysis.functions.map(f => f.name),
+ ...analysis.classes.map(c => c.name),
+ ...analysis.variables,
+ ...analysis.types,
+ ];
+}
+
+/**
+ * Scan directory for analyzable files
+ */
+export async function scanDirectory(
+ dirPath: string,
+ options: ASTAnalyzerOptions = {}
+): Promise<string[]> {
+ const extensions = options.extensions ?? ['.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go'];
+ const files: string[] = [];
+
+ async function scan(dir: string, depth: number = 0): Promise<void> {
+ if (depth > 10) return; // Max depth protection
+
+ try {
+ const entries = await fs.readdir(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+
+ // Skip common directories
+ if (entry.isDirectory()) {
+ if (!['node_modules', '.git', 'dist', 'build', '.next', '__pycache__'].includes(entry.name)) {
+ if (options.recursive !== false) {
+ await scan(fullPath, depth + 1);
+ }
+ }
+ } else if (entry.isFile()) {
+ const ext = path.extname(entry.name).toLowerCase();
+ if (extensions.includes(ext)) {
+ files.push(fullPath);
+ }
+ }
+ }
+ } catch {
+ // Skip inaccessible directories
+ }
+ }
+
+ await scan(dirPath);
+ return files;
+}
+
+// ============================================
+// Fallback Implementations
+// ============================================
+
+/**
+ * Fallback file analysis using regex
+ */
+async function analyzeFileWithFallback(filePath: string): Promise<FileAnalysis | null> {
+ const startTime = Date.now();
+
+ try {
+ const content = await fs.readFile(filePath, 'utf-8');
+ const lines = content.split('\n');
+ const language = detectLanguage(filePath);
+
+ const analysis: FileAnalysis = {
+ file: filePath,
+ language,
+ imports: extractImports(content, language),
+ exports: extractExports(content, language),
+ functions: extractFunctions(content, language),
+ classes: extractClasses(content, language),
+ variables: extractVariables(content, language),
+ types: extractTypes(content, language),
+ complexity: calculateComplexity(content),
+ lines: lines.length,
+ parseTime: Date.now() - startTime,
+ };
+
+ return analysis;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fallback complexity analysis
+ */
+async function analyzeComplexityWithFallback(filePath: string): Promise<ComplexityResult | null> {
+ try {
+ const content = await fs.readFile(filePath, 'utf-8');
+ const lines = content.split('\n');
+ const nonEmptyLines = lines.filter(l => l.trim().length > 0).length;
+
+ const functionMatches = content.match(/function\s+\w+|(?:async\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\(/g);
+ const functions = functionMatches?.length ?? 0;
+
+ return {
+ file: filePath,
+ lines: lines.length,
+ nonEmptyLines,
+ cyclomaticComplexity: calculateComplexity(content),
+ functions,
+ avgFunctionSize: functions > 0 ? Math.round(nonEmptyLines / functions) : nonEmptyLines,
+ maxFunctionComplexity: undefined, // Not available in fallback
+ };
+ } catch {
+ return null;
+ }
+}
+
+function extractImports(content: string, language: string): ImportInfo[] {
+ const imports: ImportInfo[] = [];
+
+ if (language === 'typescript' || language === 'javascript') {
+ // ES imports
+ const esmRegex = /import\s+(?:(?:(\w+)\s*,?\s*)?(?:\{([^}]+)\})?(?:\*\s+as\s+(\w+))?\s+from\s+)?['"]([^'"]+)['"]/g;
+ let match;
+ while ((match = esmRegex.exec(content)) !== null) {
+ imports.push({
+ source: match[4],
+ default: match[1],
+ named: match[2] ? match[2].split(',').map(s => s.trim().split(/\s+as\s+/)[0]) : [],
+ namespace: match[3],
+ type: 'esm',
+ });
+ }
+
+ // CommonJS require
+ const cjsRegex = /(?:const|let|var)\s+(?:(\w+)|(\{[^}]+\}))\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
+ while ((match = cjsRegex.exec(content)) !== null) {
+ imports.push({
+ source: match[3],
+ default: match[1],
+ named: match[2] ? match[2].replace(/[{}]/g, '').split(',').map(s => s.trim()) : [],
+ type: 'commonjs',
+ });
+ }
+ } else if (language === 'python') {
+ // Python imports
+ const pyImportRegex = /(?:from\s+(\S+)\s+)?import\s+([^#\n]+)/g;
+ let match;
+ while ((match = pyImportRegex.exec(content)) !== null) {
+ imports.push({
+ source: match[1] || match[2].split(',')[0].trim(),
+ named: match[2].split(',').map(s => s.trim().split(/\s+as\s+/)[0]),
+ type: 'esm',
+ });
+ }
+ }
+
+ return imports;
+}
+
+function extractExports(content: string, language: string): ExportInfo[] {
+ const exports: ExportInfo[] = [];
+
+ if (language === 'typescript' || language === 'javascript') {
+ // Export default
+ const defaultRegex = /export\s+default\s+(?:class|function|const|let|var)?\s*(\w+)?/g;
+ let match;
+ while ((match = defaultRegex.exec(content)) !== null) {
+ exports.push({ name: match[1] || 'default', type: 'default' });
+ }
+
+ // Named exports
+ const namedRegex = /export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;
+ while ((match = namedRegex.exec(content)) !== null) {
+ exports.push({ name: match[1], type: 'named' });
+ }
+
+ // Export all
+ const allRegex = /export\s*\*\s*from\s*['"]([^'"]+)['"]/g;
+ while ((match = allRegex.exec(content)) !== null) {
+ exports.push({ name: '*', type: 'all', source: match[1] });
+ }
+ }
+
+ return exports;
+}
+
+function extractFunctions(content: string, language: string): FunctionInfo[] {
+ const functions: FunctionInfo[] = [];
+ const lines = content.split('\n');
+
+ if (language === 'typescript' || language === 'javascript') {
+ // Function declarations and expressions
+ const funcRegex = /(?:export\s+)?(async\s+)?(?:function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>|\w+\s*=>))/g;
+ let match;
+ while ((match = funcRegex.exec(content)) !== null) {
+ const name = match[2] || match[3];
+ if (name) {
+ const lineNum = content.substring(0, match.index).split('\n').length;
+ functions.push({
+ name,
+ params: [],
+ async: !!match[1],
+ exported: content.substring(Math.max(0, match.index - 10), match.index).includes('export'),
+ startLine: lineNum,
+ endLine: lineNum + 10, // Approximate
+ complexity: 1,
+ calls: [],
+ });
+ }
+ }
+ } else if (language === 'python') {
+ const pyFuncRegex = /(async\s+)?def\s+(\w+)\s*\(/g;
+ let match;
+ while ((match = pyFuncRegex.exec(content)) !== null) {
+ const lineNum = content.substring(0, match.index).split('\n').length;
+ functions.push({
+ name: match[2],
+ params: [],
+ async: !!match[1],
+ exported: true,
+ startLine: lineNum,
+ endLine: lineNum + 10,
+ complexity: 1,
+ calls: [],
+ });
+ }
+ }
+
+ return functions;
+}
+
+function extractClasses(content: string, language: string): ClassInfo[] {
+ const classes: ClassInfo[] = [];
+
+ if (language === 'typescript' || language === 'javascript') {
+ const classRegex = /(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{]+))?/g;
+ let match;
+ while ((match = classRegex.exec(content)) !== null) {
+ const lineNum = content.substring(0, match.index).split('\n').length;
+ classes.push({
+ name: match[1],
+ extends: match[2],
+ implements: match[3] ? match[3].split(',').map(s => s.trim()) : [],
+ methods: [],
+ properties: [],
+ exported: content.substring(Math.max(0, match.index - 10), match.index).includes('export'),
+ startLine: lineNum,
+ endLine: lineNum + 20,
+ });
+ }
+ } else if (language === 'python') {
+ const pyClassRegex = /class\s+(\w+)(?:\s*\(([^)]*)\))?/g;
+ let match;
+ while ((match = pyClassRegex.exec(content)) !== null) {
+ const lineNum = content.substring(0, match.index).split('\n').length;
+ classes.push({
+ name: match[1],
+ extends: match[2]?.split(',')[0]?.trim(),
+ implements: [],
+ methods: [],
+ properties: [],
+ exported: true,
+ startLine: lineNum,
+ endLine: lineNum + 20,
+ });
+ }
+ }
+
+ return classes;
+}
+
+function extractVariables(content: string, language: string): string[] {
+ const variables: string[] = [];
+
+ if (language === 'typescript' || language === 'javascript') {
+ // Top-level const/let/var (not in functions)
+ const varRegex = /^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*[=:]/gm;
+ let match;
+ while ((match = varRegex.exec(content)) !== null) {
+ // Skip if it looks like a function
+ const afterMatch = content.substring(match.index, match.index + 200);
+ if (!afterMatch.includes('=>') && !afterMatch.includes('function')) {
+ variables.push(match[1]);
+ }
+ }
+ }
+
+ return variables;
+}
+
+function extractTypes(content: string, language: string): string[] {
+ const types: string[] = [];
+
+ if (language === 'typescript') {
+ // Interfaces
+ const interfaceRegex = /(?:export\s+)?interface\s+(\w+)/g;
+ let match;
+ while ((match = interfaceRegex.exec(content)) !== null) {
+ types.push(match[1]);
+ }
+
+ // Type aliases
+ const typeRegex = /(?:export\s+)?type\s+(\w+)\s*[=<]/g;
+ while ((match = typeRegex.exec(content)) !== null) {
+ types.push(match[1]);
+ }
+
+ // Enums
+ const enumRegex = /(?:export\s+)?(?:const\s+)?enum\s+(\w+)/g;
+ while ((match = enumRegex.exec(content)) !== null) {
+ types.push(match[1]);
+ }
+ }
+
+ return types;
+}
+
+function calculateComplexity(content: string): number {
+ // Simple cyclomatic complexity calculation
+ const conditions = [
+ /\bif\s*\(/g,
+ /\belse\s+if\s*\(/g,
+ /\bfor\s*\(/g,
+ /\bwhile\s*\(/g,
+ /\bcase\s+/g,
+ /\bcatch\s*\(/g,
+ /\?\s*[^:]/g, // Ternary
+ /&&/g,
+ /\|\|/g,
+ /\?\?/g, // Nullish coalescing
+ ];
+
+ let complexity = 1; // Base complexity
+
+ for (const pattern of conditions) {
+ const matches = content.match(pattern);
+ if (matches) {
+ complexity += matches.length;
+ }
+ }
+
+ return complexity;
+}
+
+export default {
+ isRuvectorAvailable,
+ analyzeFile,
+ analyzeFiles,
+ analyzeComplexity,
+ analyzeFilesComplexity,
+ getSymbols,
+ scanDirectory,
+ getComplexityRating,
+ detectLanguage,
+};
diff --git a/v3/@claude-flow/cli/src/ruvector/coverage-router.ts b/v3/@claude-flow/cli/src/ruvector/coverage-router.ts
new file mode 100644
index 0000000000..e4a2350a3d
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/coverage-router.ts
@@ -0,0 +1,985 @@
+/**
+ * Coverage-Aware Routing for @claude-flow/cli
+ *
+ * Integrates with ruvector's hooks_coverage_route and hooks_coverage_suggest
+ * to route tasks to agents based on test coverage gaps.
+ *
+ * Supports coverage formats:
+ * - lcov (lcov.info)
+ * - istanbul (coverage-summary.json, coverage-final.json)
+ * - c8 (coverage/coverage-summary.json)
+ */
+
+import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
+import { join, resolve, relative, dirname, basename, extname } from 'path';
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export interface CoverageData {
+ /** File path relative to project root */
+ filePath: string;
+ /** Line coverage percentage (0-100) */
+ lineCoverage: number;
+ /** Branch coverage percentage (0-100) */
+ branchCoverage: number;
+ /** Function coverage percentage (0-100) */
+ functionCoverage: number;
+ /** Statement coverage percentage (0-100) */
+ statementCoverage: number;
+ /** Uncovered line numbers */
+ uncoveredLines: number[];
+ /** Uncovered branch locations */
+ uncoveredBranches: UncoveredBranch[];
+ /** Uncovered function names */
+ uncoveredFunctions: string[];
+ /** Total lines in file */
+ totalLines: number;
+ /** Lines that are covered */
+ coveredLines: number;
+}
+
+export interface UncoveredBranch {
+ line: number;
+ column?: number;
+ type: 'if' | 'else' | 'case' | 'ternary' | 'logical' | 'unknown';
+}
+
+export interface CoverageSummary {
+ totalFiles: number;
+ overallLineCoverage: number;
+ overallBranchCoverage: number;
+ overallFunctionCoverage: number;
+ overallStatementCoverage: number;
+ filesBelowThreshold: number;
+ coverageThreshold: number;
+}
+
+export interface CoverageGap {
+ filePath: string;
+ coveragePercent: number;
+ gapType: 'critical' | 'high' | 'medium' | 'low';
+ complexity: number;
+ priority: number;
+ suggestedAgents: string[];
+ uncoveredLines: number[];
+ reason: string;
+}
+
+export interface CoverageRouteResult {
+ success: boolean;
+ task: string;
+ coverageAware: boolean;
+ gaps: CoverageGap[];
+ routing: {
+ primaryAgent: string;
+ confidence: number;
+ reason: string;
+ coverageImpact: string;
+ };
+ suggestions: string[];
+ metrics: {
+ filesAnalyzed: number;
+ totalGaps: number;
+ criticalGaps: number;
+ avgCoverage: number;
+ };
+}
+
+export interface CoverageSuggestResult {
+ success: boolean;
+ path: string;
+ suggestions: CoverageGap[];
+ summary: CoverageSummary;
+ prioritizedFiles: string[];
+ ruvectorAvailable: boolean;
+}
+
+export interface CoverageGapsResult {
+ success: boolean;
+ gaps: CoverageGap[];
+ summary: CoverageSummary;
+ agentAssignments: Record<string, string[]>;
+ ruvectorAvailable: boolean;
+}
+
+// ============================================================================
+// RuVector Integration (Graceful Fallback)
+// ============================================================================
+
+let ruvectorAvailable: boolean | null = null;
+
+interface RuVectorModule {
+ hooks_coverage_route?: (task: string, coverageData: CoverageData[]) => Promise<unknown>;
+ hooks_coverage_suggest?: (path: string, coverageData: CoverageData[]) => Promise<unknown>;
+}
+
+/**
+ * Check if ruvector is available
+ */
+async function checkRuvectorAvailable(): Promise<boolean> {
+ if (ruvectorAvailable !== null) {
+ return ruvectorAvailable;
+ }
+
+ try {
+ // Try to dynamically import ruvector
+ const ruvector = await import('ruvector').catch(() => null) as RuVectorModule | null;
+ ruvectorAvailable = ruvector !== null &&
+ typeof ruvector.hooks_coverage_route === 'function' &&
+ typeof ruvector.hooks_coverage_suggest === 'function';
+ } catch {
+ ruvectorAvailable = false;
+ }
+
+ return ruvectorAvailable;
+}
+
+/**
+ * Call ruvector's hooks_coverage_route if available
+ */
+async function callRuvectorRoute(
+ task: string,
+ coverageData: CoverageData[]
+): Promise<unknown | null> {
+ if (!(await checkRuvectorAvailable())) {
+ return null;
+ }
+
+ try {
+ const ruvector = await import('ruvector') as RuVectorModule;
+ if (ruvector.hooks_coverage_route) {
+ return await ruvector.hooks_coverage_route(task, coverageData);
+ }
+ } catch {
+ // Graceful fallback
+ }
+ return null;
+}
+
+/**
+ * Call ruvector's hooks_coverage_suggest if available
+ */
+async function callRuvectorSuggest(
+ path: string,
+ coverageData: CoverageData[]
+): Promise<unknown | null> {
+ if (!(await checkRuvectorAvailable())) {
+ return null;
+ }
+
+ try {
+ const ruvector = await import('ruvector') as RuVectorModule;
+ if (ruvector.hooks_coverage_suggest) {
+ return await ruvector.hooks_coverage_suggest(path, coverageData);
+ }
+ } catch {
+ // Graceful fallback
+ }
+ return null;
+}
+
+// ============================================================================
+// Coverage Report Parsing
+// ============================================================================
+
+/**
+ * Find coverage report files in project
+ */
+export function findCoverageReports(projectRoot: string): {
+ type: 'lcov' | 'istanbul' | 'c8' | 'unknown';
+ path: string;
+}[] {
+ const reports: { type: 'lcov' | 'istanbul' | 'c8' | 'unknown'; path: string }[] = [];
+ const coverageDir = join(projectRoot, 'coverage');
+
+ // Check for lcov.info
+ const lcovPaths = [
+ join(projectRoot, 'coverage', 'lcov.info'),
+ join(projectRoot, 'lcov.info'),
+ join(projectRoot, 'coverage', 'lcov-report', 'lcov.info'),
+ ];
+
+ for (const lcovPath of lcovPaths) {
+ if (existsSync(lcovPath)) {
+ reports.push({ type: 'lcov', path: lcovPath });
+ }
+ }
+
+ // Check for istanbul/c8 coverage-summary.json
+ const summaryPaths = [
+ join(coverageDir, 'coverage-summary.json'),
+ join(coverageDir, 'coverage-final.json'),
+ join(projectRoot, '.nyc_output', 'coverage-summary.json'),
+ ];
+
+ for (const summaryPath of summaryPaths) {
+ if (existsSync(summaryPath)) {
+ const type = summaryPath.includes('.nyc_output') ? 'istanbul' : 'c8';
+ reports.push({ type, path: summaryPath });
+ }
+ }
+
+ return reports;
+}
+
+/**
+ * Parse LCOV format coverage report
+ */
+export function parseLcov(lcovContent: string): CoverageData[] {
+ const files: CoverageData[] = [];
+ const records = lcovContent.split('end_of_record');
+
+ for (const record of records) {
+ if (!record.trim()) continue;
+
+ const lines = record.split('\n').map(l => l.trim()).filter(Boolean);
+ const sfLine = lines.find(l => l.startsWith('SF:'));
+ if (!sfLine) continue;
+
+ const filePath = sfLine.substring(3);
+ const data: CoverageData = {
+ filePath,
+ lineCoverage: 0,
+ branchCoverage: 0,
+ functionCoverage: 0,
+ statementCoverage: 0,
+ uncoveredLines: [],
+ uncoveredBranches: [],
+ uncoveredFunctions: [],
+ totalLines: 0,
+ coveredLines: 0,
+ };
+
+ let linesFound = 0;
+ let linesHit = 0;
+ let branchesFound = 0;
+ let branchesHit = 0;
+ let functionsFound = 0;
+ let functionsHit = 0;
+
+ for (const line of lines) {
+ // Line coverage: DA:line_number,hit_count
+ if (line.startsWith('DA:')) {
+ const [lineNum, hitCount] = line.substring(3).split(',').map(Number);
+ linesFound++;
+ if (hitCount > 0) {
+ linesHit++;
+ } else {
+ data.uncoveredLines.push(lineNum);
+ }
+ }
+
+ // Branch coverage: BRDA:line_number,block_number,branch_number,hit_count
+ if (line.startsWith('BRDA:')) {
+ const parts = line.substring(5).split(',');
+ const lineNum = parseInt(parts[0], 10);
+ const hitCount = parts[3] === '-' ? 0 : parseInt(parts[3], 10);
+ branchesFound++;
+ if (hitCount > 0) {
+ branchesHit++;
+ } else {
+ data.uncoveredBranches.push({
+ line: lineNum,
+ type: 'unknown',
+ });
+ }
+ }
+
+ // Function coverage: FNDA:hit_count,function_name
+ if (line.startsWith('FNDA:')) {
+ const [hitCount, funcName] = line.substring(5).split(',');
+ functionsFound++;
+ if (parseInt(hitCount, 10) > 0) {
+ functionsHit++;
+ } else {
+ data.uncoveredFunctions.push(funcName);
+ }
+ }
+
+ // Summary lines
+ if (line.startsWith('LF:')) {
+ data.totalLines = parseInt(line.substring(3), 10);
+ }
+ if (line.startsWith('LH:')) {
+ data.coveredLines = parseInt(line.substring(3), 10);
+ }
+ }
+
+ // Calculate percentages
+ data.lineCoverage = linesFound > 0 ? (linesHit / linesFound) * 100 : 100;
+ data.branchCoverage = branchesFound > 0 ? (branchesHit / branchesFound) * 100 : 100;
+ data.functionCoverage = functionsFound > 0 ? (functionsHit / functionsFound) * 100 : 100;
+ data.statementCoverage = data.lineCoverage; // Often equivalent in LCOV
+
+ files.push(data);
+ }
+
+ return files;
+}
+
+/**
+ * Parse Istanbul/C8 JSON format coverage report
+ */
+export function parseIstanbulJson(jsonContent: string): CoverageData[] {
+ const files: CoverageData[] = [];
+
+ try {
+ const coverage = JSON.parse(jsonContent) as Record<string, {
+ path?: string;
+ s?: Record<string, number>;
+ b?: Record<string, number[]>;
+ f?: Record<string, number>;
+ statementMap?: Record<string, { start: { line: number } }>;
+ branchMap?: Record<string, { line: number; type?: string }>;
+ fnMap?: Record<string, { name: string }>;
+ // Summary format
+ lines?: { total: number; covered: number; pct: number };
+ statements?: { total: number; covered: number; pct: number };
+ functions?: { total: number; covered: number; pct: number };
+ branches?: { total: number; covered: number; pct: number };
+ }>;
+
+ for (const [filePath, fileData] of Object.entries(coverage)) {
+ // Skip 'total' entry in summary format
+ if (filePath === 'total') continue;
+
+ const data: CoverageData = {
+ filePath: fileData.path || filePath,
+ lineCoverage: 0,
+ branchCoverage: 0,
+ functionCoverage: 0,
+ statementCoverage: 0,
+ uncoveredLines: [],
+ uncoveredBranches: [],
+ uncoveredFunctions: [],
+ totalLines: 0,
+ coveredLines: 0,
+ };
+
+ // Handle summary format
+ if (fileData.lines && typeof fileData.lines.pct === 'number') {
+ data.lineCoverage = fileData.lines.pct;
+ data.statementCoverage = fileData.statements?.pct ?? fileData.lines.pct;
+ data.branchCoverage = fileData.branches?.pct ?? 100;
+ data.functionCoverage = fileData.functions?.pct ?? 100;
+ data.totalLines = fileData.lines.total;
+ data.coveredLines = fileData.lines.covered;
+ files.push(data);
+ continue;
+ }
+
+ // Handle detailed format
+ if (fileData.s && fileData.statementMap) {
+ let statementsTotal = 0;
+ let statementsCovered = 0;
+
+ for (const [stmtId, hitCount] of Object.entries(fileData.s)) {
+ statementsTotal++;
+ if (hitCount > 0) {
+ statementsCovered++;
+ } else {
+ const stmtInfo = fileData.statementMap[stmtId];
+ if (stmtInfo?.start?.line) {
+ data.uncoveredLines.push(stmtInfo.start.line);
+ }
+ }
+ }
+
+ data.statementCoverage = statementsTotal > 0
+ ? (statementsCovered / statementsTotal) * 100
+ : 100;
+ data.lineCoverage = data.statementCoverage;
+ data.totalLines = statementsTotal;
+ data.coveredLines = statementsCovered;
+ }
+
+ // Handle branch coverage
+ if (fileData.b && fileData.branchMap) {
+ let branchesTotal = 0;
+ let branchesCovered = 0;
+
+ for (const [branchId, hits] of Object.entries(fileData.b)) {
+ for (const hitCount of hits) {
+ branchesTotal++;
+ if (hitCount > 0) {
+ branchesCovered++;
+ } else {
+ const branchInfo = fileData.branchMap[branchId];
+ if (branchInfo) {
+ data.uncoveredBranches.push({
+ line: branchInfo.line,
+ type: (branchInfo.type || 'unknown') as UncoveredBranch['type'],
+ });
+ }
+ }
+ }
+ }
+
+ data.branchCoverage = branchesTotal > 0
+ ? (branchesCovered / branchesTotal) * 100
+ : 100;
+ }
+
+ // Handle function coverage
+ if (fileData.f && fileData.fnMap) {
+ let functionsTotal = 0;
+ let functionsCovered = 0;
+
+ for (const [fnId, hitCount] of Object.entries(fileData.f)) {
+ functionsTotal++;
+ if (hitCount > 0) {
+ functionsCovered++;
+ } else {
+ const fnInfo = fileData.fnMap[fnId];
+ if (fnInfo?.name) {
+ data.uncoveredFunctions.push(fnInfo.name);
+ }
+ }
+ }
+
+ data.functionCoverage = functionsTotal > 0
+ ? (functionsCovered / functionsTotal) * 100
+ : 100;
+ }
+
+ // Deduplicate uncovered lines
+ data.uncoveredLines = Array.from(new Set(data.uncoveredLines)).sort((a, b) => a - b);
+
+ files.push(data);
+ }
+ } catch {
+ // Return empty array on parse error
+ }
+
+ return files;
+}
+
+/**
+ * Load and parse coverage data from project
+ */
+export async function loadCoverageData(projectRoot: string): Promise<{
+ data: CoverageData[];
+ format: 'lcov' | 'istanbul' | 'c8' | 'none';
+ reportPath: string | null;
+}> {
+ const reports = findCoverageReports(projectRoot);
+
+ if (reports.length === 0) {
+ return { data: [], format: 'none', reportPath: null };
+ }
+
+ // Prefer lcov format for most detailed data
+ const lcovReport = reports.find(r => r.type === 'lcov');
+ if (lcovReport) {
+ const content = readFileSync(lcovReport.path, 'utf-8');
+ return {
+ data: parseLcov(content),
+ format: 'lcov',
+ reportPath: lcovReport.path,
+ };
+ }
+
+ // Fall back to istanbul/c8 JSON
+ const jsonReport = reports.find(r => r.type === 'istanbul' || r.type === 'c8');
+ if (jsonReport) {
+ const content = readFileSync(jsonReport.path, 'utf-8');
+ return {
+ data: parseIstanbulJson(content),
+ format: jsonReport.type,
+ reportPath: jsonReport.path,
+ };
+ }
+
+ return { data: [], format: 'none', reportPath: null };
+}
+
+// ============================================================================
+// Coverage Analysis
+// ============================================================================
+
+/**
+ * Calculate file complexity based on size and structure
+ */
+function calculateComplexity(filePath: string, projectRoot: string): number {
+ const fullPath = resolve(projectRoot, filePath);
+
+ try {
+ if (!existsSync(fullPath)) return 1;
+
+ const content = readFileSync(fullPath, 'utf-8');
+ const lines = content.split('\n');
+ const lineCount = lines.length;
+
+ // Basic complexity heuristics
+ let complexity = 1;
+
+ // Line count factor
+ if (lineCount > 500) complexity += 3;
+ else if (lineCount > 200) complexity += 2;
+ else if (lineCount > 100) complexity += 1;
+
+ // Control flow complexity (simple estimation)
+ const controlFlowKeywords = content.match(
+ /\b(if|else|switch|case|for|while|do|try|catch|throw)\b/g
+ );
+ if (controlFlowKeywords) {
+ complexity += Math.min(5, Math.floor(controlFlowKeywords.length / 10));
+ }
+
+ // Class/function count
+ const declarations = content.match(
+ /\b(class|function|const\s+\w+\s*=\s*(async\s+)?\(|=>\s*{)/g
+ );
+ if (declarations) {
+ complexity += Math.min(3, Math.floor(declarations.length / 5));
+ }
+
+ return Math.min(10, complexity);
+ } catch {
+ return 1;
+ }
+}
+
+/**
+ * Determine gap type based on coverage percentage
+ */
+function determineGapType(coverage: number): 'critical' | 'high' | 'medium' | 'low' {
+ if (coverage < 20) return 'critical';
+ if (coverage < 50) return 'high';
+ if (coverage < 70) return 'medium';
+ return 'low';
+}
+
+/**
+ * Suggest agents based on file type and coverage gap
+ */
+function suggestAgentsForFile(
+ filePath: string,
+ coverageData: CoverageData,
+ gapType: 'critical' | 'high' | 'medium' | 'low'
+): string[] {
+ const ext = extname(filePath).toLowerCase();
+ const fileName = basename(filePath).toLowerCase();
+ const agents: string[] = [];
+
+ // Test files need tester primarily
+ if (fileName.includes('.test.') || fileName.includes('.spec.')) {
+ agents.push('tester', 'reviewer');
+ return agents;
+ }
+
+ // Based on file extension
+ const extAgentMap: Record<string, string[]> = {
+ '.ts': ['coder', 'tester', 'reviewer'],
+ '.tsx': ['coder', 'tester', 'reviewer'],
+ '.js': ['coder', 'tester'],
+ '.jsx': ['coder', 'tester'],
+ '.py': ['coder', 'tester', 'ml-developer'],
+ '.go': ['coder', 'tester'],
+ '.rs': ['coder', 'tester', 'performance-engineer'],
+ };
+
+ // Based on directory/file purpose
+ if (filePath.includes('/api/') || filePath.includes('/routes/')) {
+ agents.push('coder', 'tester', 'security-architect');
+ } else if (filePath.includes('/auth/') || filePath.includes('security')) {
+ agents.push('security-architect', 'tester', 'coder');
+ } else if (filePath.includes('/utils/') || filePath.includes('/helpers/')) {
+ agents.push('coder', 'tester');
+ } else if (filePath.includes('/services/')) {
+ agents.push('coder', 'tester', 'architect');
+ } else {
+ agents.push(...(extAgentMap[ext] || ['coder', 'tester']));
+ }
+
+ // For critical gaps, add reviewer
+ if (gapType === 'critical' && !agents.includes('reviewer')) {
+ agents.push('reviewer');
+ }
+
+ // For uncovered branches, add architect for complex logic
+ if (coverageData.uncoveredBranches.length > 5) {
+ if (!agents.includes('architect')) {
+ agents.push('architect');
+ }
+ }
+
+ return Array.from(new Set(agents)).slice(0, 4);
+}
+
+/**
+ * Calculate priority score for coverage gap
+ */
+function calculatePriority(
+ coverageData: CoverageData,
+ complexity: number,
+ gapType: 'critical' | 'high' | 'medium' | 'low'
+): number {
+ // Base priority from gap type
+ const gapPriority: Record<string, number> = {
+ critical: 100,
+ high: 75,
+ medium: 50,
+ low: 25,
+ };
+
+ let priority = gapPriority[gapType];
+
+ // Add complexity factor (0-30 points)
+ priority += complexity * 3;
+
+ // Add uncovered lines factor (0-20 points)
+ const uncoveredRatio = coverageData.uncoveredLines.length / Math.max(1, coverageData.totalLines);
+ priority += Math.min(20, uncoveredRatio * 50);
+
+ // Add branch coverage factor (0-15 points)
+ if (coverageData.branchCoverage < 50) {
+ priority += 15;
+ } else if (coverageData.branchCoverage < 75) {
+ priority += 8;
+ }
+
+ // Important file patterns get boost
+ const fileName = basename(coverageData.filePath);
+ if (fileName.includes('service') || fileName.includes('controller')) {
+ priority += 10;
+ }
+ if (fileName.includes('auth') || fileName.includes('security')) {
+ priority += 15;
+ }
+
+ return Math.min(200, priority);
+}
+
+/**
+ * Analyze coverage and identify gaps
+ */
+export function analyzeCoverageGaps(
+ coverageData: CoverageData[],
+ projectRoot: string,
+ threshold: number = 80
+): CoverageGap[] {
+ const gaps: CoverageGap[] = [];
+
+ for (const data of coverageData) {
+ const avgCoverage = (
+ data.lineCoverage +
+ data.branchCoverage +
+ data.functionCoverage +
+ data.statementCoverage
+ ) / 4;
+
+ if (avgCoverage >= threshold) continue;
+
+ const gapType = determineGapType(avgCoverage);
+ const complexity = calculateComplexity(data.filePath, projectRoot);
+ const suggestedAgents = suggestAgentsForFile(data.filePath, data, gapType);
+ const priority = calculatePriority(data, complexity, gapType);
+
+ // Generate reason
+ const reasons: string[] = [];
+ if (data.lineCoverage < threshold) {
+ reasons.push(`line coverage ${data.lineCoverage.toFixed(1)}%`);
+ }
+ if (data.branchCoverage < threshold) {
+ reasons.push(`branch coverage ${data.branchCoverage.toFixed(1)}%`);
+ }
+ if (data.uncoveredFunctions.length > 0) {
+ reasons.push(`${data.uncoveredFunctions.length} uncovered functions`);
+ }
+
+ gaps.push({
+ filePath: data.filePath,
+ coveragePercent: avgCoverage,
+ gapType,
+ complexity,
+ priority,
+ suggestedAgents,
+ uncoveredLines: data.uncoveredLines.slice(0, 20), // Limit for output
+ reason: reasons.join(', ') || 'Below threshold',
+ });
+ }
+
+ // Sort by priority (descending)
+ return gaps.sort((a, b) => b.priority - a.priority);
+}
+
+/**
+ * Generate coverage summary
+ */
+export function generateCoverageSummary(
+ coverageData: CoverageData[],
+ threshold: number = 80
+): CoverageSummary {
+ if (coverageData.length === 0) {
+ return {
+ totalFiles: 0,
+ overallLineCoverage: 0,
+ overallBranchCoverage: 0,
+ overallFunctionCoverage: 0,
+ overallStatementCoverage: 0,
+ filesBelowThreshold: 0,
+ coverageThreshold: threshold,
+ };
+ }
+
+ const totals = coverageData.reduce(
+ (acc, data) => {
+ acc.line += data.lineCoverage;
+ acc.branch += data.branchCoverage;
+ acc.function += data.functionCoverage;
+ acc.statement += data.statementCoverage;
+ return acc;
+ },
+ { line: 0, branch: 0, function: 0, statement: 0 }
+ );
+
+ const fileCount = coverageData.length;
+ const avgLine = totals.line / fileCount;
+ const avgBranch = totals.branch / fileCount;
+ const avgFunction = totals.function / fileCount;
+ const avgStatement = totals.statement / fileCount;
+
+ const belowThreshold = coverageData.filter(d => {
+ const avg = (d.lineCoverage + d.branchCoverage + d.functionCoverage + d.statementCoverage) / 4;
+ return avg < threshold;
+ }).length;
+
+ return {
+ totalFiles: fileCount,
+ overallLineCoverage: avgLine,
+ overallBranchCoverage: avgBranch,
+ overallFunctionCoverage: avgFunction,
+ overallStatementCoverage: avgStatement,
+ filesBelowThreshold: belowThreshold,
+ coverageThreshold: threshold,
+ };
+}
+
+// ============================================================================
+// Main API Functions
+// ============================================================================
+
+/**
+ * Route a task with coverage awareness
+ *
+ * CLI Usage:
+ * claude-flow route "fix bug" --coverage-aware
+ */
+export async function coverageRoute(
+ task: string,
+ options: {
+ projectRoot?: string;
+ threshold?: number;
+ useRuvector?: boolean;
+ } = {}
+): Promise<CoverageRouteResult> {
+ const projectRoot = options.projectRoot || process.cwd();
+ const threshold = options.threshold ?? 80;
+ const useRuvector = options.useRuvector !== false;
+
+ // Load coverage data
+ const { data: coverageData, format, reportPath } = await loadCoverageData(projectRoot);
+
+ // Analyze gaps
+ const gaps = coverageData.length > 0
+ ? analyzeCoverageGaps(coverageData, projectRoot, threshold)
+ : [];
+
+ // Try ruvector integration if available
+ if (useRuvector && coverageData.length > 0) {
+ const ruvectorResult = await callRuvectorRoute(task, coverageData);
+ if (ruvectorResult && typeof ruvectorResult === 'object') {
+ // Merge ruvector insights if available
+ // (ruvector provides more sophisticated ML-based routing)
+ }
+ }
+
+ // Determine primary agent based on task + coverage
+ const taskLower = task.toLowerCase();
+ let primaryAgent = 'coder';
+ let confidence = 0.75;
+ let reason = 'Default routing based on task analysis';
+ let coverageImpact = 'No coverage data available';
+
+ if (gaps.length > 0) {
+ // Find most relevant gap for task
+ const criticalGaps = gaps.filter(g => g.gapType === 'critical' || g.gapType === 'high');
+
+ if (criticalGaps.length > 0) {
+ primaryAgent = criticalGaps[0].suggestedAgents[0] || 'tester';
+ confidence = 0.85;
+ reason = `Critical coverage gap in ${criticalGaps[0].filePath}`;
+ coverageImpact = `${criticalGaps.length} high-priority files need attention`;
+ }
+
+ // Override based on task keywords
+ if (taskLower.includes('test') || taskLower.includes('coverage')) {
+ primaryAgent = 'tester';
+ confidence = 0.9;
+ reason = 'Task explicitly mentions testing/coverage';
+ } else if (taskLower.includes('security') || taskLower.includes('auth')) {
+ primaryAgent = 'security-architect';
+ confidence = 0.88;
+ reason = 'Security-related task detected';
+ }
+ }
+
+ // Generate suggestions
+ const suggestions: string[] = [];
+ if (format === 'none') {
+ suggestions.push('Run tests with coverage to enable coverage-aware routing');
+ suggestions.push('Supported formats: lcov, istanbul (c8), nyc');
+ } else {
+ if (gaps.length === 0) {
+ suggestions.push('All files meet coverage threshold');
+ } else {
+ suggestions.push(`Focus on ${gaps.slice(0, 3).map(g => basename(g.filePath)).join(', ')}`);
+ if (gaps.some(g => g.gapType === 'critical')) {
+ suggestions.push('Critical coverage gaps detected - prioritize testing');
+ }
+ }
+ }
+
+ const summary = generateCoverageSummary(coverageData, threshold);
+
+ return {
+ success: true,
+ task,
+ coverageAware: format !== 'none',
+ gaps: gaps.slice(0, 10), // Limit output
+ routing: {
+ primaryAgent,
+ confidence,
+ reason,
+ coverageImpact,
+ },
+ suggestions,
+ metrics: {
+ filesAnalyzed: coverageData.length,
+ totalGaps: gaps.length,
+ criticalGaps: gaps.filter(g => g.gapType === 'critical').length,
+ avgCoverage: summary.overallLineCoverage,
+ },
+ };
+}
+
+/**
+ * Suggest coverage improvements for a path
+ *
+ * CLI Usage:
+ * claude-flow route --coverage-suggest src/
+ */
+export async function coverageSuggest(
+ path: string,
+ options: {
+ projectRoot?: string;
+ threshold?: number;
+ useRuvector?: boolean;
+ limit?: number;
+ } = {}
+): Promise<CoverageSuggestResult> {
+ const projectRoot = options.projectRoot || process.cwd();
+ const threshold = options.threshold ?? 80;
+ const useRuvector = options.useRuvector !== false;
+ const limit = options.limit ?? 20;
+
+ // Load coverage data
+ const { data: coverageData, format } = await loadCoverageData(projectRoot);
+
+ // Filter to requested path
+ const normalizedPath = path.startsWith('/') ? path : join(projectRoot, path);
+ const relativePath = relative(projectRoot, normalizedPath);
+
+ const filteredData = coverageData.filter(d => {
+ const filePath = d.filePath.replace(/^\.?\//, '');
+ return filePath.startsWith(relativePath) || filePath.includes(path);
+ });
+
+ // Analyze gaps
+ const gaps = analyzeCoverageGaps(filteredData, projectRoot, threshold);
+
+ // Try ruvector integration
+ const ruvectorAvail = useRuvector ? await checkRuvectorAvailable() : false;
+ if (ruvectorAvail && filteredData.length > 0) {
+ await callRuvectorSuggest(path, filteredData);
+ }
+
+ const summary = generateCoverageSummary(filteredData, threshold);
+
+ return {
+ success: true,
+ path,
+ suggestions: gaps.slice(0, limit),
+ summary,
+ prioritizedFiles: gaps.slice(0, 10).map(g => g.filePath),
+ ruvectorAvailable: ruvectorAvail,
+ };
+}
+
+/**
+ * Get all coverage gaps in project
+ *
+ * CLI Usage:
+ * claude-flow route --coverage-gaps
+ */
+export async function coverageGaps(
+ options: {
+ projectRoot?: string;
+ threshold?: number;
+ useRuvector?: boolean;
+ groupByAgent?: boolean;
+ } = {}
+): Promise<CoverageGapsResult> {
+ const projectRoot = options.projectRoot || process.cwd();
+ const threshold = options.threshold ?? 80;
+ const useRuvector = options.useRuvector !== false;
+ const groupByAgent = options.groupByAgent ?? true;
+
+ // Load coverage data
+ const { data: coverageData } = await loadCoverageData(projectRoot);
+
+ // Analyze all gaps
+ const gaps = analyzeCoverageGaps(coverageData, projectRoot, threshold);
+
+ // Group by suggested agent
+ const agentAssignments: Record<string, string[]> = {};
+ if (groupByAgent) {
+ for (const gap of gaps) {
+ const primaryAgent = gap.suggestedAgents[0] || 'tester';
+ if (!agentAssignments[primaryAgent]) {
+ agentAssignments[primaryAgent] = [];
+ }
+ agentAssignments[primaryAgent].push(gap.filePath);
+ }
+ }
+
+ const summary = generateCoverageSummary(coverageData, threshold);
+ const ruvectorAvail = useRuvector ? await checkRuvectorAvailable() : false;
+
+ return {
+ success: true,
+ gaps,
+ summary,
+ agentAssignments,
+ ruvectorAvailable: ruvectorAvail,
+ };
+}
+
+// ============================================================================
+// Export
+// ============================================================================
+
+export default {
+ coverageRoute,
+ coverageSuggest,
+ coverageGaps,
+ loadCoverageData,
+ analyzeCoverageGaps,
+ generateCoverageSummary,
+ parseLcov,
+ parseIstanbulJson,
+ findCoverageReports,
+};
diff --git a/v3/@claude-flow/cli/src/ruvector/coverage-tools.ts b/v3/@claude-flow/cli/src/ruvector/coverage-tools.ts
new file mode 100644
index 0000000000..ee83c78741
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/coverage-tools.ts
@@ -0,0 +1,173 @@
+/**
+ * Coverage Router MCP Tools
+ *
+ * MCP tool implementations for coverage-aware routing.
+ * Integrates with hooks_coverage_route and hooks_coverage_suggest from ruvector.
+ */
+
+import type { MCPTool } from '../mcp-tools/types.js';
+import {
+ coverageRoute,
+ coverageSuggest,
+ coverageGaps,
+ type CoverageRouteResult,
+ type CoverageSuggestResult,
+ type CoverageGapsResult,
+} from './coverage-router.js';
+
+/**
+ * Coverage-aware routing MCP tool
+ *
+ * Routes tasks to optimal agents based on test coverage gaps.
+ * Uses ruvector's hooks_coverage_route when available.
+ */
+export const hooksCoverageRoute: MCPTool = {
+ name: 'hooks/coverage-route',
+ description: 'Route task to agents based on test coverage gaps (ruvector integration)',
+ category: 'coverage',
+ tags: ['coverage', 'routing', 'testing', 'ruvector'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ task: {
+ type: 'string',
+ description: 'Task description to route',
+ },
+ projectRoot: {
+ type: 'string',
+ description: 'Project root directory (defaults to cwd)',
+ },
+ threshold: {
+ type: 'number',
+ description: 'Coverage threshold percentage (default: 80)',
+ },
+ useRuvector: {
+ type: 'boolean',
+ description: 'Use ruvector integration if available (default: true)',
+ },
+ },
+ required: ['task'],
+ },
+ handler: async (params: Record<string, unknown>): Promise<CoverageRouteResult> => {
+ const task = params.task as string;
+ const projectRoot = params.projectRoot as string | undefined;
+ const threshold = params.threshold as number | undefined;
+ const useRuvector = params.useRuvector as boolean | undefined;
+
+ return coverageRoute(task, {
+ projectRoot,
+ threshold,
+ useRuvector,
+ });
+ },
+};
+
+/**
+ * Coverage suggestions MCP tool
+ *
+ * Suggests which files need better coverage in a given path.
+ * Uses ruvector's hooks_coverage_suggest when available.
+ */
+export const hooksCoverageSuggest: MCPTool = {
+ name: 'hooks/coverage-suggest',
+ description: 'Suggest coverage improvements for a path (ruvector integration)',
+ category: 'coverage',
+ tags: ['coverage', 'suggestions', 'testing', 'ruvector'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: {
+ type: 'string',
+ description: 'Path to analyze for coverage suggestions',
+ },
+ projectRoot: {
+ type: 'string',
+ description: 'Project root directory (defaults to cwd)',
+ },
+ threshold: {
+ type: 'number',
+ description: 'Coverage threshold percentage (default: 80)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of suggestions to return (default: 20)',
+ },
+ useRuvector: {
+ type: 'boolean',
+ description: 'Use ruvector integration if available (default: true)',
+ },
+ },
+ required: ['path'],
+ },
+ handler: async (params: Record<string, unknown>): Promise<CoverageSuggestResult> => {
+ const path = params.path as string;
+ const projectRoot = params.projectRoot as string | undefined;
+ const threshold = params.threshold as number | undefined;
+ const limit = params.limit as number | undefined;
+ const useRuvector = params.useRuvector as boolean | undefined;
+
+ return coverageSuggest(path, {
+ projectRoot,
+ threshold,
+ limit,
+ useRuvector,
+ });
+ },
+};
+
+/**
+ * Coverage gaps MCP tool
+ *
+ * Lists all coverage gaps in the project with agent assignments.
+ */
+export const hooksCoverageGaps: MCPTool = {
+ name: 'hooks/coverage-gaps',
+ description: 'List all coverage gaps with priority scoring and agent assignments',
+ category: 'coverage',
+ tags: ['coverage', 'gaps', 'testing', 'analysis'],
+ inputSchema: {
+ type: 'object',
+ properties: {
+ projectRoot: {
+ type: 'string',
+ description: 'Project root directory (defaults to cwd)',
+ },
+ threshold: {
+ type: 'number',
+ description: 'Coverage threshold percentage (default: 80)',
+ },
+ groupByAgent: {
+ type: 'boolean',
+ description: 'Group gaps by suggested agent (default: true)',
+ },
+ useRuvector: {
+ type: 'boolean',
+ description: 'Use ruvector integration if available (default: true)',
+ },
+ },
+ },
+ handler: async (params: Record<string, unknown>): Promise<CoverageGapsResult> => {
+ const projectRoot = params.projectRoot as string | undefined;
+ const threshold = params.threshold as number | undefined;
+ const groupByAgent = params.groupByAgent as boolean | undefined;
+ const useRuvector = params.useRuvector as boolean | undefined;
+
+ return coverageGaps({
+ projectRoot,
+ threshold,
+ groupByAgent,
+ useRuvector,
+ });
+ },
+};
+
+/**
+ * All coverage router MCP tools
+ */
+export const coverageRouterTools: MCPTool[] = [
+ hooksCoverageRoute,
+ hooksCoverageSuggest,
+ hooksCoverageGaps,
+];
+
+export default coverageRouterTools;
diff --git a/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts b/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts
new file mode 100644
index 0000000000..171ffc3bd7
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts
@@ -0,0 +1,714 @@
+/**
+ * Diff Classification Module
+ * Analyzes git diffs for change risk assessment and classification
+ *
+ * Uses ruvector's hooks_diff_analyze and hooks_diff_classify when available,
+ * with graceful fallback to built-in analysis.
+ */
+
+import { execSync, spawnSync } from 'child_process';
+
+// ============================================
+// Types
+// ============================================
+
+export type RiskLevel = 'low-risk' | 'medium-risk' | 'high-risk' | 'critical';
+
+export interface DiffFile {
+ path: string;
+ status: 'added' | 'modified' | 'deleted' | 'renamed';
+ additions: number;
+ deletions: number;
+ hunks: number;
+ binary: boolean;
+ oldPath?: string; // For renamed files
+}
+
+export interface DiffRiskAssessment {
+ overall: RiskLevel;
+ score: number; // 0-100
+ breakdown: {
+ fileCount: number;
+ totalChanges: number;
+ highRiskFiles: string[];
+ securityConcerns: string[];
+ breakingChanges: string[];
+ testCoverage: 'adequate' | 'insufficient' | 'unknown';
+ };
+}
+
+export interface DiffClassification {
+ category: string;
+ subcategory?: string;
+ confidence: number;
+ reasoning: string;
+}
+
+export interface FileRisk {
+ path: string;
+ risk: RiskLevel;
+ score: number;
+ reasons: string[];
+}
+
+export interface DiffAnalysisResult {
+ ref: string;
+ timestamp: string;
+ files: DiffFile[];
+ risk: DiffRiskAssessment;
+ classification: DiffClassification;
+ fileRisks: FileRisk[];
+ recommendedReviewers: string[];
+ summary: string;
+}
+
+// ============================================
+// Risk Patterns
+// ============================================
+
+const HIGH_RISK_PATTERNS = [
+ { pattern: /auth|authentication|login|password|secret|token|key|credential/i, reason: 'Security-sensitive code' },
+ { pattern: /payment|billing|checkout|stripe|paypal|transaction/i, reason: 'Payment processing code' },
+ { pattern: /database|migration|schema|sql|query/i, reason: 'Database changes' },
+ { pattern: /security|permission|access|rbac|acl/i, reason: 'Security/permission changes' },
+ { pattern: /config|\.env|environment/i, reason: 'Configuration changes' },
+ { pattern: /api\/v\d|breaking|deprecat/i, reason: 'Potential API breaking changes' },
+ { pattern: /crypto|encrypt|decrypt|hash/i, reason: 'Cryptography code' },
+];
+
+const MEDIUM_RISK_PATTERNS = [
+ { pattern: /core|base|foundation|lib\//i, reason: 'Core library changes' },
+ { pattern: /interface|type|contract/i, reason: 'Interface/contract changes' },
+ { pattern: /package\.json|yarn\.lock|package-lock/i, reason: 'Dependency changes' },
+ { pattern: /ci|cd|workflow|pipeline|\.github/i, reason: 'CI/CD changes' },
+ { pattern: /docker|kubernetes|k8s|helm/i, reason: 'Infrastructure changes' },
+];
+
+const SAFE_PATTERNS = [
+ { pattern: /\.md$|readme|docs\//i, reason: 'Documentation' },
+ { pattern: /\.test\.|\.spec\.|__tests__/i, reason: 'Test files' },
+ { pattern: /\.snap$|snapshot/i, reason: 'Snapshot files' },
+ { pattern: /\.css$|\.scss$|\.less$|\.styl/i, reason: 'Style files' },
+ { pattern: /comments?|todo|fixme/i, reason: 'Comment changes' },
+];
+
+// File extension to reviewer mapping
+const REVIEWER_PATTERNS: Record<string, string[]> = {
+ '.ts': ['typescript-expert', 'coder'],
+ '.tsx': ['frontend-expert', 'coder', 'reviewer'],
+ '.py': ['python-expert', 'coder'],
+ '.go': ['go-expert', 'coder'],
+ '.rs': ['rust-expert', 'coder'],
+ '.sql': ['database-expert', 'architect'],
+ '.sh': ['devops-expert', 'security-expert'],
+ '.dockerfile': ['devops-expert', 'security-expert'],
+ '.yaml': ['devops-expert', 'architect'],
+ '.yml': ['devops-expert', 'architect'],
+ '.json': ['coder', 'architect'],
+ 'security': ['security-expert', 'architect'],
+ 'auth': ['security-expert', 'architect'],
+ 'payment': ['security-expert', 'senior-reviewer'],
+};
+
+// ============================================
+// RuVector Integration (Graceful Fallback)
+// ============================================
+
+interface RuVectorResult {
+ available: boolean;
+ analysis?: unknown;
+ classification?: unknown;
+}
+
+/**
+ * Attempts to use ruvector's diff analysis when available
+ */
+async function tryRuVectorAnalysis(diffContent: string): Promise<RuVectorResult> {
+ try {
+ // Check if ruvector is available
+ const result = spawnSync('npx', ['ruvector', '--version'], {
+ encoding: 'utf-8',
+ timeout: 5000,
+ });
+
+ if (result.status !== 0) {
+ return { available: false };
+ }
+
+ // Try hooks_diff_analyze
+ const analyzeResult = spawnSync('npx', ['ruvector', 'hooks_diff_analyze'], {
+ input: diffContent,
+ encoding: 'utf-8',
+ timeout: 30000,
+ });
+
+ if (analyzeResult.status === 0 && analyzeResult.stdout) {
+ try {
+ const analysis = JSON.parse(analyzeResult.stdout);
+ return { available: true, analysis };
+ } catch {
+ // JSON parse failed, continue with fallback
+ }
+ }
+
+ return { available: false };
+ } catch {
+ return { available: false };
+ }
+}
+
+/**
+ * Attempts to use ruvector's diff classification when available
+ */
+async function tryRuVectorClassify(diffContent: string): Promise<RuVectorResult> {
+ try {
+ const result = spawnSync('npx', ['ruvector', 'hooks_diff_classify'], {
+ input: diffContent,
+ encoding: 'utf-8',
+ timeout: 30000,
+ });
+
+ if (result.status === 0 && result.stdout) {
+ try {
+ const classification = JSON.parse(result.stdout);
+ return { available: true, classification };
+ } catch {
+ // JSON parse failed, continue with fallback
+ }
+ }
+
+ return { available: false };
+ } catch {
+ return { available: false };
+ }
+}
+
+// ============================================
+// Git Diff Parsing
+// ============================================
+
+/**
+ * Get git diff for a given ref
+ */
+export function getGitDiff(ref: string = 'HEAD~1', cwd?: string): string {
+ try {
+ const result = execSync(`git diff ${ref}`, {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ maxBuffer: 10 * 1024 * 1024, // 10MB
+ });
+ return result;
+ } catch (error) {
+ throw new Error(`Failed to get git diff: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+/**
+ * Get git diff --stat for file summary
+ */
+export function getGitDiffStat(ref: string = 'HEAD~1', cwd?: string): string {
+ try {
+ const result = execSync(`git diff --stat ${ref}`, {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ });
+ return result;
+ } catch (error) {
+ throw new Error(`Failed to get git diff stat: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+/**
+ * Get git diff --numstat for precise line counts
+ */
+export function getGitDiffNumstat(ref: string = 'HEAD~1', cwd?: string): DiffFile[] {
+ try {
+ const numstat = execSync(`git diff --numstat ${ref}`, {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ });
+
+ const nameStatus = execSync(`git diff --name-status ${ref}`, {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ });
+
+ const files: DiffFile[] = [];
+ const numstatLines = numstat.trim().split('\n').filter(Boolean);
+ const statusMap = new Map<string, string>();
+
+ // Parse name-status output
+ nameStatus.trim().split('\n').filter(Boolean).forEach(line => {
+ const parts = line.split('\t');
+ if (parts.length >= 2) {
+ const status = parts[0];
+ const path = parts.length === 3 ? parts[2] : parts[1]; // Handle renames
+ statusMap.set(path, status);
+ }
+ });
+
+ for (const line of numstatLines) {
+ const parts = line.split('\t');
+ if (parts.length >= 3) {
+ const additions = parts[0] === '-' ? 0 : parseInt(parts[0], 10);
+ const deletions = parts[1] === '-' ? 0 : parseInt(parts[1], 10);
+ const path = parts[2];
+ const binary = parts[0] === '-' && parts[1] === '-';
+
+ const statusCode = statusMap.get(path) || 'M';
+ let status: DiffFile['status'] = 'modified';
+ let oldPath: string | undefined;
+
+ if (statusCode.startsWith('A')) status = 'added';
+ else if (statusCode.startsWith('D')) status = 'deleted';
+ else if (statusCode.startsWith('R')) {
+ status = 'renamed';
+ // For renames, the old path is in the numstat
+ }
+
+ files.push({
+ path,
+ status,
+ additions,
+ deletions,
+ hunks: 1, // Approximate
+ binary,
+ oldPath,
+ });
+ }
+ }
+
+ return files;
+ } catch (error) {
+ throw new Error(`Failed to get git diff numstat: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+/**
+ * Get file contributors for reviewer suggestions
+ */
+export function getFileContributors(filePath: string, cwd?: string): string[] {
+ try {
+ const result = execSync(
+ `git log --format='%an' --follow -- "${filePath}" | sort | uniq -c | sort -rn | head -5`,
+ {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ shell: '/bin/bash',
+ }
+ );
+
+ return result
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map(line => line.trim().replace(/^\d+\s+/, ''))
+ .filter(Boolean);
+ } catch {
+ return [];
+ }
+}
+
+// ============================================
+// Risk Assessment
+// ============================================
+
+/**
+ * Calculate risk score for a single file
+ */
+export function assessFileRisk(file: DiffFile): FileRisk {
+ const reasons: string[] = [];
+ let score = 0;
+
+ // Base score from change size
+ const totalChanges = file.additions + file.deletions;
+ if (totalChanges > 500) {
+ score += 30;
+ reasons.push(`Large change (${totalChanges} lines)`);
+ } else if (totalChanges > 200) {
+ score += 20;
+ reasons.push(`Significant change (${totalChanges} lines)`);
+ } else if (totalChanges > 50) {
+ score += 10;
+ }
+
+ // Check high-risk patterns
+ for (const { pattern, reason } of HIGH_RISK_PATTERNS) {
+ if (pattern.test(file.path)) {
+ score += 25;
+ reasons.push(reason);
+ }
+ }
+
+ // Check medium-risk patterns
+ for (const { pattern, reason } of MEDIUM_RISK_PATTERNS) {
+ if (pattern.test(file.path)) {
+ score += 15;
+ reasons.push(reason);
+ }
+ }
+
+ // Reduce score for safe patterns
+ for (const { pattern, reason } of SAFE_PATTERNS) {
+ if (pattern.test(file.path)) {
+ score = Math.max(0, score - 20);
+ reasons.push(`${reason} (lower risk)`);
+ }
+ }
+
+ // Deleted files are higher risk
+ if (file.status === 'deleted') {
+ score += 15;
+ reasons.push('File deletion');
+ }
+
+ // Binary files need careful review
+ if (file.binary) {
+ score += 10;
+ reasons.push('Binary file');
+ }
+
+ // Cap score at 100
+ score = Math.min(100, score);
+
+ // Determine risk level
+ let risk: RiskLevel = 'low-risk';
+ if (score >= 70) risk = 'critical';
+ else if (score >= 50) risk = 'high-risk';
+ else if (score >= 25) risk = 'medium-risk';
+
+ return { path: file.path, risk, score, reasons };
+}
+
+/**
+ * Calculate overall risk assessment for all files
+ */
+export function assessOverallRisk(files: DiffFile[], fileRisks: FileRisk[]): DiffRiskAssessment {
+ const totalChanges = files.reduce((sum, f) => sum + f.additions + f.deletions, 0);
+ const highRiskFiles = fileRisks.filter(f => f.risk === 'high-risk' || f.risk === 'critical').map(f => f.path);
+
+ // Security concerns
+ const securityConcerns: string[] = [];
+ for (const file of files) {
+ if (/auth|password|secret|token|key|credential|crypto/i.test(file.path)) {
+ securityConcerns.push(`Security-sensitive file: ${file.path}`);
+ }
+ }
+
+ // Breaking changes detection
+ const breakingChanges: string[] = [];
+ for (const file of files) {
+ if (/api\/v\d|breaking|deprecat|interface|type/i.test(file.path)) {
+ if (file.deletions > file.additions) {
+ breakingChanges.push(`Potential breaking change: ${file.path}`);
+ }
+ }
+ }
+
+ // Test coverage assessment
+ const testFiles = files.filter(f => /\.test\.|\.spec\.|__tests__/i.test(f.path));
+ const sourceFiles = files.filter(f => /\.(ts|tsx|js|jsx|py|go|rs)$/.test(f.path) && !/\.test\.|\.spec\./i.test(f.path));
+ let testCoverage: 'adequate' | 'insufficient' | 'unknown' = 'unknown';
+ if (sourceFiles.length > 0) {
+ testCoverage = testFiles.length >= sourceFiles.length * 0.5 ? 'adequate' : 'insufficient';
+ }
+
+ // Calculate overall score (weighted average)
+ const avgScore = fileRisks.length > 0
+ ? fileRisks.reduce((sum, f) => sum + f.score, 0) / fileRisks.length
+ : 0;
+
+ // Adjust for file count
+ let score = avgScore;
+ if (files.length > 20) score += 15;
+ else if (files.length > 10) score += 10;
+ else if (files.length > 5) score += 5;
+
+ // Adjust for security concerns
+ score += securityConcerns.length * 10;
+ score += breakingChanges.length * 10;
+
+ // Cap at 100
+ score = Math.min(100, Math.round(score));
+
+ // Determine overall risk level
+ let overall: RiskLevel = 'low-risk';
+ if (score >= 70) overall = 'critical';
+ else if (score >= 50) overall = 'high-risk';
+ else if (score >= 25) overall = 'medium-risk';
+
+ return {
+ overall,
+ score,
+ breakdown: {
+ fileCount: files.length,
+ totalChanges,
+ highRiskFiles,
+ securityConcerns,
+ breakingChanges,
+ testCoverage,
+ },
+ };
+}
+
+// ============================================
+// Classification
+// ============================================
+
+/**
+ * Classify the type of change
+ */
+export function classifyDiff(files: DiffFile[]): DiffClassification {
+ // Count by category
+ const categories = {
+ feature: 0,
+ bugfix: 0,
+ refactor: 0,
+ test: 0,
+ docs: 0,
+ config: 0,
+ style: 0,
+ infra: 0,
+ security: 0,
+ };
+
+ for (const file of files) {
+ const path = file.path.toLowerCase();
+
+ if (/\.test\.|\.spec\.|__tests__/.test(path)) categories.test++;
+ else if (/\.md$|readme|docs\//.test(path)) categories.docs++;
+ else if (/\.css$|\.scss$|\.less$|\.styl/.test(path)) categories.style++;
+ else if (/config|\.env|\.yaml|\.yml|\.json$/.test(path)) categories.config++;
+ else if (/docker|kubernetes|k8s|helm|ci|cd|workflow/.test(path)) categories.infra++;
+ else if (/auth|security|permission|crypto/.test(path)) categories.security++;
+ else if (file.deletions > file.additions * 2) categories.refactor++;
+ else if (file.status === 'added') categories.feature++;
+ else categories.bugfix++;
+ }
+
+ // Find dominant category
+ let maxCount = 0;
+ let category = 'feature';
+ for (const [cat, count] of Object.entries(categories)) {
+ if (count > maxCount) {
+ maxCount = count;
+ category = cat;
+ }
+ }
+
+ // Calculate confidence
+ const total = Object.values(categories).reduce((a, b) => a + b, 0);
+ const confidence = total > 0 ? Math.min(0.95, (maxCount / total) + 0.2) : 0.5;
+
+ // Generate reasoning
+ const reasoning = generateClassificationReasoning(category, files, categories);
+
+ return {
+ category,
+ subcategory: getSubcategory(category, files),
+ confidence,
+ reasoning,
+ };
+}
+
+function getSubcategory(category: string, files: DiffFile[]): string | undefined {
+ const paths = files.map(f => f.path.toLowerCase()).join(' ');
+
+ switch (category) {
+ case 'feature':
+ if (/api/.test(paths)) return 'api';
+ if (/ui|component|page/.test(paths)) return 'frontend';
+ if (/model|database/.test(paths)) return 'backend';
+ break;
+ case 'bugfix':
+ if (/security|auth/.test(paths)) return 'security-fix';
+ if (/performance|perf/.test(paths)) return 'performance-fix';
+ break;
+ case 'infra':
+ if (/docker/.test(paths)) return 'containerization';
+ if (/ci|cd|workflow/.test(paths)) return 'ci-cd';
+ if (/kubernetes|k8s/.test(paths)) return 'kubernetes';
+ break;
+ }
+
+ return undefined;
+}
+
+function generateClassificationReasoning(
+ category: string,
+ files: DiffFile[],
+ categories: Record<string, number>
+): string {
+ const total = files.length;
+ const parts: string[] = [];
+
+ parts.push(`${total} file(s) changed.`);
+
+ if (categories.test > 0) {
+ parts.push(`${categories.test} test file(s).`);
+ }
+
+ if (categories.docs > 0) {
+ parts.push(`${categories.docs} documentation file(s).`);
+ }
+
+ const addedCount = files.filter(f => f.status === 'added').length;
+ const deletedCount = files.filter(f => f.status === 'deleted').length;
+
+ if (addedCount > 0) {
+ parts.push(`${addedCount} new file(s) added.`);
+ }
+
+ if (deletedCount > 0) {
+ parts.push(`${deletedCount} file(s) deleted.`);
+ }
+
+ parts.push(`Classified as ${category} based on change patterns.`);
+
+ return parts.join(' ');
+}
+
+// ============================================
+// Reviewer Recommendations
+// ============================================
+
+/**
+ * Suggest reviewers based on files changed and their history
+ */
+export function suggestReviewers(files: DiffFile[], fileRisks: FileRisk[]): string[] {
+ const reviewerScores = new Map<string, number>();
+
+ for (const file of files) {
+ const ext = file.path.match(/\.[a-zA-Z0-9]+$/)?.[0] || '';
+ const pathLower = file.path.toLowerCase();
+
+ // Add reviewers based on file extension
+ const extReviewers = REVIEWER_PATTERNS[ext] || [];
+ for (const reviewer of extReviewers) {
+ reviewerScores.set(reviewer, (reviewerScores.get(reviewer) || 0) + 1);
+ }
+
+ // Add reviewers based on path patterns
+ for (const [pattern, reviewers] of Object.entries(REVIEWER_PATTERNS)) {
+ if (pathLower.includes(pattern)) {
+ for (const reviewer of reviewers) {
+ reviewerScores.set(reviewer, (reviewerScores.get(reviewer) || 0) + 2);
+ }
+ }
+ }
+ }
+
+ // Boost scores for high-risk files
+ for (const risk of fileRisks.filter(f => f.risk === 'high-risk' || f.risk === 'critical')) {
+ reviewerScores.set('senior-reviewer', (reviewerScores.get('senior-reviewer') || 0) + 3);
+ if (risk.reasons.some(r => /security/i.test(r))) {
+ reviewerScores.set('security-expert', (reviewerScores.get('security-expert') || 0) + 3);
+ }
+ }
+
+ // Sort by score and return top reviewers
+ return Array.from(reviewerScores.entries())
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 5)
+ .map(([reviewer]) => reviewer);
+}
+
+// ============================================
+// Main Analysis Function
+// ============================================
+
+export interface AnalyzeOptions {
+ ref?: string;
+ cwd?: string;
+ useRuVector?: boolean;
+}
+
+/**
+ * Perform complete diff analysis
+ */
+export async function analyzeDiff(options: AnalyzeOptions = {}): Promise<DiffAnalysisResult> {
+ const ref = options.ref || 'HEAD~1';
+ const cwd = options.cwd || process.cwd();
+
+ // Get diff data
+ const diffContent = getGitDiff(ref, cwd);
+ const files = getGitDiffNumstat(ref, cwd);
+
+ // Try ruvector if available and requested
+ if (options.useRuVector !== false) {
+ const ruVectorAnalysis = await tryRuVectorAnalysis(diffContent);
+ const ruVectorClassify = await tryRuVectorClassify(diffContent);
+
+ if (ruVectorAnalysis.available && ruVectorAnalysis.analysis) {
+ // Use ruvector results if available
+ // This would integrate with ruvector's output format
+ }
+ }
+
+ // Assess each file's risk
+ const fileRisks = files.map(assessFileRisk);
+
+ // Calculate overall risk
+ const risk = assessOverallRisk(files, fileRisks);
+
+ // Classify the change type
+ const classification = classifyDiff(files);
+
+ // Suggest reviewers
+ const recommendedReviewers = suggestReviewers(files, fileRisks);
+
+ // Generate summary
+ const summary = generateSummary(files, risk, classification);
+
+ return {
+ ref,
+ timestamp: new Date().toISOString(),
+ files,
+ risk,
+ classification,
+ fileRisks,
+ recommendedReviewers,
+ summary,
+ };
+}
+
+function generateSummary(
+ files: DiffFile[],
+ risk: DiffRiskAssessment,
+ classification: DiffClassification
+): string {
+ const parts: string[] = [];
+
+ parts.push(`${classification.category.charAt(0).toUpperCase() + classification.category.slice(1)} change`);
+
+ if (classification.subcategory) {
+ parts.push(`(${classification.subcategory})`);
+ }
+
+ parts.push(`affecting ${files.length} file(s).`);
+ parts.push(`Risk level: ${risk.overall} (score: ${risk.score}/100).`);
+
+ if (risk.breakdown.securityConcerns.length > 0) {
+ parts.push(`${risk.breakdown.securityConcerns.length} security concern(s) detected.`);
+ }
+
+ if (risk.breakdown.breakingChanges.length > 0) {
+ parts.push(`${risk.breakdown.breakingChanges.length} potential breaking change(s).`);
+ }
+
+ return parts.join(' ');
+}
+
+// Export utility for CLI
+export const DiffClassifier = {
+ analyzeDiff,
+ getGitDiff,
+ getGitDiffStat,
+ getGitDiffNumstat,
+ assessFileRisk,
+ assessOverallRisk,
+ classifyDiff,
+ suggestReviewers,
+};
+
+export default DiffClassifier;
diff --git a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
new file mode 100644
index 0000000000..38894de7fb
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
@@ -0,0 +1,1172 @@
+/**
+ * Graph Analyzer Module
+ *
+ * Provides code dependency graph analysis using ruvector's graph algorithms:
+ * - MinCut for code boundary detection (refactoring suggestions)
+ * - Louvain for module/community detection
+ * - Circular dependency detection
+ * - DOT format export for visualization
+ *
+ * Falls back to built-in implementations when @ruvector/wasm is not available.
+ *
+ * @module @claude-flow/cli/ruvector/graph-analyzer
+ */
+
+import { readFile, readdir, stat } from 'fs/promises';
+import { join, relative, extname, dirname, basename } from 'path';
+
+// ============================================================================
+// Types
+// ============================================================================
+
+/**
+ * Node in the dependency graph
+ */
+export interface GraphNode {
+ id: string;
+ path: string;
+ name: string;
+ type: 'file' | 'module' | 'package';
+ imports: string[];
+ exports: string[];
+ size: number;
+ complexity?: number;
+}
+
+/**
+ * Edge in the dependency graph
+ */
+export interface GraphEdge {
+ source: string;
+ target: string;
+ type: 'import' | 'require' | 'dynamic' | 're-export';
+ weight: number;
+}
+
+/**
+ * Dependency graph representation
+ */
+export interface DependencyGraph {
+ nodes: Map<string, GraphNode>;
+ edges: GraphEdge[];
+ metadata: {
+ rootDir: string;
+ totalFiles: number;
+ totalEdges: number;
+ buildTime: number;
+ };
+}
+
+/**
+ * MinCut result representing a natural boundary in the codebase
+ */
+export interface MinCutBoundary {
+ cutValue: number;
+ partition1: string[];
+ partition2: string[];
+ cutEdges: GraphEdge[];
+ suggestion: string;
+}
+
+/**
+ * Community/module detection result
+ */
+export interface ModuleCommunity {
+ id: number;
+ members: string[];
+ cohesion: number;
+ centralNode?: string;
+ suggestedName?: string;
+}
+
+/**
+ * Circular dependency info
+ */
+export interface CircularDependency {
+ cycle: string[];
+ severity: 'low' | 'medium' | 'high';
+ suggestion: string;
+}
+
+/**
+ * Analysis result
+ */
+export interface GraphAnalysisResult {
+ graph: DependencyGraph;
+ boundaries?: MinCutBoundary[];
+ communities?: ModuleCommunity[];
+ circularDependencies: CircularDependency[];
+ statistics: {
+ nodeCount: number;
+ edgeCount: number;
+ avgDegree: number;
+ maxDegree: number;
+ density: number;
+ componentCount: number;
+ };
+}
+
+// ============================================================================
+// RuVector Integration (with graceful fallback)
+// ============================================================================
+
+/**
+ * Interface for ruvector graph operations
+ */
+interface IRuVectorGraph {
+ mincut(nodes: string[], edges: Array<[string, string, number]>): {
+ cutValue: number;
+ partition1: string[];
+ partition2: string[];
+ cutEdges: Array<[string, string]>;
+ };
+ louvain(nodes: string[], edges: Array<[string, string, number]>): {
+ communities: Array<{ id: number; members: string[] }>;
+ modularity: number;
+ };
+}
+
+let ruVectorGraph: IRuVectorGraph | null = null;
+let ruVectorLoadAttempted = false;
+
+/**
+ * Attempt to load ruvector graph algorithms
+ */
+async function loadRuVector(): Promise<IRuVectorGraph | null> {
+ if (ruVectorLoadAttempted) return ruVectorGraph;
+ ruVectorLoadAttempted = true;
+
+ try {
+ // Try to load ruvector's graph module
+ // @ts-expect-error - ruvector types may not be available
+ const ruvector = await import('ruvector');
+
+ if (ruvector.hooks_graph_mincut && ruvector.hooks_graph_cluster) {
+ ruVectorGraph = {
+ mincut: (nodes, edges) => ruvector.hooks_graph_mincut(nodes, edges),
+ louvain: (nodes, edges) => ruvector.hooks_graph_cluster(nodes, edges),
+ };
+ return ruVectorGraph;
+ }
+ } catch {
+ // Try alternative import paths
+ try {
+ // @ts-expect-error - @ruvector/wasm types may not be available
+ const wasmModule = await import('@ruvector/wasm');
+ if (wasmModule.GraphAnalyzer) {
+ const analyzer = new wasmModule.GraphAnalyzer();
+ ruVectorGraph = {
+ mincut: (nodes, edges) => analyzer.mincut(nodes, edges),
+ louvain: (nodes, edges) => analyzer.louvain(nodes, edges),
+ };
+ return ruVectorGraph;
+ }
+ } catch {
+ // Fallback will be used
+ }
+ }
+
+ return null;
+}
+
+// ============================================================================
+// Import/Require Parser
+// ============================================================================
+
+/**
+ * Extract imports from TypeScript/JavaScript file
+ */
+function extractImports(content: string, filePath: string): Array<{ path: string; type: GraphEdge['type'] }> {
+ const imports: Array<{ path: string; type: GraphEdge['type'] }> = [];
+
+ // ES6 import statements
+ const esImportRegex = /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*,?\s*)*\s*from\s*['"]([^'"]+)['"]/g;
+ let match: RegExpExecArray | null;
+
+ while ((match = esImportRegex.exec(content)) !== null) {
+ imports.push({ path: match[1], type: 'import' });
+ }
+
+ // Side-effect imports: import 'module'
+ const sideEffectRegex = /import\s+['"]([^'"]+)['"]/g;
+ while ((match = sideEffectRegex.exec(content)) !== null) {
+ imports.push({ path: match[1], type: 'import' });
+ }
+
+ // CommonJS require
+ const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
+ while ((match = requireRegex.exec(content)) !== null) {
+ imports.push({ path: match[1], type: 'require' });
+ }
+
+ // Dynamic imports
+ const dynamicImportRegex = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
+ while ((match = dynamicImportRegex.exec(content)) !== null) {
+ imports.push({ path: match[1], type: 'dynamic' });
+ }
+
+ // Re-exports: export * from 'module'
+ const reExportRegex = /export\s+(?:\*|\{[^}]*\})\s+from\s*['"]([^'"]+)['"]/g;
+ while ((match = reExportRegex.exec(content)) !== null) {
+ imports.push({ path: match[1], type: 're-export' });
+ }
+
+ return imports;
+}
+
+/**
+ * Extract exports from TypeScript/JavaScript file
+ */
+function extractExports(content: string): string[] {
+ const exports: string[] = [];
+
+ // Named exports
+ const namedExportRegex = /export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;
+ let match: RegExpExecArray | null;
+ while ((match = namedExportRegex.exec(content)) !== null) {
+ exports.push(match[1]);
+ }
+
+ // Export list: export { a, b, c }
+ const exportListRegex = /export\s+\{([^}]+)\}/g;
+ while ((match = exportListRegex.exec(content)) !== null) {
+ const names = match[1].split(',').map(n => n.trim().split(/\s+as\s+/)[0].trim());
+ exports.push(...names.filter(n => n));
+ }
+
+ // Default export
+ if (/export\s+default/.test(content)) {
+ exports.push('default');
+ }
+
+ return exports;
+}
+
+/**
+ * Resolve import path to absolute file path
+ */
+function resolveImportPath(importPath: string, fromFile: string, rootDir: string): string | null {
+ // Skip external packages
+ if (!importPath.startsWith('.') && !importPath.startsWith('/')) {
+ return null;
+ }
+
+ const fromDir = dirname(fromFile);
+ let resolved: string;
+
+ if (importPath.startsWith('/')) {
+ resolved = join(rootDir, importPath);
+ } else {
+ resolved = join(fromDir, importPath);
+ }
+
+ // Handle extension-less imports
+ const ext = extname(resolved);
+ if (!ext) {
+ // Try common extensions
+ const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
+ for (const tryExt of extensions) {
+ const tryPath = resolved + tryExt;
+ return tryPath; // Return normalized, existence check done later
+ }
+ // Could be index file
+ return join(resolved, 'index');
+ }
+
+ return resolved;
+}
+
+// ============================================================================
+// Graph Builder
+// ============================================================================
+
+/**
+ * Build dependency graph from source directory
+ */
+export async function buildDependencyGraph(
+ rootDir: string,
+ options: {
+ include?: string[];
+ exclude?: string[];
+ maxDepth?: number;
+ } = {}
+): Promise<DependencyGraph> {
+ const startTime = Date.now();
+ const nodes = new Map<string, GraphNode>();
+ const edges: GraphEdge[] = [];
+
+ const include = options.include || ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
+ const exclude = options.exclude || ['node_modules', 'dist', 'build', '.git', '__tests__', '*.test.*', '*.spec.*'];
+ const maxDepth = options.maxDepth ?? 10;
+
+ /**
+ * Check if path should be excluded
+ */
+ function shouldExclude(path: string): boolean {
+ const name = basename(path);
+ return exclude.some(pattern => {
+ if (pattern.includes('*')) {
+ const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
+ return regex.test(name);
+ }
+ return name === pattern || path.includes(`/${pattern}/`);
+ });
+ }
+
+ /**
+ * Recursively scan directory for source files
+ */
+ async function scanDir(dir: string, depth: number): Promise<void> {
+ if (depth > maxDepth) return;
+
+ try {
+ const entries = await readdir(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = join(dir, entry.name);
+ const relPath = relative(rootDir, fullPath);
+
+ if (shouldExclude(fullPath)) continue;
+
+ if (entry.isDirectory()) {
+ await scanDir(fullPath, depth + 1);
+ } else if (entry.isFile()) {
+ const ext = extname(entry.name);
+ if (include.includes(ext)) {
+ await processFile(fullPath, relPath);
+ }
+ }
+ }
+ } catch {
+ // Directory not readable, skip
+ }
+ }
+
+ /**
+ * Process a single source file
+ */
+ async function processFile(fullPath: string, relPath: string): Promise<void> {
+ try {
+ const content = await readFile(fullPath, 'utf-8');
+ const fileStats = await stat(fullPath);
+
+ const imports = extractImports(content, fullPath);
+ const exportsList = extractExports(content);
+
+ // Create node
+ const node: GraphNode = {
+ id: relPath,
+ path: relPath,
+ name: basename(relPath, extname(relPath)),
+ type: 'file',
+ imports: imports.map(i => i.path),
+ exports: exportsList,
+ size: fileStats.size,
+ complexity: estimateComplexity(content),
+ };
+
+ nodes.set(relPath, node);
+
+ // Create edges for imports
+ for (const imp of imports) {
+ const resolved = resolveImportPath(imp.path, fullPath, rootDir);
+ if (resolved) {
+ const targetRel = relative(rootDir, resolved);
+ edges.push({
+ source: relPath,
+ target: targetRel,
+ type: imp.type,
+ weight: imp.type === 're-export' ? 2 : 1,
+ });
+ }
+ }
+ } catch {
+ // File not readable, skip
+ }
+ }
+
+ // Build the graph
+ await scanDir(rootDir, 0);
+
+ // Normalize edges - ensure targets exist (with extension variations)
+ const normalizedEdges: GraphEdge[] = [];
+ for (const edge of edges) {
+ // Try to find matching node
+ let targetKey = edge.target;
+ if (!nodes.has(targetKey)) {
+ // Try with different extensions
+ const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
+ const baseTarget = targetKey.replace(/\.[^.]+$/, '');
+ for (const ext of extensions) {
+ if (nodes.has(baseTarget + ext)) {
+ targetKey = baseTarget + ext;
+ break;
+ }
+ // Try index files
+ if (nodes.has(join(baseTarget, 'index' + ext))) {
+ targetKey = join(baseTarget, 'index' + ext);
+ break;
+ }
+ }
+ }
+
+ if (nodes.has(targetKey)) {
+ normalizedEdges.push({ ...edge, target: targetKey });
+ }
+ }
+
+ return {
+ nodes,
+ edges: normalizedEdges,
+ metadata: {
+ rootDir,
+ totalFiles: nodes.size,
+ totalEdges: normalizedEdges.length,
+ buildTime: Date.now() - startTime,
+ },
+ };
+}
+
+/**
+ * Estimate cyclomatic complexity from code
+ */
+function estimateComplexity(content: string): number {
+ let complexity = 1;
+
+ // Count branching statements
+ const patterns = [
+ /\bif\s*\(/g,
+ /\belse\s+if\s*\(/g,
+ /\bfor\s*\(/g,
+ /\bwhile\s*\(/g,
+ /\bcase\s+/g,
+ /\bcatch\s*\(/g,
+ /\?\s*[^:]+:/g, // Ternary operator
+ /&&/g,
+ /\|\|/g,
+ ];
+
+ for (const pattern of patterns) {
+ const matches = content.match(pattern);
+ if (matches) complexity += matches.length;
+ }
+
+ return complexity;
+}
+
+// ============================================================================
+// MinCut Algorithm (Fallback Implementation)
+// ============================================================================
+
+/**
+ * Karger's MinCut algorithm (fallback when ruvector not available)
+ * Randomized algorithm that finds minimum cut with high probability
+ */
+function fallbackMinCut(
+ nodes: string[],
+ edges: Array<[string, string, number]>
+): {
+ cutValue: number;
+ partition1: string[];
+ partition2: string[];
+ cutEdges: Array<[string, string]>;
+} {
+ if (nodes.length < 2) {
+ return {
+ cutValue: 0,
+ partition1: nodes,
+ partition2: [],
+ cutEdges: [],
+ };
+ }
+
+ // Use Stoer-Wagner for deterministic result (simplified version)
+ // This is a simplified MinCut that finds cuts using maximum adjacency ordering
+
+ // Build adjacency map with weights
+ const adj = new Map<string, Map<string, number>>();
+ for (const node of nodes) {
+ adj.set(node, new Map());
+ }
+ for (const [u, v, w] of edges) {
+ if (adj.has(u) && adj.has(v)) {
+ adj.get(u)!.set(v, (adj.get(u)!.get(v) || 0) + w);
+ adj.get(v)!.set(u, (adj.get(v)!.get(u) || 0) + w);
+ }
+ }
+
+ let bestCut = Infinity;
+ let bestPartition1: string[] = [];
+ let bestPartition2: string[] = [];
+ let bestCutEdges: Array<[string, string]> = [];
+
+ // Run multiple iterations for better results
+ const iterations = Math.min(nodes.length * 2, 20);
+
+ for (let iter = 0; iter < iterations; iter++) {
+ // Start from different nodes
+ const startNode = nodes[iter % nodes.length];
+ const inSet = new Set<string>([startNode]);
+ const remaining = new Set(nodes.filter(n => n !== startNode));
+
+ while (remaining.size > 1) {
+ // Find node with maximum connectivity to current set
+ let maxNode = '';
+ let maxConn = -1;
+
+ for (const node of remaining) {
+ let conn = 0;
+ for (const inNode of inSet) {
+ conn += adj.get(node)?.get(inNode) || 0;
+ }
+ if (conn > maxConn) {
+ maxConn = conn;
+ maxNode = node;
+ }
+ }
+
+ if (!maxNode) break;
+
+ remaining.delete(maxNode);
+ inSet.add(maxNode);
+ }
+
+ if (remaining.size === 1) {
+ const lastNode = Array.from(remaining)[0];
+ let cutValue = 0;
+ const cutEdges: Array<[string, string]> = [];
+
+ for (const inNode of inSet) {
+ const weight = adj.get(lastNode)?.get(inNode) || 0;
+ if (weight > 0) {
+ cutValue += weight;
+ cutEdges.push([lastNode, inNode]);
+ }
+ }
+
+ if (cutValue < bestCut) {
+ bestCut = cutValue;
+ bestPartition1 = Array.from(inSet);
+ bestPartition2 = [lastNode];
+ bestCutEdges = cutEdges;
+ }
+ }
+ }
+
+ // If we didn't find a good cut, split roughly in half
+ if (bestCut === Infinity) {
+ const mid = Math.floor(nodes.length / 2);
+ bestPartition1 = nodes.slice(0, mid);
+ bestPartition2 = nodes.slice(mid);
+ bestCut = 0;
+ bestCutEdges = [];
+
+ for (const [u, v, w] of edges) {
+ const uIn1 = bestPartition1.includes(u);
+ const vIn1 = bestPartition1.includes(v);
+ if (uIn1 !== vIn1) {
+ bestCut += w;
+ bestCutEdges.push([u, v]);
+ }
+ }
+ }
+
+ return {
+ cutValue: bestCut,
+ partition1: bestPartition1,
+ partition2: bestPartition2,
+ cutEdges: bestCutEdges,
+ };
+}
+
+// ============================================================================
+// Louvain Algorithm (Fallback Implementation)
+// ============================================================================
+
+/**
+ * Louvain community detection algorithm (fallback when ruvector not available)
+ * Greedy modularity optimization
+ */
+function fallbackLouvain(
+ nodes: string[],
+ edges: Array<[string, string, number]>
+): {
+ communities: Array<{ id: number; members: string[] }>;
+ modularity: number;
+} {
+ if (nodes.length === 0) {
+ return { communities: [], modularity: 0 };
+ }
+
+ // Build adjacency map
+ const adj = new Map<string, Map<string, number>>();
+ for (const node of nodes) {
+ adj.set(node, new Map());
+ }
+ let totalWeight = 0;
+ for (const [u, v, w] of edges) {
+ if (adj.has(u) && adj.has(v)) {
+ adj.get(u)!.set(v, (adj.get(u)!.get(v) || 0) + w);
+ adj.get(v)!.set(u, (adj.get(v)!.get(u) || 0) + w);
+ totalWeight += w * 2;
+ }
+ }
+
+ if (totalWeight === 0) {
+ // No edges, each node is its own community
+ return {
+ communities: nodes.map((n, i) => ({ id: i, members: [n] })),
+ modularity: 0,
+ };
+ }
+
+ // Initialize: each node in its own community
+ const community = new Map<string, number>();
+ let nextCommunityId = 0;
+ for (const node of nodes) {
+ community.set(node, nextCommunityId++);
+ }
+
+ // Calculate node degree
+ const degree = new Map<string, number>();
+ for (const node of nodes) {
+ let d = 0;
+ for (const [, w] of adj.get(node)!) {
+ d += w;
+ }
+ degree.set(node, d);
+ }
+
+ // Louvain phase 1: local moving
+ let improved = true;
+ const maxIterations = 10;
+ let iteration = 0;
+
+ while (improved && iteration < maxIterations) {
+ improved = false;
+ iteration++;
+
+ for (const node of nodes) {
+ const currentCommunity = community.get(node)!;
+ const nodeAdj = adj.get(node)!;
+ const nodeDegree = degree.get(node)!;
+
+ // Calculate modularity gain for moving to each neighbor's community
+ const communityWeights = new Map<number, number>();
+
+ for (const [neighbor, weight] of nodeAdj) {
+ const neighborCommunity = community.get(neighbor)!;
+ communityWeights.set(
+ neighborCommunity,
+ (communityWeights.get(neighborCommunity) || 0) + weight
+ );
+ }
+
+ // Calculate community totals
+ const communityTotal = new Map<number, number>();
+ for (const [n, c] of community) {
+ communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0));
+ }
+
+ let bestCommunity = currentCommunity;
+ let bestGain = 0;
+
+ for (const [targetCommunity, edgeWeight] of communityWeights) {
+ if (targetCommunity === currentCommunity) continue;
+
+ // Calculate modularity gain
+ const currentTotal = communityTotal.get(currentCommunity) || 0;
+ const targetTotal = communityTotal.get(targetCommunity) || 0;
+ const currentEdges = communityWeights.get(currentCommunity) || 0;
+
+ const gain =
+ (edgeWeight - currentEdges) / totalWeight -
+ (nodeDegree * (targetTotal - currentTotal + nodeDegree)) / (totalWeight * totalWeight);
+
+ if (gain > bestGain) {
+ bestGain = gain;
+ bestCommunity = targetCommunity;
+ }
+ }
+
+ if (bestCommunity !== currentCommunity) {
+ community.set(node, bestCommunity);
+ improved = true;
+ }
+ }
+ }
+
+ // Collect communities
+ const communityMembers = new Map<number, string[]>();
+ for (const [node, comm] of community) {
+ if (!communityMembers.has(comm)) {
+ communityMembers.set(comm, []);
+ }
+ communityMembers.get(comm)!.push(node);
+ }
+
+ // Renumber communities
+ const communities: Array<{ id: number; members: string[] }> = [];
+ let id = 0;
+ for (const [, members] of communityMembers) {
+ communities.push({ id: id++, members });
+ }
+
+ // Calculate modularity
+ let modularity = 0;
+ for (const [u, v, w] of edges) {
+ const cu = community.get(u)!;
+ const cv = community.get(v)!;
+ if (cu === cv) {
+ const du = degree.get(u)!;
+ const dv = degree.get(v)!;
+ modularity += w - (du * dv) / totalWeight;
+ }
+ }
+ modularity /= totalWeight;
+
+ return { communities, modularity };
+}
+
+// ============================================================================
+// Circular Dependency Detection
+// ============================================================================
+
+/**
+ * Detect circular dependencies using DFS
+ */
+export function detectCircularDependencies(graph: DependencyGraph): CircularDependency[] {
+ const cycles: CircularDependency[] = [];
+ const visited = new Set<string>();
+ const recursionStack = new Set<string>();
+ const path: string[] = [];
+
+ // Build adjacency list
+ const adjList = new Map<string, string[]>();
+ for (const node of graph.nodes.keys()) {
+ adjList.set(node, []);
+ }
+ for (const edge of graph.edges) {
+ const list = adjList.get(edge.source);
+ if (list) {
+ list.push(edge.target);
+ }
+ }
+
+ function dfs(node: string): void {
+ visited.add(node);
+ recursionStack.add(node);
+ path.push(node);
+
+ const neighbors = adjList.get(node) || [];
+ for (const neighbor of neighbors) {
+ if (!visited.has(neighbor)) {
+ dfs(neighbor);
+ } else if (recursionStack.has(neighbor)) {
+ // Found cycle
+ const cycleStart = path.indexOf(neighbor);
+ const cycle = path.slice(cycleStart);
+ cycle.push(neighbor); // Complete the cycle
+
+ const severity = getCycleSeverity(cycle, graph);
+ cycles.push({
+ cycle,
+ severity,
+ suggestion: getCycleSuggestion(cycle, graph),
+ });
+ }
+ }
+
+ recursionStack.delete(node);
+ path.pop();
+ }
+
+ for (const node of graph.nodes.keys()) {
+ if (!visited.has(node)) {
+ dfs(node);
+ }
+ }
+
+ return cycles;
+}
+
+function getCycleSeverity(cycle: string[], graph: DependencyGraph): 'low' | 'medium' | 'high' {
+ // High severity if cycle involves many files or core modules
+ if (cycle.length > 5) return 'high';
+ if (cycle.some(n => n.includes('index') || n.includes('core'))) return 'high';
+ if (cycle.length > 3) return 'medium';
+ return 'low';
+}
+
+function getCycleSuggestion(cycle: string[], graph: DependencyGraph): string {
+ if (cycle.length === 2) {
+ return `Consider extracting shared code into a separate module to break the cycle between ${cycle[0]} and ${cycle[1]}`;
+ }
+
+ // Find the weakest link (least important edge)
+ let weakestEdge = '';
+ let minImports = Infinity;
+
+ for (let i = 0; i < cycle.length - 1; i++) {
+ const from = cycle[i];
+ const to = cycle[i + 1];
+ const fromNode = graph.nodes.get(from);
+ if (fromNode && fromNode.imports.length < minImports) {
+ minImports = fromNode.imports.length;
+ weakestEdge = `${from} -> ${to}`;
+ }
+ }
+
+ return `Break the cycle by refactoring the dependency: ${weakestEdge}. Consider dependency injection or extracting interfaces.`;
+}
+
+// ============================================================================
+// Main Analysis Functions
+// ============================================================================
+
+/**
+ * Analyze graph boundaries using MinCut algorithm
+ */
+export async function analyzeMinCutBoundaries(
+ graph: DependencyGraph,
+ numPartitions: number = 2
+): Promise<MinCutBoundary[]> {
+ const nodes = Array.from(graph.nodes.keys());
+ const edges: Array<[string, string, number]> = graph.edges.map(e => [e.source, e.target, e.weight]);
+
+ const boundaries: MinCutBoundary[] = [];
+
+ // Try to use ruvector, fallback to built-in
+ const ruVector = await loadRuVector();
+
+ // Get initial partition
+ let result: ReturnType<typeof fallbackMinCut>;
+ if (ruVector) {
+ result = ruVector.mincut(nodes, edges);
+ } else {
+ result = fallbackMinCut(nodes, edges);
+ }
+
+ boundaries.push({
+ cutValue: result.cutValue,
+ partition1: result.partition1,
+ partition2: result.partition2,
+ cutEdges: result.cutEdges.map(([s, t]) => {
+ const edge = graph.edges.find(e => e.source === s && e.target === t);
+ return edge || { source: s, target: t, type: 'import' as const, weight: 1 };
+ }),
+ suggestion: generateBoundarySuggestion(result.partition1, result.partition2, graph),
+ });
+
+ // Recursively partition if needed
+ if (numPartitions > 2 && result.partition1.length > 2) {
+ const subEdges: Array<[string, string, number]> = edges.filter(
+ ([u, v]) => result.partition1.includes(u) && result.partition1.includes(v)
+ );
+ const subResult = ruVector
+ ? ruVector.mincut(result.partition1, subEdges)
+ : fallbackMinCut(result.partition1, subEdges);
+
+ if (subResult.cutValue > 0) {
+ boundaries.push({
+ cutValue: subResult.cutValue,
+ partition1: subResult.partition1,
+ partition2: subResult.partition2,
+ cutEdges: subResult.cutEdges.map(([s, t]) => {
+ const edge = graph.edges.find(e => e.source === s && e.target === t);
+ return edge || { source: s, target: t, type: 'import' as const, weight: 1 };
+ }),
+ suggestion: generateBoundarySuggestion(subResult.partition1, subResult.partition2, graph),
+ });
+ }
+ }
+
+ return boundaries;
+}
+
+function generateBoundarySuggestion(partition1: string[], partition2: string[], graph: DependencyGraph): string {
+ // Analyze the partitions to suggest organization
+ const p1Dirs = new Set(partition1.map(p => dirname(p)).filter(d => d !== '.'));
+ const p2Dirs = new Set(partition2.map(p => dirname(p)).filter(d => d !== '.'));
+
+ if (p1Dirs.size === 1 && p2Dirs.size === 1) {
+ const dir1 = Array.from(p1Dirs)[0];
+ const dir2 = Array.from(p2Dirs)[0];
+ return `Natural boundary detected between ${dir1}/ and ${dir2}/. These could be separate packages.`;
+ }
+
+ if (partition1.length > partition2.length * 3) {
+ return `Consider extracting ${partition2.length} files into a separate module. They have minimal coupling to the rest.`;
+ }
+
+ return `Found ${partition1.length} and ${partition2.length} file groups with minimal coupling. Consider organizing into separate modules.`;
+}
+
+/**
+ * Analyze module communities using Louvain algorithm
+ */
+export async function analyzeModuleCommunities(graph: DependencyGraph): Promise<ModuleCommunity[]> {
+ const nodes = Array.from(graph.nodes.keys());
+ const edges: Array<[string, string, number]> = graph.edges.map(e => [e.source, e.target, e.weight]);
+
+ // Try to use ruvector, fallback to built-in
+ const ruVector = await loadRuVector();
+ const result = ruVector ? ruVector.louvain(nodes, edges) : fallbackLouvain(nodes, edges);
+
+ return result.communities.map(comm => {
+ // Find the most connected node as central
+ let maxConnections = 0;
+ let centralNode = comm.members[0];
+
+ for (const member of comm.members) {
+ const connections = graph.edges.filter(
+ e =>
+ (e.source === member && comm.members.includes(e.target)) ||
+ (e.target === member && comm.members.includes(e.source))
+ ).length;
+
+ if (connections > maxConnections) {
+ maxConnections = connections;
+ centralNode = member;
+ }
+ }
+
+ // Calculate cohesion (internal edges / total possible edges)
+ const internalEdges = graph.edges.filter(
+ e => comm.members.includes(e.source) && comm.members.includes(e.target)
+ ).length;
+ const possibleEdges = (comm.members.length * (comm.members.length - 1)) / 2;
+ const cohesion = possibleEdges > 0 ? internalEdges / possibleEdges : 1;
+
+ // Suggest name based on common directory
+ const dirs = comm.members.map(m => dirname(m));
+ const commonDir = findCommonPrefix(dirs);
+ const suggestedName = commonDir || basename(centralNode, extname(centralNode));
+
+ return {
+ id: comm.id,
+ members: comm.members,
+ cohesion,
+ centralNode,
+ suggestedName,
+ };
+ });
+}
+
+function findCommonPrefix(strings: string[]): string {
+ if (strings.length === 0) return '';
+ if (strings.length === 1) return strings[0];
+
+ const sorted = [...strings].sort();
+ const first = sorted[0];
+ const last = sorted[sorted.length - 1];
+
+ let i = 0;
+ while (i < first.length && first[i] === last[i]) {
+ i++;
+ }
+
+ const prefix = first.slice(0, i);
+ // Return the last complete directory segment
+ const lastSlash = prefix.lastIndexOf('/');
+ return lastSlash > 0 ? prefix.slice(0, lastSlash) : '';
+}
+
+/**
+ * Full graph analysis
+ */
+export async function analyzeGraph(
+ rootDir: string,
+ options: {
+ includeBoundaries?: boolean;
+ includeModules?: boolean;
+ numPartitions?: number;
+ } = {}
+): Promise<GraphAnalysisResult> {
+ const graph = await buildDependencyGraph(rootDir);
+
+ // Calculate statistics
+ const nodeCount = graph.nodes.size;
+ const edgeCount = graph.edges.length;
+
+ const degrees = new Map<string, number>();
+ for (const node of graph.nodes.keys()) {
+ degrees.set(node, 0);
+ }
+ for (const edge of graph.edges) {
+ degrees.set(edge.source, (degrees.get(edge.source) || 0) + 1);
+ degrees.set(edge.target, (degrees.get(edge.target) || 0) + 1);
+ }
+
+ const degreeValues = Array.from(degrees.values());
+ const avgDegree = degreeValues.length > 0 ? degreeValues.reduce((a, b) => a + b, 0) / degreeValues.length : 0;
+ const maxDegree = degreeValues.length > 0 ? Math.max(...degreeValues) : 0;
+ const density = nodeCount > 1 ? (2 * edgeCount) / (nodeCount * (nodeCount - 1)) : 0;
+
+ // Count connected components
+ const visited = new Set<string>();
+ let componentCount = 0;
+
+ function dfs(node: string): void {
+ visited.add(node);
+ for (const edge of graph.edges) {
+ if (edge.source === node && !visited.has(edge.target)) {
+ dfs(edge.target);
+ }
+ if (edge.target === node && !visited.has(edge.source)) {
+ dfs(edge.source);
+ }
+ }
+ }
+
+ for (const node of graph.nodes.keys()) {
+ if (!visited.has(node)) {
+ componentCount++;
+ dfs(node);
+ }
+ }
+
+ // Detect circular dependencies
+ const circularDependencies = detectCircularDependencies(graph);
+
+ // Analyze boundaries and communities if requested
+ let boundaries: MinCutBoundary[] | undefined;
+ let communities: ModuleCommunity[] | undefined;
+
+ if (options.includeBoundaries !== false) {
+ boundaries = await analyzeMinCutBoundaries(graph, options.numPartitions);
+ }
+
+ if (options.includeModules !== false) {
+ communities = await analyzeModuleCommunities(graph);
+ }
+
+ return {
+ graph,
+ boundaries,
+ communities,
+ circularDependencies,
+ statistics: {
+ nodeCount,
+ edgeCount,
+ avgDegree,
+ maxDegree,
+ density,
+ componentCount,
+ },
+ };
+}
+
+// ============================================================================
+// DOT Format Export
+// ============================================================================
+
+/**
+ * Export graph to DOT format for visualization
+ */
+export function exportToDot(
+ result: GraphAnalysisResult,
+ options: {
+ includeLabels?: boolean;
+ colorByCommunity?: boolean;
+ highlightCycles?: boolean;
+ } = {}
+): string {
+ const { graph, communities, circularDependencies } = result;
+ const lines: string[] = ['digraph DependencyGraph {'];
+ lines.push(' rankdir=LR;');
+ lines.push(' node [shape=box, style=rounded];');
+ lines.push('');
+
+ // Generate colors for communities
+ const communityColors = new Map<string, string>();
+ if (options.colorByCommunity && communities) {
+ const colors = [
+ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231',
+ '#911eb4', '#42d4f4', '#f032e6', '#bfef45', '#fabed4',
+ ];
+ for (const comm of communities) {
+ const color = colors[comm.id % colors.length];
+ for (const member of comm.members) {
+ communityColors.set(member, color);
+ }
+ }
+ }
+
+ // Find nodes in cycles
+ const nodesInCycles = new Set<string>();
+ if (options.highlightCycles && circularDependencies) {
+ for (const cycle of circularDependencies) {
+ for (const node of cycle.cycle) {
+ nodesInCycles.add(node);
+ }
+ }
+ }
+
+ // Output nodes
+ lines.push(' // Nodes');
+ for (const [id, node] of graph.nodes) {
+ const attrs: string[] = [];
+
+ if (options.includeLabels !== false) {
+ attrs.push(`label="${node.name}"`);
+ }
+
+ if (communityColors.has(id)) {
+ attrs.push(`fillcolor="${communityColors.get(id)}"`, 'style="filled,rounded"');
+ }
+
+ if (nodesInCycles.has(id)) {
+ attrs.push('color=red', 'penwidth=2');
+ }
+
+ const attrStr = attrs.length > 0 ? ` [${attrs.join(', ')}]` : '';
+ lines.push(` "${id}"${attrStr};`);
+ }
+
+ lines.push('');
+
+ // Output edges
+ lines.push(' // Edges');
+ for (const edge of graph.edges) {
+ const attrs: string[] = [];
+
+ if (edge.type === 'dynamic') {
+ attrs.push('style=dashed');
+ } else if (edge.type === 're-export') {
+ attrs.push('style=bold');
+ }
+
+ // Check if edge is part of a cycle
+ if (options.highlightCycles) {
+ const isCycleEdge = circularDependencies.some(cd => {
+ for (let i = 0; i < cd.cycle.length - 1; i++) {
+ if (cd.cycle[i] === edge.source && cd.cycle[i + 1] === edge.target) {
+ return true;
+ }
+ }
+ return false;
+ });
+
+ if (isCycleEdge) {
+ attrs.push('color=red', 'penwidth=2');
+ }
+ }
+
+ const attrStr = attrs.length > 0 ? ` [${attrs.join(', ')}]` : '';
+ lines.push(` "${edge.source}" -> "${edge.target}"${attrStr};`);
+ }
+
+ lines.push('}');
+ return lines.join('\n');
+}
+
+// ============================================================================
+// Exports
+// ============================================================================
+
+export {
+ loadRuVector,
+ fallbackMinCut,
+ fallbackLouvain,
+};
diff --git a/v3/@claude-flow/cli/src/ruvector/index.ts b/v3/@claude-flow/cli/src/ruvector/index.ts
new file mode 100644
index 0000000000..d6b30a4be0
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/index.ts
@@ -0,0 +1,42 @@
+/**
+ * RuVector Integration Module for Claude Flow CLI
+ *
+ * Provides integration with @ruvector packages for:
+ * - Q-Learning based task routing
+ * - AST code analysis
+ * - Diff classification
+ * - Coverage-based routing
+ * - Graph boundary analysis
+ *
+ * @module @claude-flow/cli/ruvector
+ */
+
+export { QLearningRouter, createQLearningRouter, type QLearningRouterConfig, type RouteDecision } from './q-learning-router.js';
+export { ASTAnalyzer, createASTAnalyzer, type ASTAnalysis, type ASTNode, type ASTAnalyzerConfig } from './ast-analyzer.js';
+export { DiffClassifier, createDiffClassifier, type DiffClassification, type DiffHunk, type DiffClassifierConfig } from './diff-classifier.js';
+export { CoverageRouter, createCoverageRouter, type CoverageReport, type CoverageRouteResult, type CoverageRouterConfig } from './coverage-router.js';
+export { GraphAnalyzer, createGraphAnalyzer, type GraphBoundary, type DependencyGraph, type GraphAnalyzerConfig } from './graph-analyzer.js';
+
+/**
+ * Check if ruvector packages are available
+ */
+export async function isRuvectorAvailable(): Promise<boolean> {
+ try {
+ await import('@ruvector/core');
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Get ruvector version if available
+ */
+export async function getRuvectorVersion(): Promise<string | null> {
+ try {
+ const ruvector = await import('@ruvector/core');
+ return (ruvector as any).version || '1.0.0';
+ } catch {
+ return null;
+ }
+}
diff --git a/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts b/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts
new file mode 100644
index 0000000000..b304cfad35
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/q-learning-router.ts
@@ -0,0 +1,328 @@
+/**
+ * Q-Learning Router for Task Routing
+ *
+ * Uses reinforcement learning to optimize task routing decisions
+ * based on historical performance and context.
+ *
+ * @module q-learning-router
+ */
+
+/**
+ * Q-Learning Router Configuration
+ */
+export interface QLearningRouterConfig {
+ /** Learning rate (default: 0.1) */
+ learningRate: number;
+ /** Discount factor (default: 0.99) */
+ gamma: number;
+ /** Initial exploration rate (default: 1.0) */
+ explorationInitial: number;
+ /** Final exploration rate (default: 0.01) */
+ explorationFinal: number;
+ /** Exploration decay steps (default: 10000) */
+ explorationDecay: number;
+ /** Maximum states in Q-table (default: 10000) */
+ maxStates: number;
+ /** Number of actions/routes (default: 8) */
+ numActions: number;
+}
+
+/**
+ * Route decision result
+ */
+export interface RouteDecision {
+ /** Selected route/action */
+ route: string;
+ /** Confidence score (0-1) */
+ confidence: number;
+ /** Q-values for all routes */
+ qValues: number[];
+ /** Was exploration used */
+ explored: boolean;
+ /** Route alternatives */
+ alternatives: Array<{ route: string; score: number }>;
+}
+
+/**
+ * Q-table entry
+ */
+interface QEntry {
+ qValues: Float32Array;
+ visits: number;
+ lastUpdate: number;
+}
+
+/**
+ * Default configuration
+ */
+const DEFAULT_CONFIG: QLearningRouterConfig = {
+ learningRate: 0.1,
+ gamma: 0.99,
+ explorationInitial: 1.0,
+ explorationFinal: 0.01,
+ explorationDecay: 10000,
+ maxStates: 10000,
+ numActions: 8,
+};
+
+/**
+ * Route names mapping
+ */
+const ROUTE_NAMES = [
+ 'coder',
+ 'tester',
+ 'reviewer',
+ 'architect',
+ 'researcher',
+ 'optimizer',
+ 'debugger',
+ 'documenter',
+];
+
+/**
+ * Q-Learning Router for intelligent task routing
+ */
+export class QLearningRouter {
+ private config: QLearningRouterConfig;
+ private qTable: Map<string, QEntry> = new Map();
+ private epsilon: number;
+ private stepCount = 0;
+ private updateCount = 0;
+ private avgTDError = 0;
+ private ruvectorEngine: unknown = null;
+ private useNative = false;
+
+ constructor(config: Partial<QLearningRouterConfig> = {}) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ this.epsilon = this.config.explorationInitial;
+ }
+
+ /**
+ * Initialize the router, attempting to load ruvector native module
+ */
+ async initialize(): Promise<void> {
+ try {
+ const ruvector = await import('@ruvector/core');
+ this.ruvectorEngine = (ruvector as any).createQLearning?.(this.config);
+ this.useNative = !!this.ruvectorEngine;
+ } catch {
+ // Fallback to JS implementation
+ this.useNative = false;
+ }
+ }
+
+ /**
+ * Route a task based on its context
+ */
+ route(taskContext: string, explore: boolean = true): RouteDecision {
+ const stateKey = this.hashState(taskContext);
+
+ // Check if we should explore
+ const shouldExplore = explore && Math.random() < this.epsilon;
+
+ let actionIdx: number;
+ let qValues: number[];
+
+ if (shouldExplore) {
+ // Random exploration
+ actionIdx = Math.floor(Math.random() * this.config.numActions);
+ qValues = this.getQValues(stateKey);
+ } else {
+ // Exploit - choose best action
+ qValues = this.getQValues(stateKey);
+ actionIdx = this.argmax(qValues);
+ }
+
+ // Calculate confidence from softmax of Q-values
+ const confidence = this.softmaxConfidence(qValues, actionIdx);
+
+ // Get alternatives sorted by Q-value
+ const alternatives = ROUTE_NAMES
+ .map((route, idx) => ({ route, score: qValues[idx] }))
+ .sort((a, b) => b.score - a.score)
+ .slice(1, 4); // Top 3 alternatives
+
+ return {
+ route: ROUTE_NAMES[actionIdx] || 'coder',
+ confidence,
+ qValues,
+ explored: shouldExplore,
+ alternatives,
+ };
+ }
+
+ /**
+ * Update Q-values based on feedback
+ */
+ update(taskContext: string, action: string, reward: number, nextContext?: string): number {
+ const stateKey = this.hashState(taskContext);
+ const actionIdx = ROUTE_NAMES.indexOf(action);
+
+ if (actionIdx === -1) {
+ return 0;
+ }
+
+ const entry = this.getOrCreateEntry(stateKey);
+ const currentQ = entry.qValues[actionIdx];
+
+ // Calculate target Q-value
+ let targetQ: number;
+ if (nextContext) {
+ const nextStateKey = this.hashState(nextContext);
+ const nextQValues = this.getQValues(nextStateKey);
+ const maxNextQ = Math.max(...nextQValues);
+ targetQ = reward + this.config.gamma * maxNextQ;
+ } else {
+ // Terminal state
+ targetQ = reward;
+ }
+
+ // TD error
+ const tdError = targetQ - currentQ;
+
+ // Update Q-value
+ entry.qValues[actionIdx] += this.config.learningRate * tdError;
+ entry.visits++;
+ entry.lastUpdate = Date.now();
+
+ // Decay exploration
+ this.stepCount++;
+ this.epsilon = Math.max(
+ this.config.explorationFinal,
+ this.config.explorationInitial - this.stepCount / this.config.explorationDecay
+ );
+
+ // Prune Q-table if needed
+ if (this.qTable.size > this.config.maxStates) {
+ this.pruneQTable();
+ }
+
+ this.updateCount++;
+ this.avgTDError = (this.avgTDError * (this.updateCount - 1) + Math.abs(tdError)) / this.updateCount;
+
+ return tdError;
+ }
+
+ /**
+ * Get statistics
+ */
+ getStats(): Record<string, number> {
+ return {
+ updateCount: this.updateCount,
+ qTableSize: this.qTable.size,
+ epsilon: this.epsilon,
+ avgTDError: this.avgTDError,
+ stepCount: this.stepCount,
+ useNative: this.useNative ? 1 : 0,
+ };
+ }
+
+ /**
+ * Reset the router
+ */
+ reset(): void {
+ this.qTable.clear();
+ this.epsilon = this.config.explorationInitial;
+ this.stepCount = 0;
+ this.updateCount = 0;
+ this.avgTDError = 0;
+ }
+
+ /**
+ * Export Q-table for persistence
+ */
+ export(): Record<string, { qValues: number[]; visits: number }> {
+ const result: Record<string, { qValues: number[]; visits: number }> = {};
+ for (const [key, entry] of this.qTable) {
+ result[key] = {
+ qValues: Array.from(entry.qValues),
+ visits: entry.visits,
+ };
+ }
+ return result;
+ }
+
+ /**
+ * Import Q-table from persistence
+ */
+ import(data: Record<string, { qValues: number[]; visits: number }>): void {
+ this.qTable.clear();
+ for (const [key, entry] of Object.entries(data)) {
+ this.qTable.set(key, {
+ qValues: new Float32Array(entry.qValues),
+ visits: entry.visits,
+ lastUpdate: Date.now(),
+ });
+ }
+ }
+
+ // Private methods
+
+ private hashState(context: string): string {
+ // Simple hash for context string
+ let hash = 0;
+ for (let i = 0; i < context.length; i++) {
+ const char = context.charCodeAt(i);
+ hash = ((hash << 5) - hash) + char;
+ hash = hash & hash; // Convert to 32-bit integer
+ }
+ return `state_${hash}`;
+ }
+
+ private getQValues(stateKey: string): number[] {
+ const entry = this.qTable.get(stateKey);
+ if (!entry) {
+ return new Array(this.config.numActions).fill(0);
+ }
+ return Array.from(entry.qValues);
+ }
+
+ private getOrCreateEntry(stateKey: string): QEntry {
+ let entry = this.qTable.get(stateKey);
+ if (!entry) {
+ entry = {
+ qValues: new Float32Array(this.config.numActions),
+ visits: 0,
+ lastUpdate: Date.now(),
+ };
+ this.qTable.set(stateKey, entry);
+ }
+ return entry;
+ }
+
+ private argmax(values: number[]): number {
+ let maxIdx = 0;
+ let maxVal = values[0];
+ for (let i = 1; i < values.length; i++) {
+ if (values[i] > maxVal) {
+ maxVal = values[i];
+ maxIdx = i;
+ }
+ }
+ return maxIdx;
+ }
+
+ private softmaxConfidence(qValues: number[], actionIdx: number): number {
+ const maxQ = Math.max(...qValues);
+ const expValues = qValues.map(q => Math.exp(q - maxQ)); // Subtract max for numerical stability
+ const sumExp = expValues.reduce((a, b) => a + b, 0);
+ return expValues[actionIdx] / sumExp;
+ }
+
+ private pruneQTable(): void {
+ const entries = Array.from(this.qTable.entries())
+ .sort((a, b) => a[1].lastUpdate - b[1].lastUpdate);
+
+ const toRemove = entries.length - Math.floor(this.config.maxStates * 0.8);
+ for (let i = 0; i < toRemove; i++) {
+ this.qTable.delete(entries[i][0]);
+ }
+ }
+}
+
+/**
+ * Factory function
+ */
+export function createQLearningRouter(config?: Partial<QLearningRouterConfig>): QLearningRouter {
+ return new QLearningRouter(config);
+}
diff --git a/v3/@claude-flow/cli/src/ruvector/vector-db.ts b/v3/@claude-flow/cli/src/ruvector/vector-db.ts
new file mode 100644
index 0000000000..a02df79947
--- /dev/null
+++ b/v3/@claude-flow/cli/src/ruvector/vector-db.ts
@@ -0,0 +1,257 @@
+/**
+ * Vector Database Module
+ *
+ * Provides optional ruvector WASM-accelerated vector operations for:
+ * - Semantic similarity search
+ * - HNSW indexing (150x faster)
+ * - Embedding generation
+ *
+ * Gracefully degrades when ruvector is not installed.
+ *
+ * Created with love by ruv.io
+ */
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export interface VectorDB {
+ insert(embedding: Float32Array, id: string, metadata?: Record<string, unknown>): void;
+ search(query: Float32Array, k?: number): Array<{ id: string; score: number; metadata?: Record<string, unknown> }>;
+ remove(id: string): boolean;
+ size(): number;
+ clear(): void;
+}
+
+export interface RuVectorModule {
+ createVectorDB(dimensions: number): Promise<VectorDB>;
+ generateEmbedding(text: string, dimensions?: number): Float32Array;
+ cosineSimilarity(a: Float32Array, b: Float32Array): number;
+ isWASMAccelerated(): boolean;
+}
+
+// ============================================================================
+// Fallback Implementation (when ruvector not available)
+// ============================================================================
+
+class FallbackVectorDB implements VectorDB {
+ private vectors: Map<string, { embedding: Float32Array; metadata?: Record<string, unknown> }> = new Map();
+ private dimensions: number;
+
+ constructor(dimensions: number) {
+ this.dimensions = dimensions;
+ }
+
+ insert(embedding: Float32Array, id: string, metadata?: Record<string, unknown>): void {
+ this.vectors.set(id, { embedding, metadata });
+ }
+
+ search(query: Float32Array, k: number = 10): Array<{ id: string; score: number; metadata?: Record<string, unknown> }> {
+ const results: Array<{ id: string; score: number; metadata?: Record<string, unknown> }> = [];
+
+ for (const [id, { embedding, metadata }] of this.vectors) {
+ const score = cosineSimilarity(query, embedding);
+ results.push({ id, score, metadata });
+ }
+
+ return results
+ .sort((a, b) => b.score - a.score)
+ .slice(0, k);
+ }
+
+ remove(id: string): boolean {
+ return this.vectors.delete(id);
+ }
+
+ size(): number {
+ return this.vectors.size;
+ }
+
+ clear(): void {
+ this.vectors.clear();
+ }
+}
+
+/**
+ * Compute cosine similarity between two vectors
+ */
+function cosineSimilarity(a: Float32Array, b: Float32Array): number {
+ if (a.length !== b.length) {
+ throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
+ }
+
+ let dotProduct = 0;
+ let normA = 0;
+ let normB = 0;
+
+ for (let i = 0; i < a.length; i++) {
+ dotProduct += a[i] * b[i];
+ normA += a[i] * a[i];
+ normB += b[i] * b[i];
+ }
+
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
+ return denom === 0 ? 0 : dotProduct / denom;
+}
+
+/**
+ * Generate a simple hash-based embedding (fallback when ruvector not available)
+ */
+function generateHashEmbedding(text: string, dimensions: number = 768): Float32Array {
+ const embedding = new Float32Array(dimensions);
+ const normalized = text.toLowerCase().trim();
+
+ // Simple hash function
+ let hash = 0;
+ for (let i = 0; i < normalized.length; i++) {
+ hash = ((hash << 5) - hash) + normalized.charCodeAt(i);
+ hash = hash & hash; // Convert to 32bit integer
+ }
+
+ // Generate pseudo-random embedding based on hash
+ for (let i = 0; i < dimensions; i++) {
+ embedding[i] = Math.sin(hash * (i + 1) * 0.001) * 0.5 + 0.5;
+ }
+
+ // Normalize
+ let norm = 0;
+ for (let i = 0; i < dimensions; i++) {
+ norm += embedding[i] * embedding[i];
+ }
+ norm = Math.sqrt(norm);
+ for (let i = 0; i < dimensions; i++) {
+ embedding[i] /= norm;
+ }
+
+ return embedding;
+}
+
+// ============================================================================
+// Module State
+// ============================================================================
+
+let ruvectorModule: RuVectorModule | null = null;
+let loadAttempted = false;
+let isAvailable = false;
+
+// ============================================================================
+// Public API
+// ============================================================================
+
+/**
+ * Attempt to load the ruvector module
+ * Returns true if successfully loaded, false otherwise
+ */
+export async function loadRuVector(): Promise<boolean> {
+ if (loadAttempted) {
+ return isAvailable;
+ }
+
+ loadAttempted = true;
+
+ try {
+ // Dynamic import to handle missing dependency gracefully
+ const ruvector = await import('ruvector').catch(() => null);
+
+ if (ruvector && typeof ruvector.createVectorDB === 'function') {
+ ruvectorModule = ruvector as RuVectorModule;
+ isAvailable = true;
+ return true;
+ }
+ } catch {
+ // Silently fail - ruvector is optional
+ }
+
+ isAvailable = false;
+ return false;
+}
+
+/**
+ * Check if ruvector is available
+ */
+export function isRuVectorAvailable(): boolean {
+ return isAvailable;
+}
+
+/**
+ * Check if WASM acceleration is enabled
+ */
+export function isWASMAccelerated(): boolean {
+ if (ruvectorModule && typeof ruvectorModule.isWASMAccelerated === 'function') {
+ return ruvectorModule.isWASMAccelerated();
+ }
+ return false;
+}
+
+/**
+ * Create a vector database
+ * Uses ruvector HNSW if available, falls back to brute-force search
+ */
+export async function createVectorDB(dimensions: number = 768): Promise<VectorDB> {
+ await loadRuVector();
+
+ if (ruvectorModule && typeof ruvectorModule.createVectorDB === 'function') {
+ try {
+ return await ruvectorModule.createVectorDB(dimensions);
+ } catch {
+ // Fall back to simple implementation
+ }
+ }
+
+ return new FallbackVectorDB(dimensions);
+}
+
+/**
+ * Generate an embedding for text
+ * Uses ruvector if available, falls back to hash-based embedding
+ */
+export function generateEmbedding(text: string, dimensions: number = 768): Float32Array {
+ if (ruvectorModule && typeof ruvectorModule.generateEmbedding === 'function') {
+ try {
+ return ruvectorModule.generateEmbedding(text, dimensions);
+ } catch {
+ // Fall back to hash-based embedding
+ }
+ }
+
+ return generateHashEmbedding(text, dimensions);
+}
+
+/**
+ * Compute cosine similarity between two vectors
+ */
+export function computeSimilarity(a: Float32Array, b: Float32Array): number {
+ if (ruvectorModule && typeof ruvectorModule.cosineSimilarity === 'function') {
+ try {
+ return ruvectorModule.cosineSimilarity(a, b);
+ } catch {
+ // Fall back to JS implementation
+ }
+ }
+
+ return cosineSimilarity(a, b);
+}
+
+/**
+ * Get status information about the ruvector module
+ */
+export function getStatus(): {
+ available: boolean;
+ wasmAccelerated: boolean;
+ backend: 'ruvector-wasm' | 'ruvector' | 'fallback';
+} {
+ if (!isAvailable) {
+ return {
+ available: false,
+ wasmAccelerated: false,
+ backend: 'fallback',
+ };
+ }
+
+ const wasmAccelerated = isWASMAccelerated();
+ return {
+ available: true,
+ wasmAccelerated,
+ backend: wasmAccelerated ? 'ruvector-wasm' : 'ruvector',
+ };
+}
diff --git a/v3/CLAUDE.md b/v3/CLAUDE.md
new file mode 100644
index 0000000000..483813b62f
--- /dev/null
+++ b/v3/CLAUDE.md
@@ -0,0 +1,573 @@
+# Claude Code Configuration - SPARC Development Environment
+
+## 🚨 AUTOMATIC SWARM ORCHESTRATION
+
+**When starting work on complex tasks, Claude Code MUST automatically:**
+
+1. **Initialize the swarm** using MCP tools
+2. **Spawn concurrent agents** using Claude Code's Task tool
+3. **Coordinate via hooks** and memory
+
+### 🚨 CRITICAL: MCP + Task Tool in SAME Message
+
+**When user says "spawn swarm" or requests complex work, Claude Code MUST in ONE message:**
+1. Call MCP tools to initialize coordination
+2. **IMMEDIATELY** call Task tool to spawn REAL working agents
+3. Both MCP and Task calls must be in the SAME response
+
+**MCP alone does NOT execute work - Task tool agents do the actual work!**
+
+### πŸ”„ Auto-Start Swarm Protocol
+
+When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**
+
+```javascript
+// STEP 1: Initialize swarm coordination via MCP (in parallel with agent spawning)
+mcp__claude-flow__swarm_init({
+ topology: "hierarchical",
+ maxAgents: 15,
+ strategy: "adaptive"
+})
+
+// STEP 2: Spawn agents concurrently using Claude Code's Task tool
+// ALL Task calls MUST be in the SAME message for parallel execution
+Task("Coordinator", "You are the swarm coordinator. Initialize session, coordinate other agents via memory. Run: npx claude-flow@v3alpha hooks session-start", "hierarchical-coordinator")
+Task("Researcher", "Analyze requirements and existing code patterns. Store findings in memory via hooks.", "researcher")
+Task("Architect", "Design implementation approach based on research. Document decisions in memory.", "system-architect")
+Task("Coder", "Implement the solution following architect's design. Coordinate via hooks.", "coder")
+Task("Tester", "Write tests for the implementation. Report coverage via hooks.", "tester")
+Task("Reviewer", "Review code quality and security. Document findings.", "reviewer")
+
+// STEP 3: Batch all todos
+TodoWrite({ todos: [
+ {content: "Initialize swarm coordination", status: "in_progress", activeForm: "Initializing swarm"},
+ {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching requirements"},
+ {content: "Design architecture", status: "pending", activeForm: "Designing architecture"},
+ {content: "Implement solution", status: "pending", activeForm: "Implementing solution"},
+ {content: "Write tests", status: "pending", activeForm: "Writing tests"},
+ {content: "Review and finalize", status: "pending", activeForm: "Reviewing code"}
+]})
+
+// STEP 4: Store swarm state in memory
+mcp__claude-flow__memory_usage({
+ action: "store",
+ namespace: "swarm",
+ key: "current-session",
+ value: JSON.stringify({task: "[user's task]", agents: 6, startedAt: new Date().toISOString()})
+})
+```
+
+### πŸ“‹ Agent Routing by Task Type
+
+**Automatically select agents based on task:**
+
+| Task Type | Required Agents | Topology |
+|-----------|-----------------|----------|
+| Bug Fix | researcher, coder, tester | mesh |
+| New Feature | coordinator, architect, coder, tester, reviewer | hierarchical |
+| Refactoring | architect, coder, reviewer | mesh |
+| Performance | researcher, coder, perf-analyzer | hierarchical |
+| Security Audit | security-manager, reviewer, tester | hierarchical |
+| Documentation | researcher, api-docs | mesh |
+
+### 🎯 Task Complexity Detection
+
+**AUTO-INVOKE SWARM when task involves:**
+- Multiple files (3+)
+- New feature implementation
+- Refactoring across modules
+- API changes with tests
+- Security-related changes
+- Performance optimization
+- Database schema changes
+
+**SKIP SWARM for:**
+- Single file edits
+- Simple bug fixes (1-2 lines)
+- Documentation updates
+- Configuration changes
+- Quick questions/exploration
+
+### πŸ”§ Settings Configuration
+
+The following settings are auto-configured in `.claude/settings.json`:
+
+```json
+{
+ "hooks": {
+ "PreToolUse": [{
+ "matcher": "Task",
+ "commands": ["npx claude-flow@v3alpha hooks pre-task --tool Task"]
+ }],
+ "PostToolUse": [{
+ "matcher": "Task",
+ "commands": ["npx claude-flow@v3alpha hooks post-task --tool Task"]
+ }],
+ "UserPromptSubmit": [{
+ "matcher": ".*",
+ "commands": ["npx claude-flow@v3alpha hooks route-task"]
+ }]
+ },
+ "permissions": {
+ "allow": [
+ "Bash(npx claude-flow:*)",
+ "mcp__claude-flow__*",
+ "mcp__ruv-swarm__*"
+ ]
+ }
+}
+```
+
+## 🚨 CRITICAL: CONCURRENT EXECUTION & FILE MANAGEMENT
+
+**ABSOLUTE RULES**:
+1. ALL operations MUST be concurrent/parallel in a single message
+2. **NEVER save working files, text/mds and tests to the root folder**
+3. ALWAYS organize files in appropriate subdirectories
+4. **USE CLAUDE CODE'S TASK TOOL** for spawning agents concurrently, not just MCP
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**MANDATORY PATTERNS:**
+- **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+- **Task tool (Claude Code)**: ALWAYS spawn ALL agents in ONE message with full instructions
+- **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+- **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+- **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### 🎯 CRITICAL: Claude Code Task Tool for Agent Execution
+
+**Claude Code's Task tool is the PRIMARY way to spawn agents:**
+```javascript
+// βœ… CORRECT: Use Claude Code's Task tool for parallel agent execution
+[Single Message]:
+ Task("Research agent", "Analyze requirements and patterns...", "researcher")
+ Task("Coder agent", "Implement core features...", "coder")
+ Task("Tester agent", "Create comprehensive tests...", "tester")
+ Task("Reviewer agent", "Review code quality...", "reviewer")
+ Task("Architect agent", "Design system architecture...", "system-architect")
+```
+
+**MCP tools are ONLY for coordination setup:**
+- `mcp__claude-flow__swarm_init` - Initialize coordination topology
+- `mcp__claude-flow__agent_spawn` - Define agent types for coordination
+- `mcp__claude-flow__task_orchestrate` - Orchestrate high-level workflows
+
+### πŸ“ File Organization Rules
+
+**NEVER save to root folder. Use these directories:**
+- `/src` - Source code files
+- `/tests` - Test files
+- `/docs` - Documentation and markdown files
+- `/config` - Configuration files
+- `/scripts` - Utility scripts
+- `/examples` - Example code
+
+## Project Configuration
+
+This project is configured with Claude Flow V3:
+- **Topology**: hierarchical
+- **Max Agents**: 15
+- **Memory Backend**: hybrid
+- **HNSW Indexing**: Enabled
+- **Neural Learning**: Enabled
+
+## SPARC Workflow Phases
+
+1. **Specification** - Requirements analysis (`sparc run spec-pseudocode`)
+2. **Pseudocode** - Algorithm design (`sparc run spec-pseudocode`)
+3. **Architecture** - System design (`sparc run architect`)
+4. **Refinement** - TDD implementation (`sparc tdd`)
+5. **Completion** - Integration (`sparc run integration`)
+
+## Code Style & Best Practices
+
+- **Modular Design**: Files under 500 lines
+- **Environment Safety**: Never hardcode secrets
+- **Test-First**: Write tests before implementation
+- **Clean Architecture**: Separate concerns
+- **Documentation**: Keep updated
+
+## πŸš€ Available Agents
+
+### Core Development
+`coder`, `reviewer`, `tester`, `planner`, `researcher`
+
+### Swarm Coordination
+`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`
+
+### Consensus & Distributed
+`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`
+
+### Performance & Optimization
+`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`
+
+### GitHub & Repository
+`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`
+
+### SPARC Methodology
+`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`
+
+### Specialized Development
+`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`
+
+### Testing & Validation
+`tdd-london-swarm`, `production-validator`
+
+## 🎯 Claude Code vs MCP Tools
+
+### Claude Code Handles ALL EXECUTION:
+- **Task tool**: Spawn and run agents concurrently for actual work
+- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)
+- Code generation and programming
+- Bash commands and system operations
+- Implementation work
+- Project navigation and analysis
+- TodoWrite and task management
+- Git operations
+- Package management
+- Testing and debugging
+
+### MCP Tools ONLY COORDINATE:
+- Swarm initialization (topology setup)
+- Agent type definitions (coordination patterns)
+- Task orchestration (high-level planning)
+- Memory management
+- Neural features
+- Performance tracking
+- GitHub integration
+
+**KEY**: MCP coordinates the strategy, Claude Code's Task tool executes with real agents.
+
+## πŸš€ Quick Setup
+
+```bash
+# Add MCP servers (Claude Flow required, others optional)
+claude mcp add claude-flow npx claude-flow@v3alpha mcp start
+claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional: Enhanced coordination
+claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional: Cloud features
+```
+
+## MCP Tool Categories
+
+### Coordination
+`swarm_init`, `agent_spawn`, `task_orchestrate`
+
+### Monitoring
+`swarm_status`, `agent_list`, `agent_metrics`, `task_status`, `task_results`
+
+### Memory & Neural
+`memory_usage`, `neural_status`, `neural_train`, `neural_patterns`
+
+### GitHub Integration
+`github_swarm`, `repo_analyze`, `pr_enhance`, `issue_triage`, `code_review`
+
+### System
+`benchmark_run`, `features_detect`, `swarm_monitor`
+
+## πŸš€ Agent Execution Flow with Claude Code
+
+### The Correct Pattern:
+
+1. **Optional**: Use MCP tools to set up coordination topology
+2. **REQUIRED**: Use Claude Code's Task tool to spawn agents that do actual work
+3. **REQUIRED**: Each agent runs hooks for coordination
+4. **REQUIRED**: Batch all operations in single messages
+
+### Example Full-Stack Development:
+
+```javascript
+// Single message with all agent spawning via Claude Code's Task tool
+[Parallel Agent Execution]:
+ Task("Backend Developer", "Build REST API with Express. Use hooks for coordination.", "backend-dev")
+ Task("Frontend Developer", "Create React UI. Coordinate with backend via memory.", "coder")
+ Task("Database Architect", "Design PostgreSQL schema. Store schema in memory.", "code-analyzer")
+ Task("Test Engineer", "Write Jest tests. Check memory for API contracts.", "tester")
+ Task("DevOps Engineer", "Setup Docker and CI/CD. Document in memory.", "cicd-engineer")
+ Task("Security Auditor", "Review authentication. Report findings via hooks.", "reviewer")
+
+ // All todos batched together
+ TodoWrite { todos: [...8-10 todos...] }
+
+ // All file operations together
+ Write "backend/server.js"
+ Write "frontend/App.jsx"
+ Write "database/schema.sql"
+```
+
+## πŸ“‹ Agent Coordination Protocol
+
+### Every Agent Spawned via Task Tool MUST:
+
+**1️⃣ BEFORE Work:**
+```bash
+npx claude-flow@v3alpha hooks pre-task --description "[task]"
+npx claude-flow@v3alpha hooks session-restore --session-id "swarm-[id]"
+```
+
+**2️⃣ DURING Work:**
+```bash
+npx claude-flow@v3alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
+npx claude-flow@v3alpha hooks notify --message "[what was done]"
+```
+
+**3️⃣ AFTER Work:**
+```bash
+npx claude-flow@v3alpha hooks post-task --task-id "[task]"
+npx claude-flow@v3alpha hooks session-end --export-metrics true
+```
+
+## πŸš€ Swarm Lifecycle Management
+
+### Session Start (AUTOMATIC)
+When beginning ANY development task, Claude Code should:
+
+```javascript
+// 1. Check for existing swarm session
+mcp__claude-flow__swarm_status({})
+
+// 2. If no active swarm, initialize one
+mcp__claude-flow__swarm_init({ topology: "hierarchical", maxAgents: 15 })
+
+// 3. Restore previous context if available
+mcp__claude-flow__memory_usage({ action: "retrieve", namespace: "swarm", key: "last-session" })
+```
+
+### Task Execution (AUTOMATIC)
+For each significant task:
+
+```javascript
+// 1. Create task orchestration
+mcp__claude-flow__task_orchestrate({
+ task: "[task description]",
+ priority: "high",
+ strategy: "adaptive"
+})
+
+// 2. Spawn appropriate agents via Task tool (PARALLEL)
+Task("Agent1", "...", "agent-type")
+Task("Agent2", "...", "agent-type")
+Task("Agent3", "...", "agent-type")
+
+// 3. Monitor progress via MCP
+mcp__claude-flow__swarm_status({ includeAgents: true, includeMetrics: true })
+```
+
+### Session End (AUTOMATIC)
+When task completes or user ends session:
+
+```javascript
+// 1. Save session state
+mcp__claude-flow__memory_usage({
+ action: "store",
+ namespace: "swarm",
+ key: "last-session",
+ value: JSON.stringify({ completedAt: new Date().toISOString(), summary: "..." })
+})
+
+// 2. Export metrics if enabled
+mcp__claude-flow__agent_metrics({})
+
+// 3. Graceful shutdown (only if explicitly requested)
+// mcp__claude-flow__swarm_destroy({ swarmId: "..." })
+```
+
+## 🎯 Concurrent Execution Examples
+
+### βœ… CORRECT WORKFLOW: MCP Coordinates, Claude Code Executes
+
+```javascript
+// Step 1: MCP tools set up coordination (optional, for complex tasks)
+[Single Message - Coordination Setup]:
+ mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 15 }
+ mcp__claude-flow__agent_spawn { type: "researcher" }
+ mcp__claude-flow__agent_spawn { type: "coder" }
+ mcp__claude-flow__agent_spawn { type: "tester" }
+
+// Step 2: Claude Code Task tool spawns ACTUAL agents that do the work
+[Single Message - Parallel Agent Execution]:
+ // Claude Code's Task tool spawns real agents concurrently
+ Task("Research agent", "Analyze API requirements and best practices. Check memory for prior decisions.", "researcher")
+ Task("Coder agent", "Implement REST endpoints with authentication. Coordinate via hooks.", "coder")
+ Task("Database agent", "Design and implement database schema. Store decisions in memory.", "code-analyzer")
+ Task("Tester agent", "Create comprehensive test suite with 90% coverage.", "tester")
+ Task("Reviewer agent", "Review code quality and security. Document findings.", "reviewer")
+
+ // Batch ALL todos in ONE call
+ TodoWrite { todos: [
+ {id: "1", content: "Research API patterns", status: "in_progress", priority: "high"},
+ {id: "2", content: "Design database schema", status: "in_progress", priority: "high"},
+ {id: "3", content: "Implement authentication", status: "pending", priority: "high"},
+ {id: "4", content: "Build REST endpoints", status: "pending", priority: "high"},
+ {id: "5", content: "Write unit tests", status: "pending", priority: "medium"},
+ {id: "6", content: "Integration tests", status: "pending", priority: "medium"},
+ {id: "7", content: "API documentation", status: "pending", priority: "low"},
+ {id: "8", content: "Performance optimization", status: "pending", priority: "low"}
+ ]}
+
+ // Parallel file operations
+ Bash "mkdir -p app/{src,tests,docs,config}"
+ Write "app/package.json"
+ Write "app/src/server.js"
+ Write "app/tests/server.test.js"
+ Write "app/docs/API.md"
+```
+
+### ❌ WRONG (Multiple Messages):
+```javascript
+Message 1: mcp__claude-flow__swarm_init
+Message 2: Task("agent 1")
+Message 3: TodoWrite { todos: [single todo] }
+Message 4: Write "file.js"
+// This breaks parallel coordination!
+```
+
+## V3 Performance Targets
+
+- **2.49x-7.47x** Flash Attention speedup
+- **150x-12,500x** search improvements with HNSW
+- **50-75%** memory reduction with quantization
+- **Sub-100ms** MCP response times
+
+## πŸͺ V3 Hooks System (26 Hooks)
+
+Claude Flow V3 provides 26 hooks for comprehensive agent coordination and self-learning.
+
+### Hook Categories
+
+| Category | Hooks | Purpose |
+|----------|-------|---------|
+| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |
+| **Routing** | `route`, `metrics`, `list` | Task analysis |
+| **Intelligence** | `explain`, `pretrain`, `build-agents`, `transfer`, `init` | Neural learning |
+| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |
+| **Learning** | `trajectory-start`, `trajectory-step`, `trajectory-end` | Reinforcement learning |
+| **Patterns** | `pattern-store`, `pattern-search`, `stats`, `learn`, `attention` | Memory & search |
+
+### Essential Hook Commands
+
+```bash
+# Core hooks for tool coordination
+npx claude-flow@v3alpha hooks pre-task --description "[task]"
+npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true
+npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns
+
+# Session management
+npx claude-flow@v3alpha hooks session-start --session-id "[id]"
+npx claude-flow@v3alpha hooks session-end --export-metrics true --persist-patterns
+npx claude-flow@v3alpha hooks session-restore --session-id "[id]"
+
+# Intelligence routing
+npx claude-flow@v3alpha hooks route --task "[task]" --include-explanation
+npx claude-flow@v3alpha hooks explain --topic "[topic]" --depth comprehensive
+
+# Neural learning
+npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10
+npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester --config-format yaml
+
+# Trajectory learning (reinforcement)
+npx claude-flow@v3alpha hooks intelligence trajectory-start --session "[session]"
+npx claude-flow@v3alpha hooks intelligence trajectory-step --action "[action]" --reward "[reward]"
+npx claude-flow@v3alpha hooks intelligence trajectory-end --verdict success
+
+# Pattern storage (HNSW-indexed)
+npx claude-flow@v3alpha hooks intelligence pattern-store --pattern "[pattern]" --embedding "[json]"
+npx claude-flow@v3alpha hooks intelligence pattern-search --query "[query]" --limit 10
+
+# Learning stats & attention
+npx claude-flow@v3alpha hooks intelligence stats
+npx claude-flow@v3alpha hooks intelligence attention --focus "[task]"
+```
+
+### Intelligence System (RuVector)
+
+V3 includes the RuVector Intelligence System with:
+- **SONA**: Self-Optimizing Neural Architecture
+- **MoE**: Mixture of Experts for specialized routing
+- **HNSW**: 150x faster pattern search
+- **EWC++**: Elastic Weight Consolidation (prevents forgetting)
+- **Flash Attention**: 2.49x-7.47x speedup
+
+The 4-step intelligence pipeline:
+1. **RETRIEVE** - Fetch relevant patterns via HNSW
+2. **JUDGE** - Evaluate with verdicts (success/failure)
+3. **DISTILL** - Extract key learnings via LoRA
+4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++
+
+### Auto-Configured Hooks
+
+The init system configures these hooks in `.claude/settings.json`:
+
+```json
+{
+ "hooks": {
+ "PreToolUse": [
+ { "matcher": "Task", "commands": ["npx claude-flow@v3alpha hooks pre-task --tool Task"] }
+ ],
+ "PostToolUse": [
+ { "matcher": "Task", "commands": ["npx claude-flow@v3alpha hooks post-task --tool Task --train-patterns"] }
+ ],
+ "UserPromptSubmit": [
+ { "matcher": ".*", "commands": ["npx claude-flow@v3alpha hooks route-task --analyze-complexity"] }
+ ],
+ "SessionStart": [
+ { "commands": ["npx claude-flow@v3alpha hooks session-start --load-context"] }
+ ]
+ }
+}
+```
+
+### Agent Coordination via Hooks
+
+Every spawned agent should use hooks for coordination:
+
+```javascript
+// In agent prompt instructions
+Task("Coder", `
+ BEFORE starting: npx claude-flow@v3alpha hooks pre-task --description "Implement feature X"
+
+ DURING work:
+ - After each file edit: npx claude-flow@v3alpha hooks post-edit --file "[file]"
+ - To notify others: npx claude-flow@v3alpha hooks notify --message "[update]"
+
+ AFTER completing: npx claude-flow@v3alpha hooks post-task --success true
+`, "coder")
+```
+
+## Advanced Features (V3)
+
+- πŸš€ Automatic Topology Selection
+- ⚑ Parallel Execution (2.8-4.4x speed)
+- 🧠 Neural Training with ReasoningBank
+- πŸ“Š Bottleneck Analysis
+- πŸ€– Smart Auto-Spawning
+- πŸ›‘οΈ Self-Healing Workflows
+- πŸ’Ύ Cross-Session Memory with AgentDB
+- πŸ”— GitHub Integration
+- πŸ” Security-Hardened Architecture
+
+## Integration Tips
+
+1. Start with basic swarm init
+2. Scale agents gradually
+3. Use memory for context
+4. Monitor progress regularly
+5. Train patterns from success
+6. Enable hooks automation
+7. Use GitHub tools first
+
+## Support
+
+- Documentation: https://github.com/ruvnet/claude-flow
+- Issues: https://github.com/ruvnet/claude-flow/issues
+
+---
+
+Remember: **Claude Flow coordinates, Claude Code creates!**
+
+# important-instruction-reminders
+Do what has been asked; nothing more, nothing less.
+NEVER create files unless they're absolutely necessary for achieving your goal.
+ALWAYS prefer editing an existing file to creating a new one.
+NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
+Never save working files, text/mds and tests to the root folder.
diff --git a/v3/implementation/adrs/ADR-017-ruvector-integration.md b/v3/implementation/adrs/ADR-017-ruvector-integration.md
new file mode 100644
index 0000000000..aaf3dce71d
--- /dev/null
+++ b/v3/implementation/adrs/ADR-017-ruvector-integration.md
@@ -0,0 +1,1006 @@
+# ADR-017: RuVector Integration Architecture
+
+**Status:** Proposed
+**Date:** 2026-01-07
+**Author:** System Architecture Designer
+**Version:** 1.0.0
+
+## Context
+
+The `@claude-flow/cli` package requires integration with `ruvector` for advanced code intelligence features:
+
+1. **Q-Learning Agent Router** - ML-based task routing (80%+ accuracy)
+2. **AST Analysis** - Symbol extraction and complexity metrics
+3. **Diff Classification** - Change risk scoring
+4. **Coverage Routing** - Test-aware agent selection
+5. **Graph Analysis** - Code boundaries (MinCut/Louvain)
+
+These features are unique to ruvector and complement claude-flow's existing capabilities without duplicating functionality already present in `@claude-flow/embeddings` or `@claude-flow/memory`.
+
+## Decision
+
+Implement ruvector as an **OPTIONAL dependency** with graceful fallback, following the existing patterns in `@claude-flow/cli`.
+
+### Design Principles
+
+1. **Optional by Default** - ruvector is not required; all commands degrade gracefully
+2. **Consistent CLI Patterns** - Match existing command structure (`agent`, `hooks`, `neural`)
+3. **MCP-First Architecture** - CLI wraps MCP tools per ADR-005
+4. **Lazy Loading** - Only load ruvector modules when needed
+5. **Clear Error Messages** - Helpful guidance when ruvector is missing
+
+---
+
+## File Structure
+
+```
+v3/@claude-flow/cli/src/
+β”œβ”€β”€ commands/
+β”‚ β”œβ”€β”€ route.ts # NEW: Q-Learning routing command
+β”‚ β”œβ”€β”€ analyze.ts # NEW: AST/Diff/Graph analysis commands
+β”‚ └── index.ts # Updated: register new commands
+β”œβ”€β”€ ruvector/
+β”‚ β”œβ”€β”€ index.ts # Lazy loader with availability check
+β”‚ β”œβ”€β”€ types.ts # TypeScript interfaces for ruvector
+β”‚ β”œβ”€β”€ availability.ts # Package detection utilities
+β”‚ └── adapters/
+β”‚ β”œβ”€β”€ router-adapter.ts # Wraps hooks_route, hooks_route_enhanced
+β”‚ β”œβ”€β”€ ast-adapter.ts # Wraps hooks_ast_analyze, hooks_ast_complexity
+β”‚ β”œβ”€β”€ diff-adapter.ts # Wraps hooks_diff_analyze, hooks_diff_classify
+β”‚ β”œβ”€β”€ coverage-adapter.ts # Wraps hooks_coverage_route
+β”‚ └── graph-adapter.ts # Wraps hooks_graph_mincut, hooks_graph_cluster
+β”œβ”€β”€ mcp-tools/
+β”‚ └── ruvector-tools.ts # NEW: MCP tool definitions for ruvector
+└── package.json # Updated: optionalDependencies
+```
+
+---
+
+## Interface Definitions
+
+### 1. RuVector Availability Interface
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/availability.ts
+
+/**
+ * RuVector availability state
+ */
+export interface RuVectorStatus {
+ available: boolean;
+ version?: string;
+ features: RuVectorFeatures;
+ error?: string;
+}
+
+export interface RuVectorFeatures {
+ qLearningRouter: boolean;
+ astAnalysis: boolean;
+ diffClassification: boolean;
+ coverageRouting: boolean;
+ graphAnalysis: boolean;
+}
+
+/**
+ * Check if ruvector is installed and available
+ * Uses lazy evaluation and caching
+ */
+export async function checkRuVectorAvailability(): Promise<RuVectorStatus>;
+
+/**
+ * Get human-readable installation instructions
+ */
+export function getInstallInstructions(): string;
+
+/**
+ * Require ruvector feature, throw helpful error if unavailable
+ */
+export async function requireRuVector(feature: keyof RuVectorFeatures): Promise<void>;
+```
+
+### 2. Router Adapter Interface
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/adapters/router-adapter.ts
+
+export interface RouteRequest {
+ task: string;
+ context?: string;
+ options?: {
+ useQLearning?: boolean;
+ useCoverageAware?: boolean;
+ includeExplanation?: boolean;
+ maxAgents?: number;
+ };
+}
+
+export interface RouteResult {
+ recommendedAgents: AgentRecommendation[];
+ confidence: number;
+ reasoning: string;
+ learningFeedback?: {
+ modelVersion: string;
+ trainingEpisodes: number;
+ };
+}
+
+export interface AgentRecommendation {
+ type: string;
+ score: number;
+ rationale: string;
+ capabilities: string[];
+}
+
+/**
+ * Route task using Q-Learning model
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function routeWithQLearning(request: RouteRequest): Promise<RouteResult>;
+
+/**
+ * Route with coverage awareness
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function routeWithCoverage(request: RouteRequest): Promise<RouteResult>;
+```
+
+### 3. AST Adapter Interface
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/adapters/ast-adapter.ts
+
+export interface ASTAnalysisRequest {
+ path: string;
+ options?: {
+ includeSymbols?: boolean;
+ includeComplexity?: boolean;
+ includeDependencies?: boolean;
+ recursive?: boolean;
+ };
+}
+
+export interface ASTAnalysisResult {
+ files: FileAnalysis[];
+ summary: {
+ totalFiles: number;
+ totalFunctions: number;
+ totalClasses: number;
+ avgComplexity: number;
+ maxComplexity: number;
+ };
+}
+
+export interface FileAnalysis {
+ path: string;
+ language: string;
+ symbols: Symbol[];
+ complexity: ComplexityMetrics;
+ dependencies: string[];
+}
+
+export interface Symbol {
+ name: string;
+ type: 'function' | 'class' | 'interface' | 'variable' | 'type';
+ line: number;
+ exported: boolean;
+ parameters?: string[];
+}
+
+export interface ComplexityMetrics {
+ cyclomatic: number;
+ cognitive: number;
+ linesOfCode: number;
+ maintainabilityIndex: number;
+}
+
+/**
+ * Analyze AST of files at path
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function analyzeAST(request: ASTAnalysisRequest): Promise<ASTAnalysisResult>;
+
+/**
+ * Get complexity metrics for path
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function getComplexity(path: string): Promise<ComplexityMetrics>;
+```
+
+### 4. Diff Adapter Interface
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/adapters/diff-adapter.ts
+
+export interface DiffAnalysisRequest {
+ diff?: string;
+ baseBranch?: string;
+ targetBranch?: string;
+ options?: {
+ includeRisk?: boolean;
+ includeClassification?: boolean;
+ };
+}
+
+export interface DiffAnalysisResult {
+ classification: DiffClassification;
+ riskScore: number;
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
+ affectedFiles: AffectedFile[];
+ recommendations: string[];
+}
+
+export type DiffClassification =
+ | 'feature'
+ | 'bugfix'
+ | 'refactor'
+ | 'documentation'
+ | 'test'
+ | 'config'
+ | 'dependency'
+ | 'breaking';
+
+export interface AffectedFile {
+ path: string;
+ changeType: 'added' | 'modified' | 'deleted' | 'renamed';
+ additions: number;
+ deletions: number;
+ riskContribution: number;
+}
+
+/**
+ * Analyze diff and classify changes
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function analyzeDiff(request: DiffAnalysisRequest): Promise<DiffAnalysisResult>;
+
+/**
+ * Get risk score for diff
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function classifyDiffRisk(diff: string): Promise<number>;
+```
+
+### 5. Graph Adapter Interface
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/adapters/graph-adapter.ts
+
+export interface GraphAnalysisRequest {
+ path: string;
+ options?: {
+ algorithm?: 'mincut' | 'louvain' | 'both';
+ minModuleSize?: number;
+ resolution?: number;
+ };
+}
+
+export interface GraphAnalysisResult {
+ modules: CodeModule[];
+ boundaries: Boundary[];
+ metrics: GraphMetrics;
+}
+
+export interface CodeModule {
+ id: string;
+ name: string;
+ files: string[];
+ cohesion: number;
+ coupling: number;
+}
+
+export interface Boundary {
+ from: string;
+ to: string;
+ strength: number;
+ suggestedSplit: boolean;
+}
+
+export interface GraphMetrics {
+ modularity: number;
+ avgCohesion: number;
+ avgCoupling: number;
+ suggestedBoundaries: number;
+}
+
+/**
+ * Analyze code boundaries using graph algorithms
+ * @throws RuVectorNotAvailableError if ruvector not installed
+ */
+export async function analyzeGraphBoundaries(request: GraphAnalysisRequest): Promise<GraphAnalysisResult>;
+```
+
+---
+
+## CLI Command Definitions
+
+### 1. Route Command
+
+```typescript
+// v3/@claude-flow/cli/src/commands/route.ts
+
+export const routeCommand: Command = {
+ name: 'route',
+ description: 'Route tasks to optimal agents using ML-based routing',
+ options: [
+ {
+ name: 'task',
+ short: 't',
+ description: 'Task description to route',
+ type: 'string',
+ required: true
+ },
+ {
+ name: 'q-learning',
+ short: 'q',
+ description: 'Use Q-Learning model for routing (requires ruvector)',
+ type: 'boolean',
+ default: false
+ },
+ {
+ name: 'coverage-aware',
+ short: 'c',
+ description: 'Use test coverage data for routing (requires ruvector)',
+ type: 'boolean',
+ default: false
+ },
+ {
+ name: 'explain',
+ short: 'e',
+ description: 'Include detailed explanation of routing decision',
+ type: 'boolean',
+ default: false
+ },
+ {
+ name: 'max-agents',
+ short: 'm',
+ description: 'Maximum number of agent recommendations',
+ type: 'number',
+ default: 3
+ }
+ ],
+ examples: [
+ {
+ command: 'claude-flow route -t "Implement user authentication" --q-learning',
+ description: 'Route with Q-Learning model'
+ },
+ {
+ command: 'claude-flow route -t "Fix login bug" --coverage-aware',
+ description: 'Route with coverage awareness'
+ }
+ ],
+ action: routeAction
+};
+```
+
+### 2. Analyze Command
+
+```typescript
+// v3/@claude-flow/cli/src/commands/analyze.ts
+
+export const analyzeCommand: Command = {
+ name: 'analyze',
+ description: 'Code analysis tools (AST, diff, boundaries)',
+ subcommands: [astSubcommand, diffSubcommand, boundariesSubcommand],
+ options: [],
+ action: analyzeHelpAction
+};
+
+const astSubcommand: Command = {
+ name: 'ast',
+ description: 'Analyze code AST for symbols and complexity',
+ options: [
+ {
+ name: 'path',
+ short: 'p',
+ description: 'Path to analyze (file or directory)',
+ type: 'string',
+ required: true
+ },
+ {
+ name: 'recursive',
+ short: 'r',
+ description: 'Recursively analyze directories',
+ type: 'boolean',
+ default: true
+ },
+ {
+ name: 'complexity',
+ description: 'Include complexity metrics',
+ type: 'boolean',
+ default: true
+ },
+ {
+ name: 'symbols',
+ description: 'Include symbol extraction',
+ type: 'boolean',
+ default: true
+ }
+ ],
+ examples: [
+ { command: 'claude-flow analyze ast -p src/', description: 'Analyze src directory' },
+ { command: 'claude-flow analyze ast -p src/api.ts --complexity', description: 'Get complexity for file' }
+ ],
+ action: astAction
+};
+
+const diffSubcommand: Command = {
+ name: 'diff',
+ description: 'Analyze and classify code diffs',
+ options: [
+ {
+ name: 'risk',
+ short: 'r',
+ description: 'Include risk assessment',
+ type: 'boolean',
+ default: true
+ },
+ {
+ name: 'base',
+ short: 'b',
+ description: 'Base branch for comparison',
+ type: 'string',
+ default: 'main'
+ },
+ {
+ name: 'target',
+ description: 'Target branch for comparison',
+ type: 'string'
+ },
+ {
+ name: 'stdin',
+ description: 'Read diff from stdin',
+ type: 'boolean',
+ default: false
+ }
+ ],
+ examples: [
+ { command: 'claude-flow analyze diff --risk', description: 'Analyze current diff with risk' },
+ { command: 'claude-flow analyze diff --base main --target feature', description: 'Compare branches' },
+ { command: 'git diff | claude-flow analyze diff --stdin --risk', description: 'Pipe diff from git' }
+ ],
+ action: diffAction
+};
+
+const boundariesSubcommand: Command = {
+ name: 'boundaries',
+ description: 'Detect code boundaries using graph algorithms',
+ options: [
+ {
+ name: 'path',
+ short: 'p',
+ description: 'Path to analyze',
+ type: 'string',
+ default: '.'
+ },
+ {
+ name: 'algorithm',
+ short: 'a',
+ description: 'Algorithm: mincut, louvain, or both',
+ type: 'string',
+ choices: ['mincut', 'louvain', 'both'],
+ default: 'both'
+ },
+ {
+ name: 'min-module-size',
+ description: 'Minimum files per detected module',
+ type: 'number',
+ default: 3
+ }
+ ],
+ examples: [
+ { command: 'claude-flow analyze boundaries -p src/', description: 'Detect boundaries in src' },
+ { command: 'claude-flow analyze boundaries -a louvain', description: 'Use Louvain algorithm' }
+ ],
+ action: boundariesAction
+};
+```
+
+---
+
+## Error Handling Strategy
+
+### 1. RuVector Not Available Error
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/errors.ts
+
+export class RuVectorNotAvailableError extends CLIError {
+ constructor(feature: string) {
+ super(
+ `RuVector is required for ${feature} but is not installed.`,
+ 'RUVECTOR_NOT_AVAILABLE',
+ 1,
+ {
+ feature,
+ suggestion: 'Install with: npm install ruvector',
+ documentation: 'https://github.com/ruvnet/ruvector'
+ }
+ );
+ this.name = 'RuVectorNotAvailableError';
+ }
+}
+
+export class RuVectorFeatureDisabledError extends CLIError {
+ constructor(feature: string, reason: string) {
+ super(
+ `RuVector feature "${feature}" is disabled: ${reason}`,
+ 'RUVECTOR_FEATURE_DISABLED',
+ 1
+ );
+ this.name = 'RuVectorFeatureDisabledError';
+ }
+}
+```
+
+### 2. Graceful Degradation Pattern
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/availability.ts
+
+let cachedStatus: RuVectorStatus | null = null;
+
+export async function checkRuVectorAvailability(): Promise<RuVectorStatus> {
+ if (cachedStatus) return cachedStatus;
+
+ try {
+ // Attempt dynamic import
+ const ruvector = await import('ruvector');
+
+ cachedStatus = {
+ available: true,
+ version: ruvector.version ?? 'unknown',
+ features: {
+ qLearningRouter: typeof ruvector.hooks_route === 'function',
+ astAnalysis: typeof ruvector.hooks_ast_analyze === 'function',
+ diffClassification: typeof ruvector.hooks_diff_analyze === 'function',
+ coverageRouting: typeof ruvector.hooks_coverage_route === 'function',
+ graphAnalysis: typeof ruvector.hooks_graph_mincut === 'function',
+ }
+ };
+ } catch (error) {
+ cachedStatus = {
+ available: false,
+ features: {
+ qLearningRouter: false,
+ astAnalysis: false,
+ diffClassification: false,
+ coverageRouting: false,
+ graphAnalysis: false,
+ },
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+
+ return cachedStatus;
+}
+
+export function getInstallInstructions(): string {
+ return `
+RuVector provides advanced code intelligence features:
+ - Q-Learning agent routing (80%+ accuracy)
+ - AST analysis and complexity metrics
+ - Diff classification and risk scoring
+ - Coverage-aware routing
+ - Graph-based boundary detection
+
+Install with:
+ npm install ruvector
+
+Or add as optional dependency:
+ npm install ruvector --save-optional
+
+Learn more: https://github.com/ruvnet/ruvector
+`.trim();
+}
+
+export async function requireRuVector(feature: keyof RuVectorFeatures): Promise<void> {
+ const status = await checkRuVectorAvailability();
+
+ if (!status.available) {
+ throw new RuVectorNotAvailableError(feature);
+ }
+
+ if (!status.features[feature]) {
+ throw new RuVectorFeatureDisabledError(
+ feature,
+ `Your version of ruvector (${status.version}) does not support this feature.`
+ );
+ }
+}
+```
+
+### 3. CLI Error Display
+
+```typescript
+// In command action handlers
+
+async function routeAction(ctx: CommandContext): Promise<CommandResult> {
+ const useQLearning = ctx.flags['q-learning'] as boolean;
+ const useCoverageAware = ctx.flags['coverage-aware'] as boolean;
+
+ // Check if ruvector features are needed
+ if (useQLearning || useCoverageAware) {
+ try {
+ const feature = useQLearning ? 'qLearningRouter' : 'coverageRouting';
+ await requireRuVector(feature);
+ } catch (error) {
+ if (error instanceof RuVectorNotAvailableError) {
+ output.printError(error.message);
+ output.writeln();
+ output.printBox(getInstallInstructions(), 'Install RuVector');
+ output.writeln();
+ output.printInfo('Falling back to default agent routing...');
+
+ // Fall back to default routing
+ return fallbackRoute(ctx);
+ }
+ throw error;
+ }
+ }
+
+ // Continue with ruvector-powered routing
+ // ...
+}
+```
+
+---
+
+## Integration Points with RuVector
+
+### 1. MCP Tool Definitions
+
+```typescript
+// v3/@claude-flow/cli/src/mcp-tools/ruvector-tools.ts
+
+import type { MCPTool } from './types.js';
+
+export const ruvectorTools: MCPTool[] = [
+ {
+ name: 'ruvector/route',
+ description: 'Route task to optimal agents using Q-Learning',
+ category: 'ruvector',
+ version: '1.0.0',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ task: { type: 'string', description: 'Task to route' },
+ useQLearning: { type: 'boolean', default: true },
+ useCoverageAware: { type: 'boolean', default: false },
+ maxAgents: { type: 'number', default: 3 }
+ },
+ required: ['task']
+ },
+ handler: async (input) => {
+ const adapter = await import('../ruvector/adapters/router-adapter.js');
+ return adapter.routeWithQLearning({
+ task: input.task as string,
+ options: {
+ useQLearning: input.useQLearning as boolean,
+ useCoverageAware: input.useCoverageAware as boolean,
+ maxAgents: input.maxAgents as number
+ }
+ });
+ }
+ },
+ {
+ name: 'ruvector/analyze-ast',
+ description: 'Analyze code AST for symbols and complexity',
+ category: 'ruvector',
+ version: '1.0.0',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to analyze' },
+ recursive: { type: 'boolean', default: true },
+ includeComplexity: { type: 'boolean', default: true },
+ includeSymbols: { type: 'boolean', default: true }
+ },
+ required: ['path']
+ },
+ handler: async (input) => {
+ const adapter = await import('../ruvector/adapters/ast-adapter.js');
+ return adapter.analyzeAST({
+ path: input.path as string,
+ options: {
+ recursive: input.recursive as boolean,
+ includeComplexity: input.includeComplexity as boolean,
+ includeSymbols: input.includeSymbols as boolean
+ }
+ });
+ }
+ },
+ {
+ name: 'ruvector/analyze-diff',
+ description: 'Analyze and classify code diffs with risk scoring',
+ category: 'ruvector',
+ version: '1.0.0',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ diff: { type: 'string', description: 'Diff content' },
+ baseBranch: { type: 'string', default: 'main' },
+ targetBranch: { type: 'string' },
+ includeRisk: { type: 'boolean', default: true }
+ }
+ },
+ handler: async (input) => {
+ const adapter = await import('../ruvector/adapters/diff-adapter.js');
+ return adapter.analyzeDiff({
+ diff: input.diff as string,
+ baseBranch: input.baseBranch as string,
+ targetBranch: input.targetBranch as string,
+ options: {
+ includeRisk: input.includeRisk as boolean
+ }
+ });
+ }
+ },
+ {
+ name: 'ruvector/analyze-boundaries',
+ description: 'Detect code boundaries using graph algorithms',
+ category: 'ruvector',
+ version: '1.0.0',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to analyze' },
+ algorithm: {
+ type: 'string',
+ enum: ['mincut', 'louvain', 'both'],
+ default: 'both'
+ },
+ minModuleSize: { type: 'number', default: 3 }
+ },
+ required: ['path']
+ },
+ handler: async (input) => {
+ const adapter = await import('../ruvector/adapters/graph-adapter.js');
+ return adapter.analyzeGraphBoundaries({
+ path: input.path as string,
+ options: {
+ algorithm: input.algorithm as 'mincut' | 'louvain' | 'both',
+ minModuleSize: input.minModuleSize as number
+ }
+ });
+ }
+ }
+];
+```
+
+### 2. Lazy Loading Pattern
+
+```typescript
+// v3/@claude-flow/cli/src/ruvector/index.ts
+
+/**
+ * RuVector Integration Module
+ *
+ * Provides lazy-loaded access to ruvector features with graceful fallback.
+ * All imports are dynamic to avoid build failures when ruvector is not installed.
+ */
+
+export { checkRuVectorAvailability, requireRuVector, getInstallInstructions } from './availability.js';
+export { RuVectorNotAvailableError, RuVectorFeatureDisabledError } from './errors.js';
+
+// Re-export types (these are safe - no runtime dependency)
+export type * from './types.js';
+
+// Lazy adapter exports
+export async function getRouterAdapter() {
+ await requireRuVector('qLearningRouter');
+ return import('./adapters/router-adapter.js');
+}
+
+export async function getASTAdapter() {
+ await requireRuVector('astAnalysis');
+ return import('./adapters/ast-adapter.js');
+}
+
+export async function getDiffAdapter() {
+ await requireRuVector('diffClassification');
+ return import('./adapters/diff-adapter.js');
+}
+
+export async function getCoverageAdapter() {
+ await requireRuVector('coverageRouting');
+ return import('./adapters/coverage-adapter.js');
+}
+
+export async function getGraphAdapter() {
+ await requireRuVector('graphAnalysis');
+ return import('./adapters/graph-adapter.js');
+}
+```
+
+---
+
+## Package.json Updates
+
+```json
+{
+ "name": "@claude-flow/cli",
+ "version": "3.0.0-alpha.16",
+ "optionalDependencies": {
+ "ruvector": "^0.1.95"
+ },
+ "peerDependencies": {
+ "ruvector": "^0.1.95"
+ },
+ "peerDependenciesMeta": {
+ "ruvector": {
+ "optional": true
+ }
+ }
+}
+```
+
+---
+
+## Command Index Updates
+
+```typescript
+// v3/@claude-flow/cli/src/commands/index.ts
+
+// Existing imports...
+import { routeCommand } from './route.js';
+import { analyzeCommand } from './analyze.js';
+
+// Update commands array
+export const commands: Command[] = [
+ // ... existing commands
+ routeCommand,
+ analyzeCommand,
+];
+```
+
+---
+
+## Implementation Phases
+
+### Phase 1: Core Infrastructure (Day 1)
+
+1. Create `/ruvector/availability.ts` - Package detection
+2. Create `/ruvector/errors.ts` - Error types
+3. Create `/ruvector/types.ts` - TypeScript interfaces
+4. Create `/ruvector/index.ts` - Lazy loader
+5. Update `package.json` - Optional dependency
+
+### Phase 2: Route Command (Day 1-2)
+
+1. Create `/commands/route.ts` - CLI command
+2. Create `/ruvector/adapters/router-adapter.ts` - Q-Learning adapter
+3. Create `/ruvector/adapters/coverage-adapter.ts` - Coverage adapter
+4. Add MCP tools to `/mcp-tools/ruvector-tools.ts`
+5. Update command index
+
+### Phase 3: Analyze Command (Day 2-3)
+
+1. Create `/commands/analyze.ts` - CLI command with subcommands
+2. Create `/ruvector/adapters/ast-adapter.ts` - AST adapter
+3. Create `/ruvector/adapters/diff-adapter.ts` - Diff adapter
+4. Create `/ruvector/adapters/graph-adapter.ts` - Graph adapter
+5. Add MCP tools
+
+### Phase 4: Testing & Documentation (Day 3-4)
+
+1. Unit tests for availability detection
+2. Integration tests for adapters
+3. Update CLI help text
+4. Update README with ruvector features
+
+---
+
+## Testing Strategy
+
+### 1. Availability Tests
+
+```typescript
+// v3/@claude-flow/cli/tests/ruvector/availability.test.ts
+
+import { describe, it, expect, vi } from 'vitest';
+import { checkRuVectorAvailability } from '../../src/ruvector/availability.js';
+
+describe('RuVector Availability', () => {
+ it('should detect when ruvector is not installed', async () => {
+ vi.mock('ruvector', () => {
+ throw new Error('Cannot find module');
+ });
+
+ const status = await checkRuVectorAvailability();
+ expect(status.available).toBe(false);
+ expect(status.error).toBeDefined();
+ });
+
+ it('should detect available features', async () => {
+ vi.mock('ruvector', () => ({
+ hooks_route: vi.fn(),
+ hooks_ast_analyze: vi.fn(),
+ version: '0.1.95'
+ }));
+
+ const status = await checkRuVectorAvailability();
+ expect(status.available).toBe(true);
+ expect(status.features.qLearningRouter).toBe(true);
+ expect(status.features.astAnalysis).toBe(true);
+ });
+});
+```
+
+### 2. Command Tests
+
+```typescript
+// v3/@claude-flow/cli/tests/commands/route.test.ts
+
+import { describe, it, expect, vi } from 'vitest';
+import { routeCommand } from '../../src/commands/route.js';
+
+describe('Route Command', () => {
+ it('should show helpful error when ruvector not available', async () => {
+ const ctx = {
+ args: [],
+ flags: { task: 'Build API', 'q-learning': true },
+ interactive: false,
+ cwd: process.cwd()
+ };
+
+ // Mock ruvector as unavailable
+ vi.mock('../../src/ruvector/availability.js', () => ({
+ requireRuVector: vi.fn().mockRejectedValue(
+ new RuVectorNotAvailableError('qLearningRouter')
+ )
+ }));
+
+ const result = await routeCommand.action!(ctx);
+ expect(result.success).toBe(true); // Falls back gracefully
+ });
+});
+```
+
+---
+
+## Consequences
+
+### Positive
+
+1. **Zero breaking changes** - ruvector is optional
+2. **Enhanced capabilities** - Q-Learning routing, AST analysis, etc.
+3. **Clean separation** - ruvector code isolated in `/ruvector/`
+4. **Consistent UX** - Follows existing CLI patterns
+5. **MCP-first** - All features available via MCP tools
+
+### Negative
+
+1. **Increased complexity** - More code to maintain
+2. **Optional dependency** - Users may not discover features
+3. **Version coupling** - Must track ruvector API changes
+
+### Neutral
+
+1. **Bundle size unchanged** - Lazy loading prevents bloat
+2. **Build unaffected** - Optional dependency won't break builds
+
+---
+
+## References
+
+- ADR-005: MCP-First API Design
+- ADR-004: Plugin-Based Architecture
+- RuVector Documentation: https://github.com/ruvnet/ruvector
+- Existing hooks command: `/commands/hooks.ts`
+- Existing neural command: `/commands/neural.ts`
+
+---
+
+## Appendix: RuVector Function Mapping
+
+| RuVector Function | CLI Command | MCP Tool |
+|-------------------|-------------|----------|
+| `hooks_route` | `route --q-learning` | `ruvector/route` |
+| `hooks_route_enhanced` | `route --q-learning --explain` | `ruvector/route` |
+| `hooks_coverage_route` | `route --coverage-aware` | `ruvector/route` |
+| `hooks_ast_analyze` | `analyze ast <path>` | `ruvector/analyze-ast` |
+| `hooks_ast_complexity` | `analyze ast --complexity` | `ruvector/analyze-ast` |
+| `hooks_diff_analyze` | `analyze diff` | `ruvector/analyze-diff` |
+| `hooks_diff_classify` | `analyze diff --risk` | `ruvector/analyze-diff` |
+| `hooks_graph_mincut` | `analyze boundaries -a mincut` | `ruvector/analyze-boundaries` |
+| `hooks_graph_cluster` | `analyze boundaries -a louvain` | `ruvector/analyze-boundaries` |