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

rUvb1980dd883c5
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/ast-analyzer.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/ast-analyzer.test.ts
new file mode 100644
index 0000000000..7f9bfb0b75
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/ast-analyzer.test.ts
@@ -0,0 +1,422 @@
+/**
+ * AST Analyzer Tests
+ *
+ * Tests for the AST analysis functionality.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { ASTAnalyzer, createASTAnalyzer, type ASTAnalysis } from '../../src/ruvector/ast-analyzer';
+
+// Mock the @ruvector/ast module
+vi.mock('@ruvector/ast', () => ({
+ createASTAnalyzer: vi.fn(() => null),
+}));
+
+describe('ASTAnalyzer', () => {
+ let analyzer: ASTAnalyzer;
+
+ beforeEach(() => {
+ analyzer = new ASTAnalyzer();
+ });
+
+ afterEach(() => {
+ analyzer.clearCache();
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it('should create analyzer with default config', () => {
+ const stats = analyzer.getStats();
+ expect(stats.cacheSize).toBe(0);
+ });
+
+ it('should create analyzer with custom config', () => {
+ const customAnalyzer = new ASTAnalyzer({
+ maxFileSize: 500000,
+ languages: ['typescript'],
+ includeComments: false,
+ });
+ expect(customAnalyzer).toBeInstanceOf(ASTAnalyzer);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should initialize without ruvector (fallback mode)', async () => {
+ await analyzer.initialize();
+ const stats = analyzer.getStats();
+ expect(stats.useNative).toBe(0);
+ });
+ });
+
+ describe('analyze', () => {
+ const typeScriptCode = `
+import { foo } from './foo';
+import bar from 'bar';
+
+export interface User {
+ id: string;
+ name: string;
+}
+
+export class UserService {
+ private users: User[] = [];
+
+ async getUser(id: string): Promise<User | null> {
+ return this.users.find(u => u.id === id) || null;
+ }
+
+ createUser(name: string): User {
+ const user = { id: Date.now().toString(), name };
+ this.users.push(user);
+ return user;
+ }
+}
+
+export function helper() {
+ return 'helper';
+}
+`;
+
+ it('should analyze TypeScript code', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis).toHaveProperty('filePath', 'test.ts');
+ expect(analysis).toHaveProperty('language', 'typescript');
+ expect(analysis).toHaveProperty('root');
+ expect(analysis).toHaveProperty('functions');
+ expect(analysis).toHaveProperty('classes');
+ expect(analysis).toHaveProperty('imports');
+ expect(analysis).toHaveProperty('exports');
+ expect(analysis).toHaveProperty('complexity');
+ expect(analysis).toHaveProperty('timestamp');
+ expect(analysis).toHaveProperty('durationMs');
+ });
+
+ it('should extract functions', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis.functions.length).toBeGreaterThan(0);
+ const funcNames = analysis.functions.map(f => f.name);
+ expect(funcNames).toContain('helper');
+ });
+
+ it('should extract classes', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis.classes.length).toBeGreaterThan(0);
+ const classNames = analysis.classes.map(c => c.name);
+ expect(classNames).toContain('UserService');
+ });
+
+ it('should extract imports', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis.imports).toContain('./foo');
+ expect(analysis.imports).toContain('bar');
+ });
+
+ it('should extract exports', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis.exports).toContain('User');
+ expect(analysis.exports).toContain('UserService');
+ expect(analysis.exports).toContain('helper');
+ });
+
+ it('should calculate complexity metrics', () => {
+ const analysis = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis.complexity).toHaveProperty('cyclomatic');
+ expect(analysis.complexity).toHaveProperty('cognitive');
+ expect(analysis.complexity).toHaveProperty('loc');
+ expect(analysis.complexity).toHaveProperty('commentDensity');
+ expect(analysis.complexity.cyclomatic).toBeGreaterThan(0);
+ expect(analysis.complexity.loc).toBeGreaterThan(0);
+ });
+
+ it('should cache analysis results', () => {
+ const analysis1 = analyzer.analyze(typeScriptCode, 'test.ts');
+ const analysis2 = analyzer.analyze(typeScriptCode, 'test.ts');
+ expect(analysis1.timestamp).toBe(analysis2.timestamp);
+ expect(analyzer.getStats().cacheSize).toBe(1);
+ });
+
+ it('should throw on file too large', () => {
+ const smallAnalyzer = new ASTAnalyzer({ maxFileSize: 10 });
+ expect(() => smallAnalyzer.analyze(typeScriptCode, 'test.ts')).toThrow('File too large');
+ });
+ });
+
+ describe('language detection', () => {
+ it('should detect TypeScript by extension', () => {
+ const analysis = analyzer.analyze('const x = 1;', 'file.ts');
+ expect(analysis.language).toBe('typescript');
+ });
+
+ it('should detect JavaScript by extension', () => {
+ const analysis = analyzer.analyze('const x = 1;', 'file.js');
+ expect(analysis.language).toBe('javascript');
+ });
+
+ it('should detect Python by extension', () => {
+ const analysis = analyzer.analyze('x = 1', 'file.py');
+ expect(analysis.language).toBe('python');
+ });
+
+ it('should detect Rust by extension', () => {
+ const analysis = analyzer.analyze('fn main() {}', 'file.rs');
+ expect(analysis.language).toBe('rust');
+ });
+
+ it('should detect Go by extension', () => {
+ const analysis = analyzer.analyze('package main', 'file.go');
+ expect(analysis.language).toBe('go');
+ });
+
+ it('should detect TypeScript by content', () => {
+ const analysis = analyzer.analyze('const x: string = "hello";', 'unknown');
+ expect(analysis.language).toBe('typescript');
+ });
+
+ it('should detect Python by content', () => {
+ const analysis = analyzer.analyze('def hello():\n print("hi")', 'unknown');
+ expect(analysis.language).toBe('python');
+ });
+
+ it('should return unknown for undetectable language', () => {
+ const analysis = analyzer.analyze('random text', 'file.xyz');
+ expect(analysis.language).toBe('unknown');
+ });
+ });
+
+ describe('JavaScript analysis', () => {
+ const jsCode = `
+const helper = (x) => x * 2;
+
+function processData(data) {
+ if (data.length === 0) {
+ return [];
+ }
+ return data.map(helper);
+}
+
+class DataProcessor {
+ process(data) {
+ return processData(data);
+ }
+}
+
+module.exports = { DataProcessor, processData };
+`;
+
+ it('should analyze JavaScript code', () => {
+ const analysis = analyzer.analyze(jsCode, 'processor.js');
+ expect(analysis.language).toBe('javascript');
+ expect(analysis.functions.length).toBeGreaterThan(0);
+ });
+
+ it('should extract arrow functions', () => {
+ const analysis = analyzer.analyze(jsCode, 'processor.js');
+ const funcNames = analysis.functions.map(f => f.name);
+ expect(funcNames).toContain('helper');
+ });
+ });
+
+ describe('Python analysis', () => {
+ const pythonCode = `
+import os
+from typing import List
+
+class DataService:
+ def __init__(self):
+ self.data = []
+
+ def add_item(self, item):
+ self.data.append(item)
+
+def process(items: List[str]) -> List[str]:
+ return [item.upper() for item in items]
+`;
+
+ it('should analyze Python code', () => {
+ const analysis = analyzer.analyze(pythonCode, 'service.py');
+ expect(analysis.language).toBe('python');
+ });
+
+ it('should extract Python functions', () => {
+ const analysis = analyzer.analyze(pythonCode, 'service.py');
+ const funcNames = analysis.functions.map(f => f.name);
+ expect(funcNames).toContain('process');
+ });
+
+ it('should extract Python classes', () => {
+ const analysis = analyzer.analyze(pythonCode, 'service.py');
+ const classNames = analysis.classes.map(c => c.name);
+ expect(classNames).toContain('DataService');
+ });
+
+ it('should extract Python imports', () => {
+ const analysis = analyzer.analyze(pythonCode, 'service.py');
+ expect(analysis.imports).toContain('os');
+ });
+ });
+
+ describe('getFunctionAtLine', () => {
+ const code = `
+function foo() {
+ return 1;
+}
+
+function bar() {
+ return 2;
+}
+`;
+
+ it('should return function containing line', () => {
+ const analysis = analyzer.analyze(code, 'test.ts');
+ const func = analyzer.getFunctionAtLine(analysis, 3);
+ expect(func).not.toBeNull();
+ expect(func?.name).toBe('foo');
+ });
+
+ it('should return null for line outside functions', () => {
+ const analysis = analyzer.analyze(code, 'test.ts');
+ const func = analyzer.getFunctionAtLine(analysis, 1);
+ expect(func).toBeNull();
+ });
+ });
+
+ describe('getClassAtLine', () => {
+ const code = `
+class Foo {
+ method() {}
+}
+
+class Bar {
+ method() {}
+}
+`;
+
+ it('should return class containing line', () => {
+ const analysis = analyzer.analyze(code, 'test.ts');
+ const cls = analyzer.getClassAtLine(analysis, 3);
+ expect(cls).not.toBeNull();
+ expect(cls?.name).toBe('Foo');
+ });
+
+ it('should return null for line outside classes', () => {
+ const analysis = analyzer.analyze(code, 'test.ts');
+ const cls = analyzer.getClassAtLine(analysis, 1);
+ expect(cls).toBeNull();
+ });
+ });
+
+ describe('getSymbols', () => {
+ const code = `
+function helper() {}
+class Service {}
+function util() {}
+`;
+
+ it('should return all symbols', () => {
+ const analysis = analyzer.analyze(code, 'test.ts');
+ const symbols = analyzer.getSymbols(analysis);
+ expect(symbols).toContain('helper');
+ expect(symbols).toContain('Service');
+ expect(symbols).toContain('util');
+ });
+ });
+
+ describe('clearCache', () => {
+ it('should clear the analysis cache', () => {
+ analyzer.analyze('const x = 1;', 'test.ts');
+ expect(analyzer.getStats().cacheSize).toBe(1);
+
+ analyzer.clearCache();
+ expect(analyzer.getStats().cacheSize).toBe(0);
+ });
+ });
+
+ describe('complexity calculation', () => {
+ it('should calculate higher cyclomatic complexity for branching code', () => {
+ const simpleCode = 'const x = 1;';
+ const complexCode = `
+function complex(x) {
+ if (x > 0) {
+ if (x > 10) {
+ return 'big';
+ } else {
+ return 'medium';
+ }
+ } else {
+ return 'small';
+ }
+}
+`;
+ const simpleAnalysis = analyzer.analyze(simpleCode, 'simple.ts');
+ const complexAnalysis = analyzer.analyze(complexCode, 'complex.ts');
+
+ expect(complexAnalysis.complexity.cyclomatic).toBeGreaterThan(
+ simpleAnalysis.complexity.cyclomatic
+ );
+ });
+
+ it('should calculate cognitive complexity with nesting', () => {
+ const nestedCode = `
+function nested() {
+ for (let i = 0; i < 10; i++) {
+ if (i % 2 === 0) {
+ while (true) {
+ break;
+ }
+ }
+ }
+}
+`;
+ const analysis = analyzer.analyze(nestedCode, 'nested.ts');
+ expect(analysis.complexity.cognitive).toBeGreaterThan(0);
+ });
+
+ it('should calculate comment density', () => {
+ const commentedCode = `
+// This is a comment
+function foo() {
+ // Another comment
+ return 1;
+}
+`;
+ const analysis = analyzer.analyze(commentedCode, 'test.ts');
+ expect(analysis.complexity.commentDensity).toBeGreaterThan(0);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty code', () => {
+ const analysis = analyzer.analyze('', 'empty.ts');
+ expect(analysis.functions).toHaveLength(0);
+ expect(analysis.classes).toHaveLength(0);
+ });
+
+ it('should handle code with only comments', () => {
+ const analysis = analyzer.analyze('// Just a comment\n/* block comment */', 'comments.ts');
+ // Comments are counted as lines but have low LOC
+ expect(analysis.complexity.loc).toBeGreaterThanOrEqual(0);
+ });
+
+ it('should handle malformed code', () => {
+ const analysis = analyzer.analyze('function { broken', 'broken.ts');
+ expect(analysis).toBeDefined();
+ });
+
+ it('should handle Unicode identifiers', () => {
+ const analysis = analyzer.analyze('function \u00e9valuate() { return true; }', 'unicode.ts');
+ expect(analysis.functions.length).toBeGreaterThanOrEqual(0);
+ });
+ });
+});
+
+describe('createASTAnalyzer', () => {
+ it('should create analyzer instance', () => {
+ const analyzer = createASTAnalyzer();
+ expect(analyzer).toBeInstanceOf(ASTAnalyzer);
+ });
+
+ it('should accept config', () => {
+ const analyzer = createASTAnalyzer({ maxFileSize: 500000 });
+ expect(analyzer).toBeInstanceOf(ASTAnalyzer);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/coverage-router.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/coverage-router.test.ts
new file mode 100644
index 0000000000..cb89493048
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/coverage-router.test.ts
@@ -0,0 +1,437 @@
+/**
+ * Coverage Router Tests
+ *
+ * Tests for the coverage-based test routing functionality.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { CoverageRouter, createCoverageRouter, type CoverageReport, type FileCoverage } from '../../src/ruvector/coverage-router';
+
+// Mock the @ruvector/coverage module
+vi.mock('@ruvector/coverage', () => ({
+ createCoverageRouter: vi.fn(() => null),
+}));
+
+describe('CoverageRouter', () => {
+ let router: CoverageRouter;
+
+ beforeEach(() => {
+ router = new CoverageRouter();
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it('should create router with default config', () => {
+ const stats = router.getStats();
+ expect(stats.minCoverage).toBe(70);
+ expect(stats.targetCoverage).toBe(85);
+ });
+
+ it('should create router with custom config', () => {
+ const customRouter = new CoverageRouter({
+ minCoverage: 80,
+ targetCoverage: 95,
+ incremental: false,
+ });
+ const stats = customRouter.getStats();
+ expect(stats.minCoverage).toBe(80);
+ expect(stats.targetCoverage).toBe(95);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should initialize without ruvector (fallback mode)', async () => {
+ await router.initialize();
+ const stats = router.getStats();
+ expect(stats.useNative).toBe(false);
+ });
+ });
+
+ describe('parseCoverage', () => {
+ describe('JSON format', () => {
+ it('should parse JSON coverage data', () => {
+ const data = {
+ 'src/utils.ts': {
+ lineCoverage: 80,
+ branchCoverage: 70,
+ functionCoverage: 90,
+ statementCoverage: 85,
+ uncoveredLines: [10, 20, 30],
+ totalLines: 100,
+ coveredLines: 80,
+ },
+ };
+
+ const report = router.parseCoverage(data, 'json');
+ expect(report).toHaveProperty('overall');
+ expect(report).toHaveProperty('byType');
+ expect(report).toHaveProperty('byFile');
+ expect(report.byFile.length).toBe(1);
+ });
+
+ it('should parse array of FileCoverage', () => {
+ const data: FileCoverage[] = [
+ { path: 'src/a.ts', lineCoverage: 80, branchCoverage: 70, functionCoverage: 90, statementCoverage: 85, uncoveredLines: [], totalLines: 100, coveredLines: 80 },
+ { path: 'src/b.ts', lineCoverage: 60, branchCoverage: 50, functionCoverage: 70, statementCoverage: 65, uncoveredLines: [], totalLines: 50, coveredLines: 30 },
+ ];
+
+ const report = router.parseCoverage(data, 'json');
+ expect(report.byFile.length).toBe(2);
+ });
+ });
+
+ describe('LCOV format', () => {
+ it('should parse LCOV data', () => {
+ const lcov = `SF:src/utils.ts
+LF:100
+LH:80
+DA:1,1
+DA:2,1
+DA:3,0
+end_of_record
+SF:src/helper.ts
+LF:50
+LH:40
+end_of_record
+`;
+
+ const report = router.parseCoverage(lcov, 'lcov');
+ expect(report.byFile.length).toBe(2);
+ expect(report.byFile[0].path).toBe('src/utils.ts');
+ });
+
+ it('should extract uncovered lines from LCOV', () => {
+ const lcov = `SF:src/utils.ts
+LF:10
+LH:8
+DA:1,1
+DA:2,0
+DA:3,1
+DA:4,0
+end_of_record
+`;
+
+ const report = router.parseCoverage(lcov, 'lcov');
+ expect(report.byFile[0].uncoveredLines).toContain(2);
+ expect(report.byFile[0].uncoveredLines).toContain(4);
+ });
+ });
+
+ describe('Istanbul format', () => {
+ it('should parse Istanbul coverage data', () => {
+ const istanbul = {
+ 'src/utils.ts': {
+ s: { '0': 1, '1': 0, '2': 1 },
+ f: { '0': 1, '1': 0 },
+ b: { '0': [1, 0] },
+ },
+ };
+
+ const report = router.parseCoverage(istanbul, 'istanbul');
+ expect(report.byFile.length).toBe(1);
+ expect(report.byFile[0].statementCoverage).toBeCloseTo(66.67, 1);
+ });
+ });
+
+ describe('Cobertura format', () => {
+ it('should parse Cobertura XML data', () => {
+ const cobertura = `
+<coverage>
+ <packages>
+ <package>
+ <classes>
+ <class filename="src/utils.ts" line-rate="0.8" branch-rate="0.7">
+ </class>
+ </classes>
+ </package>
+ </packages>
+</coverage>
+`;
+
+ const report = router.parseCoverage(cobertura, 'cobertura');
+ expect(report.byFile.length).toBe(1);
+ expect(report.byFile[0].lineCoverage).toBe(80);
+ expect(report.byFile[0].branchCoverage).toBe(70);
+ });
+ });
+ });
+
+ describe('route', () => {
+ it('should return CoverageRouteResult', () => {
+ const report: CoverageReport = {
+ overall: 75,
+ byType: { line: 75, branch: 70, function: 80, statement: 75 },
+ byFile: [
+ { path: 'src/low.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [1,2,3], totalLines: 100, coveredLines: 50 },
+ { path: 'src/high.ts', lineCoverage: 90, branchCoverage: 85, functionCoverage: 95, statementCoverage: 90, uncoveredLines: [], totalLines: 100, coveredLines: 90 },
+ ],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result).toHaveProperty('action');
+ expect(result).toHaveProperty('priority');
+ expect(result).toHaveProperty('targetFiles');
+ expect(result).toHaveProperty('testTypes');
+ expect(result).toHaveProperty('gaps');
+ expect(result).toHaveProperty('estimatedEffort');
+ expect(result).toHaveProperty('impactScore');
+ });
+
+ it('should return prioritize action for low coverage', () => {
+ const report: CoverageReport = {
+ overall: 50,
+ byType: { line: 50, branch: 40, function: 60, statement: 50 },
+ byFile: [{ path: 'src/low.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [], totalLines: 100, coveredLines: 50 }],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result.action).toBe('prioritize');
+ });
+
+ it('should return skip action for high coverage', () => {
+ const report: CoverageReport = {
+ overall: 95,
+ byType: { line: 95, branch: 90, function: 98, statement: 95 },
+ byFile: [{ path: 'src/high.ts', lineCoverage: 95, branchCoverage: 90, functionCoverage: 98, statementCoverage: 95, uncoveredLines: [], totalLines: 100, coveredLines: 95 }],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result.action).toBe('skip');
+ });
+
+ it('should identify coverage gaps', () => {
+ const report: CoverageReport = {
+ overall: 75,
+ byType: { line: 75, branch: 70, function: 80, statement: 75 },
+ byFile: [
+ { path: 'src/low.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [1,2,3], totalLines: 100, coveredLines: 50 },
+ ],
+ lowestCoverage: [{ path: 'src/low.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [1,2,3], totalLines: 100, coveredLines: 50 }],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result.gaps.length).toBeGreaterThan(0);
+ expect(result.gaps[0].file).toBe('src/low.ts');
+ expect(result.gaps[0].gap).toBeGreaterThan(0);
+ });
+
+ it('should prioritize changed files', () => {
+ const report: CoverageReport = {
+ overall: 80,
+ byType: { line: 80, branch: 75, function: 85, statement: 80 },
+ byFile: [
+ { path: 'src/changed.ts', lineCoverage: 60, branchCoverage: 50, functionCoverage: 70, statementCoverage: 60, uncoveredLines: [], totalLines: 100, coveredLines: 60 },
+ { path: 'src/unchanged.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [], totalLines: 100, coveredLines: 50 },
+ ],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report, ['changed.ts']);
+ expect(result.targetFiles[0]).toContain('changed');
+ });
+
+ it('should recommend test types based on files', () => {
+ const report: CoverageReport = {
+ overall: 75,
+ byType: { line: 75, branch: 70, function: 80, statement: 75 },
+ byFile: [
+ { path: 'src/api/handler.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [], totalLines: 100, coveredLines: 50 },
+ ],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result.testTypes).toContain('unit');
+ expect(result.testTypes).toContain('integration');
+ });
+
+ it('should calculate estimated effort', () => {
+ const report: CoverageReport = {
+ overall: 75,
+ byType: { line: 75, branch: 70, function: 80, statement: 75 },
+ byFile: [
+ { path: 'src/a.ts', lineCoverage: 50, branchCoverage: 40, functionCoverage: 60, statementCoverage: 50, uncoveredLines: [], totalLines: 100, coveredLines: 50 },
+ { path: 'src/b.ts', lineCoverage: 60, branchCoverage: 50, functionCoverage: 70, statementCoverage: 60, uncoveredLines: [], totalLines: 100, coveredLines: 60 },
+ ],
+ lowestCoverage: [],
+ highestCoverage: [],
+ uncoveredCritical: [],
+ timestamp: Date.now(),
+ };
+
+ const result = router.route(report);
+ expect(result.estimatedEffort).toBeGreaterThan(0);
+ });
+ });
+
+ describe('getTrend', () => {
+ it('should return stable for insufficient history', () => {
+ const trend = router.getTrend();
+ expect(trend.direction).toBe('stable');
+ expect(trend.change).toBe(0);
+ });
+
+ it('should detect upward trend', () => {
+ const report1: CoverageReport = { overall: 70, byType: { line: 70, branch: 65, function: 75, statement: 70 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+ const report2: CoverageReport = { overall: 80, byType: { line: 80, branch: 75, function: 85, statement: 80 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+
+ router.addToHistory(report1);
+ router.addToHistory(report2);
+
+ const trend = router.getTrend();
+ expect(trend.direction).toBe('up');
+ expect(trend.change).toBe(10);
+ });
+
+ it('should detect downward trend', () => {
+ const report1: CoverageReport = { overall: 80, byType: { line: 80, branch: 75, function: 85, statement: 80 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+ const report2: CoverageReport = { overall: 70, byType: { line: 70, branch: 65, function: 75, statement: 70 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+
+ router.addToHistory(report1);
+ router.addToHistory(report2);
+
+ const trend = router.getTrend();
+ expect(trend.direction).toBe('down');
+ expect(trend.change).toBe(-10);
+ });
+
+ it('should detect stable trend for small changes', () => {
+ const report1: CoverageReport = { overall: 80, byType: { line: 80, branch: 75, function: 85, statement: 80 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+ const report2: CoverageReport = { overall: 80.3, byType: { line: 80.3, branch: 75, function: 85, statement: 80 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+
+ router.addToHistory(report1);
+ router.addToHistory(report2);
+
+ const trend = router.getTrend();
+ expect(trend.direction).toBe('stable');
+ });
+ });
+
+ describe('addToHistory', () => {
+ it('should add report to history', () => {
+ const report: CoverageReport = { overall: 80, byType: { line: 80, branch: 75, function: 85, statement: 80 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+
+ router.addToHistory(report);
+ expect(router.getStats().historySize).toBe(1);
+ });
+
+ it('should limit history to 10 entries', () => {
+ for (let i = 0; i < 15; i++) {
+ const report: CoverageReport = { overall: 70 + i, byType: { line: 70, branch: 65, function: 75, statement: 70 }, byFile: [], lowestCoverage: [], highestCoverage: [], uncoveredCritical: [], timestamp: Date.now() };
+ router.addToHistory(report);
+ }
+
+ expect(router.getStats().historySize).toBe(10);
+ });
+ });
+
+ describe('critical file detection', () => {
+ it('should identify uncovered critical files', () => {
+ const data = {
+ 'src/auth/login.ts': {
+ lineCoverage: 50,
+ branchCoverage: 40,
+ functionCoverage: 60,
+ statementCoverage: 50,
+ uncoveredLines: [1, 2, 3],
+ totalLines: 100,
+ coveredLines: 50,
+ },
+ 'src/payment/checkout.ts': {
+ lineCoverage: 60,
+ branchCoverage: 50,
+ functionCoverage: 70,
+ statementCoverage: 60,
+ uncoveredLines: [1, 2],
+ totalLines: 100,
+ coveredLines: 60,
+ },
+ };
+
+ const report = router.parseCoverage(data, 'json');
+ expect(report.uncoveredCritical.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty coverage data', () => {
+ const report = router.parseCoverage({}, 'json');
+ expect(report.byFile).toHaveLength(0);
+ expect(report.overall).toBe(100);
+ });
+
+ it('should handle 100% coverage', () => {
+ const data = {
+ 'src/perfect.ts': {
+ lineCoverage: 100,
+ branchCoverage: 100,
+ functionCoverage: 100,
+ statementCoverage: 100,
+ uncoveredLines: [],
+ totalLines: 100,
+ coveredLines: 100,
+ },
+ };
+
+ const report = router.parseCoverage(data, 'json');
+ const result = router.route(report);
+ expect(result.action).toBe('skip');
+ expect(result.gaps).toHaveLength(0);
+ });
+
+ it('should handle 0% coverage', () => {
+ const data = {
+ 'src/empty.ts': {
+ lineCoverage: 0,
+ branchCoverage: 0,
+ functionCoverage: 0,
+ statementCoverage: 0,
+ uncoveredLines: Array.from({ length: 100 }, (_, i) => i + 1),
+ totalLines: 100,
+ coveredLines: 0,
+ },
+ };
+
+ const report = router.parseCoverage(data, 'json');
+ const result = router.route(report);
+ expect(result.action).toBe('prioritize');
+ expect(result.priority).toBeGreaterThanOrEqual(8);
+ });
+ });
+});
+
+describe('createCoverageRouter', () => {
+ it('should create router instance', () => {
+ const router = createCoverageRouter();
+ expect(router).toBeInstanceOf(CoverageRouter);
+ });
+
+ it('should accept config', () => {
+ const router = createCoverageRouter({ minCoverage: 80 });
+ expect(router).toBeInstanceOf(CoverageRouter);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/diff-classifier.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/diff-classifier.test.ts
new file mode 100644
index 0000000000..8bc228f478
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/diff-classifier.test.ts
@@ -0,0 +1,450 @@
+/**
+ * Diff Classifier Tests
+ *
+ * Tests for the diff classification functionality.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { DiffClassifier, createDiffClassifier, type DiffAnalysis, type FileDiff } from '../../src/ruvector/diff-classifier';
+
+// Mock the @ruvector/diff module
+vi.mock('@ruvector/diff', () => ({
+ createDiffClassifier: vi.fn(() => null),
+}));
+
+describe('DiffClassifier', () => {
+ let classifier: DiffClassifier;
+
+ beforeEach(() => {
+ classifier = new DiffClassifier();
+ });
+
+ afterEach(() => {
+ classifier.clearCache();
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it('should create classifier with default config', () => {
+ const stats = classifier.getStats();
+ expect(stats.cacheSize).toBe(0);
+ expect(stats.useNative).toBe(false);
+ });
+
+ it('should create classifier with custom config', () => {
+ const customClassifier = new DiffClassifier({
+ maxDiffSize: 5000,
+ detectRefactoring: false,
+ minConfidence: 0.8,
+ });
+ expect(customClassifier).toBeInstanceOf(DiffClassifier);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should initialize without ruvector (fallback mode)', async () => {
+ await classifier.initialize();
+ const stats = classifier.getStats();
+ expect(stats.useNative).toBe(false);
+ });
+ });
+
+ describe('parseDiff', () => {
+ const sampleDiff = `diff --git a/src/utils.ts b/src/utils.ts
+index 1234567..abcdefg 100644
+--- a/src/utils.ts
++++ b/src/utils.ts
+@@ -1,5 +1,7 @@
+ import { foo } from 'foo';
+
++import { bar } from 'bar';
++
+ export function helper() {
+- return null;
++ return 'hello';
+ }
+`;
+
+ it('should parse diff into FileDiff array', () => {
+ const files = classifier.parseDiff(sampleDiff);
+ expect(Array.isArray(files)).toBe(true);
+ expect(files.length).toBe(1);
+ });
+
+ it('should extract file path', () => {
+ const files = classifier.parseDiff(sampleDiff);
+ expect(files[0].path).toBe('src/utils.ts');
+ });
+
+ it('should count additions and deletions', () => {
+ const files = classifier.parseDiff(sampleDiff);
+ expect(files[0].additions).toBeGreaterThan(0);
+ expect(files[0].deletions).toBeGreaterThan(0);
+ });
+
+ it('should parse hunks', () => {
+ const files = classifier.parseDiff(sampleDiff);
+ expect(files[0].hunks.length).toBeGreaterThan(0);
+ expect(files[0].hunks[0]).toHaveProperty('oldStart');
+ expect(files[0].hunks[0]).toHaveProperty('newStart');
+ expect(files[0].hunks[0]).toHaveProperty('changes');
+ });
+
+ it('should generate classification for each file', () => {
+ const files = classifier.parseDiff(sampleDiff);
+ expect(files[0].classification).toHaveProperty('primary');
+ expect(files[0].classification).toHaveProperty('confidence');
+ expect(files[0].classification).toHaveProperty('impactLevel');
+ });
+
+ it('should handle empty diff', () => {
+ const files = classifier.parseDiff('');
+ expect(files).toEqual([]);
+ });
+
+ it('should handle multi-file diff', () => {
+ const multiDiff = `diff --git a/file1.ts b/file1.ts
+--- a/file1.ts
++++ b/file1.ts
+@@ -1 +1 @@
+-old
++new
+diff --git a/file2.ts b/file2.ts
+--- a/file2.ts
++++ b/file2.ts
+@@ -1 +1 @@
+-old
++new
+`;
+ const files = classifier.parseDiff(multiDiff);
+ expect(files.length).toBe(2);
+ });
+ });
+
+ describe('classify', () => {
+ it('should return DiffAnalysis', () => {
+ const files: FileDiff[] = [{
+ path: 'src/feature.ts',
+ hunks: [],
+ additions: 10,
+ deletions: 2,
+ classification: {
+ primary: 'feature',
+ secondary: [],
+ confidence: 0.8,
+ impactLevel: 'medium',
+ suggestedReviewers: [],
+ testingStrategy: [],
+ riskFactors: [],
+ },
+ }];
+
+ const analysis = classifier.classify(files);
+ expect(analysis).toHaveProperty('files');
+ expect(analysis).toHaveProperty('overall');
+ expect(analysis).toHaveProperty('stats');
+ expect(analysis).toHaveProperty('timestamp');
+ });
+
+ it('should calculate overall stats', () => {
+ const files: FileDiff[] = [
+ { path: 'a.ts', hunks: [], additions: 10, deletions: 5, classification: { primary: 'feature', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ { path: 'b.ts', hunks: [], additions: 20, deletions: 3, classification: { primary: 'feature', secondary: [], confidence: 0.9, impactLevel: 'medium', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ ];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.stats.totalAdditions).toBe(30);
+ expect(analysis.stats.totalDeletions).toBe(8);
+ expect(analysis.stats.filesChanged).toBe(2);
+ });
+
+ it('should compute average confidence', () => {
+ const files: FileDiff[] = [
+ { path: 'a.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'feature', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ { path: 'b.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'bugfix', secondary: [], confidence: 0.6, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ ];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.stats.avgConfidence).toBe(0.7);
+ });
+
+ it('should determine overall primary classification by majority', () => {
+ const files: FileDiff[] = [
+ { path: 'a.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'bugfix', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ { path: 'b.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'bugfix', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ { path: 'c.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'feature', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ ];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.overall.primary).toBe('bugfix');
+ });
+
+ it('should use maximum impact level', () => {
+ const files: FileDiff[] = [
+ { path: 'a.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'feature', secondary: [], confidence: 0.8, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ { path: 'b.ts', hunks: [], additions: 1, deletions: 1, classification: { primary: 'feature', secondary: [], confidence: 0.8, impactLevel: 'critical', suggestedReviewers: [], testingStrategy: [], riskFactors: [] } },
+ ];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.overall.impactLevel).toBe('critical');
+ });
+
+ it('should handle empty files array', () => {
+ const analysis = classifier.classify([]);
+ expect(analysis.overall.primary).toBe('unknown');
+ expect(analysis.stats.filesChanged).toBe(0);
+ });
+ });
+
+ describe('classifyCommitMessage', () => {
+ it('should classify feature commits', () => {
+ expect(classifier.classifyCommitMessage('feat: add new login feature')).toBe('feature');
+ expect(classifier.classifyCommitMessage('implement user dashboard')).toBe('feature');
+ });
+
+ it('should classify bugfix commits', () => {
+ expect(classifier.classifyCommitMessage('fix: resolve login bug')).toBe('bugfix');
+ expect(classifier.classifyCommitMessage('hotfix: critical security patch')).toBe('bugfix');
+ });
+
+ it('should classify refactor commits', () => {
+ expect(classifier.classifyCommitMessage('refactor: restructure auth module')).toBe('refactor');
+ expect(classifier.classifyCommitMessage('cleanup: remove dead code')).toBe('refactor');
+ });
+
+ it('should classify docs commits', () => {
+ expect(classifier.classifyCommitMessage('docs: update README')).toBe('docs');
+ expect(classifier.classifyCommitMessage('add documentation for API')).toBe('docs');
+ });
+
+ it('should classify test commits', () => {
+ expect(classifier.classifyCommitMessage('test: add unit tests')).toBe('test');
+ });
+
+ it('should classify config commits', () => {
+ expect(classifier.classifyCommitMessage('config: update tsconfig')).toBe('config');
+ });
+
+ it('should classify style commits', () => {
+ expect(classifier.classifyCommitMessage('style: format code')).toBe('style');
+ });
+
+ it('should return unknown for unclassified commits', () => {
+ expect(classifier.classifyCommitMessage('random commit message')).toBe('unknown');
+ });
+ });
+
+ describe('classification by file path', () => {
+ it('should classify test files', () => {
+ const diff = `diff --git a/src/__tests__/foo.test.ts b/src/__tests__/foo.test.ts
+--- a/src/__tests__/foo.test.ts
++++ b/src/__tests__/foo.test.ts
+@@ -1 +1 @@
+-test
++test2
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.primary).toBe('test');
+ });
+
+ it('should classify config files', () => {
+ const diff = `diff --git a/tsconfig.json b/tsconfig.json
+--- a/tsconfig.json
++++ b/tsconfig.json
+@@ -1 +1 @@
+-{}
++{"compilerOptions": {}}
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.primary).toBe('config');
+ });
+
+ it('should classify documentation files', () => {
+ const diff = `diff --git a/README.md b/README.md
+--- a/README.md
++++ b/README.md
+@@ -1 +1 @@
+-old
++new
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.primary).toBe('docs');
+ });
+ });
+
+ describe('impact level detection', () => {
+ it('should detect critical impact for security files', () => {
+ const diff = `diff --git a/src/security/auth.ts b/src/security/auth.ts
+--- a/src/security/auth.ts
++++ b/src/security/auth.ts
+@@ -1,100 +1,100 @@
+` + Array(100).fill('+new line').join('\n');
+
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.impactLevel).toBe('critical');
+ });
+
+ it('should detect low impact for test files', () => {
+ const diff = `diff --git a/test/foo.test.ts b/test/foo.test.ts
+--- a/test/foo.test.ts
++++ b/test/foo.test.ts
+@@ -1 +1 @@
+-test
++test2
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.impactLevel).toBe('low');
+ });
+ });
+
+ describe('reviewer suggestions', () => {
+ it('should suggest reviewers based on classification', () => {
+ const diff = `diff --git a/src/feature.ts b/src/feature.ts
+--- a/src/feature.ts
++++ b/src/feature.ts
+@@ -1,10 +1,15 @@
++new feature code
+`;
+ const files = classifier.parseDiff(diff);
+ const analysis = classifier.classify(files);
+ expect(analysis.overall.suggestedReviewers.length).toBeGreaterThan(0);
+ });
+
+ it('should suggest security reviewer for high impact', () => {
+ const files: FileDiff[] = [{
+ path: 'src/auth/login.ts',
+ hunks: [],
+ additions: 100,
+ deletions: 50,
+ classification: {
+ primary: 'feature',
+ secondary: [],
+ confidence: 0.8,
+ impactLevel: 'critical',
+ suggestedReviewers: ['security-reviewer'],
+ testingStrategy: [],
+ riskFactors: [],
+ },
+ }];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.overall.suggestedReviewers).toContain('security-reviewer');
+ });
+ });
+
+ describe('testing strategy', () => {
+ it('should recommend unit tests for non-test files', () => {
+ const diff = `diff --git a/src/utils.ts b/src/utils.ts
+--- a/src/utils.ts
++++ b/src/utils.ts
+@@ -1 +1 @@
+-old
++new
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.testingStrategy).toContain('unit-tests');
+ });
+
+ it('should recommend integration tests for features', () => {
+ const files: FileDiff[] = [{
+ path: 'src/feature.ts',
+ hunks: [],
+ additions: 50,
+ deletions: 0,
+ classification: {
+ primary: 'feature',
+ secondary: [],
+ confidence: 0.8,
+ impactLevel: 'medium',
+ suggestedReviewers: [],
+ testingStrategy: ['unit-tests', 'integration-tests'],
+ riskFactors: [],
+ },
+ }];
+
+ const analysis = classifier.classify(files);
+ expect(analysis.overall.testingStrategy).toContain('integration-tests');
+ });
+ });
+
+ describe('risk factors', () => {
+ it('should identify security risk for auth files', () => {
+ const diff = `diff --git a/src/auth/verify.ts b/src/auth/verify.ts
+--- a/src/auth/verify.ts
++++ b/src/auth/verify.ts
+@@ -1 +1 @@
+-old
++new
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files[0].classification.riskFactors.some(r => r.includes('Security'))).toBe(true);
+ });
+ });
+
+ describe('caching', () => {
+ it('should cache classification results', () => {
+ const diff = `diff --git a/src/file.ts b/src/file.ts
+--- a/src/file.ts
++++ b/src/file.ts
+@@ -1 +1 @@
+-old
++new
+`;
+ classifier.parseDiff(diff);
+ const stats1 = classifier.getStats();
+
+ classifier.parseDiff(diff);
+ const stats2 = classifier.getStats();
+
+ expect(stats2.cacheSize).toBeGreaterThanOrEqual(stats1.cacheSize);
+ });
+
+ it('should clear cache', () => {
+ const diff = `diff --git a/src/file.ts b/src/file.ts
+--- a/src/file.ts
++++ b/src/file.ts
+@@ -1 +1 @@
+-old
++new
+`;
+ classifier.parseDiff(diff);
+ expect(classifier.getStats().cacheSize).toBeGreaterThan(0);
+
+ classifier.clearCache();
+ expect(classifier.getStats().cacheSize).toBe(0);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle diff without hunks', () => {
+ const diff = `diff --git a/file.ts b/file.ts
+--- a/file.ts
++++ b/file.ts
+`;
+ const files = classifier.parseDiff(diff);
+ expect(files.length).toBe(1);
+ expect(files[0].hunks.length).toBe(0);
+ });
+
+ it('should handle binary files', () => {
+ const diff = `diff --git a/image.png b/image.png
+Binary files differ
+`;
+ const files = classifier.parseDiff(diff);
+ // Binary files may or may not be parsed depending on implementation
+ expect(files.length).toBeLessThanOrEqual(1);
+ });
+ });
+});
+
+describe('createDiffClassifier', () => {
+ it('should create classifier instance', () => {
+ const classifier = createDiffClassifier();
+ expect(classifier).toBeInstanceOf(DiffClassifier);
+ });
+
+ it('should accept config', () => {
+ const classifier = createDiffClassifier({ maxDiffSize: 5000 });
+ expect(classifier).toBeInstanceOf(DiffClassifier);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.test.ts
new file mode 100644
index 0000000000..c207168397
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.test.ts
@@ -0,0 +1,432 @@
+/**
+ * Graph Analyzer Tests
+ *
+ * Tests for the dependency graph analysis functionality.
+ * Tests the function-based API: buildDependencyGraph, analyzeGraph, etc.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ buildDependencyGraph,
+ analyzeGraph,
+ analyzeMinCutBoundaries,
+ analyzeModuleCommunities,
+ detectCircularDependencies,
+ exportToDot,
+ loadRuVector,
+ fallbackMinCut,
+ fallbackLouvain,
+ type DependencyGraph,
+ type GraphNode,
+ type GraphEdge,
+ type MinCutBoundary,
+ type ModuleCommunity,
+ type CircularDependency,
+ type GraphAnalysisResult,
+} from '../../src/ruvector/graph-analyzer.js';
+import { mkdir, writeFile, rm } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+// Mock the @ruvector/wasm module
+vi.mock('@ruvector/wasm', () => ({
+ minCut: vi.fn(() => null),
+ louvain: vi.fn(() => null),
+}));
+
+describe('Graph Analyzer', () => {
+ let testDir: string;
+
+ beforeEach(async () => {
+ testDir = join(tmpdir(), `graph-test-${Date.now()}`);
+ await mkdir(testDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ vi.clearAllMocks();
+ try {
+ await rm(testDir, { recursive: true, force: true });
+ } catch {
+ // Ignore cleanup errors
+ }
+ });
+
+ describe('loadRuVector', () => {
+ it('should return null when ruvector is not installed', async () => {
+ const result = await loadRuVector();
+ // Returns null or IRuVectorGraph interface
+ expect(result === null || typeof result === 'object').toBe(true);
+ });
+ });
+
+ describe('buildDependencyGraph', () => {
+ it('should build graph from directory with TypeScript files', async () => {
+ // Create test files
+ await writeFile(join(testDir, 'index.ts'), `
+import { helper } from './utils';
+export function main() { return helper(); }
+`);
+ await writeFile(join(testDir, 'utils.ts'), `
+export function helper() { return 'hello'; }
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+
+ expect(graph).toHaveProperty('nodes');
+ expect(graph).toHaveProperty('edges');
+ expect(graph.nodes.size).toBeGreaterThan(0);
+ });
+
+ it('should detect imports correctly', async () => {
+ await writeFile(join(testDir, 'a.ts'), `
+import { b } from './b';
+export const a = b;
+`);
+ await writeFile(join(testDir, 'b.ts'), `
+export const b = 'value';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const nodeA = Array.from(graph.nodes.values()).find(n => n.path.includes('a.ts'));
+
+ expect(nodeA).toBeDefined();
+ expect(nodeA?.imports.length).toBeGreaterThan(0);
+ });
+
+ it('should handle empty directory', async () => {
+ const graph = await buildDependencyGraph(testDir);
+ expect(graph.nodes.size).toBe(0);
+ expect(graph.edges.length).toBe(0);
+ });
+
+ it('should handle nested directories', async () => {
+ await mkdir(join(testDir, 'src'), { recursive: true });
+ await writeFile(join(testDir, 'src', 'index.ts'), `
+export const main = 'main';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ expect(graph.nodes.size).toBeGreaterThan(0);
+ });
+
+ it('should exclude node_modules by default', async () => {
+ await mkdir(join(testDir, 'node_modules', 'pkg'), { recursive: true });
+ await writeFile(join(testDir, 'node_modules', 'pkg', 'index.js'), `
+export const pkg = 'pkg';
+`);
+ await writeFile(join(testDir, 'index.ts'), `
+export const main = 'main';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const hasNodeModules = Array.from(graph.nodes.values()).some(n => n.path.includes('node_modules'));
+ expect(hasNodeModules).toBe(false);
+ });
+ });
+
+ describe('detectCircularDependencies', () => {
+ it('should detect circular dependencies', async () => {
+ await writeFile(join(testDir, 'a.ts'), `
+import { b } from './b';
+export const a = b;
+`);
+ await writeFile(join(testDir, 'b.ts'), `
+import { a } from './a';
+export const b = a;
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const cycles = detectCircularDependencies(graph);
+
+ expect(cycles.length).toBeGreaterThan(0);
+ });
+
+ it('should return empty array when no circular dependencies', async () => {
+ await writeFile(join(testDir, 'a.ts'), `
+import { b } from './b';
+export const a = b;
+`);
+ await writeFile(join(testDir, 'b.ts'), `
+export const b = 'value';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const cycles = detectCircularDependencies(graph);
+
+ expect(cycles.length).toBe(0);
+ });
+
+ it('should detect self-referencing imports', async () => {
+ await writeFile(join(testDir, 'self.ts'), `
+import { self } from './self';
+export { self };
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const cycles = detectCircularDependencies(graph);
+
+ expect(cycles.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('analyzeGraph', () => {
+ it('should return comprehensive analysis', async () => {
+ await writeFile(join(testDir, 'index.ts'), `
+import { util } from './util';
+export const main = util;
+`);
+ await writeFile(join(testDir, 'util.ts'), `
+export const util = 'util';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const analysis = await analyzeGraph(graph);
+
+ expect(analysis).toHaveProperty('graph');
+ expect(analysis).toHaveProperty('boundaries');
+ expect(analysis).toHaveProperty('communities');
+ expect(analysis).toHaveProperty('circularDependencies');
+ expect(analysis).toHaveProperty('statistics');
+ });
+
+ it('should calculate stats correctly', async () => {
+ await writeFile(join(testDir, 'a.ts'), `export const a = 1;`);
+ await writeFile(join(testDir, 'b.ts'), `export const b = 2;`);
+ await writeFile(join(testDir, 'c.ts'), `
+import { a } from './a';
+import { b } from './b';
+export const c = a + b;
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const analysis = await analyzeGraph(graph);
+
+ // Verify analysis structure - nodeCount may be 0 if files don't parse correctly
+ expect(analysis.statistics).toHaveProperty('nodeCount');
+ expect(analysis.statistics).toHaveProperty('edgeCount');
+ expect(analysis.statistics).toHaveProperty('avgDegree');
+ expect(analysis.statistics).toHaveProperty('maxDegree');
+ expect(analysis.statistics).toHaveProperty('density');
+ expect(analysis.statistics).toHaveProperty('componentCount');
+ });
+ });
+
+ describe('analyzeMinCutBoundaries', () => {
+ it('should identify module boundaries', async () => {
+ // Create two separate module groups
+ await mkdir(join(testDir, 'moduleA'), { recursive: true });
+ await mkdir(join(testDir, 'moduleB'), { recursive: true });
+
+ await writeFile(join(testDir, 'moduleA', 'a1.ts'), `
+import { a2 } from './a2';
+export const a1 = a2;
+`);
+ await writeFile(join(testDir, 'moduleA', 'a2.ts'), `
+export const a2 = 'a2';
+`);
+ await writeFile(join(testDir, 'moduleB', 'b1.ts'), `
+import { b2 } from './b2';
+export const b1 = b2;
+`);
+ await writeFile(join(testDir, 'moduleB', 'b2.ts'), `
+export const b2 = 'b2';
+`);
+ await writeFile(join(testDir, 'index.ts'), `
+import { a1 } from './moduleA/a1';
+import { b1 } from './moduleB/b1';
+export { a1, b1 };
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const boundaries = await analyzeMinCutBoundaries(graph);
+
+ expect(boundaries).toBeDefined();
+ expect(Array.isArray(boundaries)).toBe(true);
+ });
+ });
+
+ describe('analyzeModuleCommunities', () => {
+ it('should detect module communities', async () => {
+ await writeFile(join(testDir, 'a.ts'), `export const a = 1;`);
+ await writeFile(join(testDir, 'b.ts'), `
+import { a } from './a';
+export const b = a;
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const communities = await analyzeModuleCommunities(graph);
+
+ expect(Array.isArray(communities)).toBe(true);
+ });
+ });
+
+ describe('exportToDot', () => {
+ it('should export graph to DOT format', async () => {
+ await writeFile(join(testDir, 'a.ts'), `
+import { b } from './b';
+export const a = b;
+`);
+ await writeFile(join(testDir, 'b.ts'), `
+export const b = 'b';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const analysis = await analyzeGraph(graph);
+ const dot = exportToDot(analysis);
+
+ expect(dot).toContain('digraph');
+ // DOT may or may not contain edges depending on whether imports resolve
+ // The key is that it produces valid DOT output
+ expect(dot).toMatch(/^digraph \w+ \{[\s\S]*\}$/);
+ });
+
+ it('should handle empty graph', async () => {
+ const graph = await buildDependencyGraph(testDir);
+ const analysis = await analyzeGraph(graph);
+ const dot = exportToDot(analysis);
+
+ expect(dot).toContain('digraph');
+ });
+
+ it('should accept custom options', async () => {
+ await writeFile(join(testDir, 'a.ts'), `export const a = 1;`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const analysis = await analyzeGraph(graph);
+ const dot = exportToDot(analysis, { includeLabels: true });
+
+ expect(dot).toContain('digraph');
+ });
+ });
+
+ describe('fallback implementations', () => {
+ it('fallbackMinCut should return boundaries', () => {
+ // fallbackMinCut takes nodes array and edges array, not a graph object
+ const nodes = ['a', 'b', 'c'];
+ const edges: Array<[string, string, number]> = [
+ ['a', 'b', 1],
+ ['b', 'c', 1],
+ ];
+
+ const result = fallbackMinCut(nodes, edges);
+
+ expect(result).toHaveProperty('cutValue');
+ expect(result).toHaveProperty('partition1');
+ expect(result).toHaveProperty('partition2');
+ expect(result).toHaveProperty('cutEdges');
+ expect(Array.isArray(result.partition1)).toBe(true);
+ expect(Array.isArray(result.partition2)).toBe(true);
+ });
+
+ it('fallbackLouvain should return communities', () => {
+ // fallbackLouvain takes nodes array and edges array, not a graph object
+ const nodes = ['a', 'b', 'c'];
+ const edges: Array<[string, string, number]> = [
+ ['a', 'b', 1],
+ ['b', 'c', 1],
+ ];
+
+ const result = fallbackLouvain(nodes, edges);
+
+ expect(result).toHaveProperty('communities');
+ expect(result).toHaveProperty('modularity');
+ expect(Array.isArray(result.communities)).toBe(true);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle files with syntax errors gracefully', async () => {
+ await writeFile(join(testDir, 'broken.ts'), `
+export const broken = {
+ // Missing closing brace
+`);
+ await writeFile(join(testDir, 'valid.ts'), `
+export const valid = 'valid';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ // Should still process valid files
+ expect(graph.nodes.size).toBeGreaterThanOrEqual(1);
+ });
+
+ it('should handle various import styles', async () => {
+ await writeFile(join(testDir, 'styles.ts'), `
+import defaultExport from './default';
+import { named } from './named';
+import * as namespace from './namespace';
+const dynamic = import('./dynamic');
+export { defaultExport, named, namespace };
+`);
+ await writeFile(join(testDir, 'default.ts'), `export default 'default';`);
+ await writeFile(join(testDir, 'named.ts'), `export const named = 'named';`);
+ await writeFile(join(testDir, 'namespace.ts'), `export const ns = 'ns';`);
+ await writeFile(join(testDir, 'dynamic.ts'), `export const dyn = 'dyn';`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const stylesNode = Array.from(graph.nodes.values()).find(n => n.path.includes('styles.ts'));
+
+ expect(stylesNode).toBeDefined();
+ expect(stylesNode?.imports.length).toBeGreaterThan(0);
+ });
+
+ it('should handle re-exports', async () => {
+ await writeFile(join(testDir, 'reexport.ts'), `
+export { foo } from './foo';
+export * from './bar';
+`);
+ await writeFile(join(testDir, 'foo.ts'), `export const foo = 'foo';`);
+ await writeFile(join(testDir, 'bar.ts'), `export const bar = 'bar';`);
+
+ const graph = await buildDependencyGraph(testDir);
+ const reexportNode = Array.from(graph.nodes.values()).find(n => n.path.includes('reexport.ts'));
+
+ expect(reexportNode).toBeDefined();
+ });
+
+ it('should handle JavaScript files', async () => {
+ await writeFile(join(testDir, 'file.js'), `
+const { helper } = require('./helper');
+module.exports = { main: helper };
+`);
+ await writeFile(join(testDir, 'helper.js'), `
+module.exports = { helper: 'helper' };
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ expect(graph.nodes.size).toBeGreaterThan(0);
+ });
+
+ it('should handle mixed TS/JS projects', async () => {
+ await writeFile(join(testDir, 'index.ts'), `
+import { jsHelper } from './helper';
+export const main = jsHelper;
+`);
+ await writeFile(join(testDir, 'helper.js'), `
+export const jsHelper = 'helper';
+`);
+
+ const graph = await buildDependencyGraph(testDir);
+ expect(graph.nodes.size).toBeGreaterThan(0);
+ });
+ });
+
+ describe('performance', () => {
+ it('should handle many files efficiently', async () => {
+ // Create 50 files
+ const promises = [];
+ for (let i = 0; i < 50; i++) {
+ const deps = i > 0 ? `import { f${i-1} } from './f${i-1}';\n` : '';
+ const content = `${deps}export const f${i} = ${i};`;
+ promises.push(writeFile(join(testDir, `f${i}.ts`), content));
+ }
+ await Promise.all(promises);
+
+ const startTime = performance.now();
+ const graph = await buildDependencyGraph(testDir);
+ const duration = performance.now() - startTime;
+
+ expect(graph.nodes.size).toBe(50);
+ expect(duration).toBeLessThan(5000); // Should complete within 5 seconds
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/index.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/index.test.ts
new file mode 100644
index 0000000000..62285078e0
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/index.test.ts
@@ -0,0 +1,514 @@
+/**
+ * RuVector Integration Tests
+ *
+ * Tests for the main ruvector module exports and integration.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ isRuvectorAvailable,
+ getRuvectorVersion,
+ createQLearningRouter,
+ createASTAnalyzer,
+ createDiffClassifier,
+ createCoverageRouter,
+ QLearningRouter,
+ ASTAnalyzer,
+ DiffClassifier,
+ CoverageRouter,
+ // Graph analyzer exports (function-based API)
+ buildDependencyGraph,
+ analyzeGraph,
+ analyzeMinCutBoundaries,
+ analyzeModuleCommunities,
+ detectCircularDependencies,
+ exportToDot,
+ loadRuVector,
+ fallbackMinCut,
+ fallbackLouvain,
+} from '../../src/ruvector/index.js';
+
+// Mock all ruvector modules
+vi.mock('@ruvector/core', () => ({
+ createQLearning: vi.fn(() => null),
+ version: '1.0.0',
+}));
+
+vi.mock('@ruvector/ast', () => ({
+ createASTAnalyzer: vi.fn(() => null),
+}));
+
+vi.mock('@ruvector/diff', () => ({
+ createDiffClassifier: vi.fn(() => null),
+}));
+
+vi.mock('@ruvector/coverage', () => ({
+ createCoverageRouter: vi.fn(() => null),
+}));
+
+vi.mock('@ruvector/wasm', () => ({
+ minCut: vi.fn(() => null),
+ louvain: vi.fn(() => null),
+}));
+
+describe('RuVector Module Exports', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('isRuvectorAvailable', () => {
+ it('should return boolean', async () => {
+ const result = await isRuvectorAvailable();
+ expect(typeof result).toBe('boolean');
+ });
+
+ it('should return false when ruvector is not installed', async () => {
+ vi.doMock('@ruvector/core', () => {
+ throw new Error('Module not found');
+ });
+
+ const result = await isRuvectorAvailable();
+ expect(result).toBe(false);
+ });
+ });
+
+ describe('getRuvectorVersion', () => {
+ it('should return version string or null', async () => {
+ const version = await getRuvectorVersion();
+ expect(version === null || typeof version === 'string').toBe(true);
+ });
+ });
+
+ describe('Factory Functions', () => {
+ it('should export createQLearningRouter', () => {
+ expect(typeof createQLearningRouter).toBe('function');
+ const router = createQLearningRouter();
+ expect(router).toBeInstanceOf(QLearningRouter);
+ });
+
+ it('should export createASTAnalyzer', () => {
+ expect(typeof createASTAnalyzer).toBe('function');
+ const analyzer = createASTAnalyzer();
+ expect(analyzer).toBeInstanceOf(ASTAnalyzer);
+ });
+
+ it('should export createDiffClassifier', () => {
+ expect(typeof createDiffClassifier).toBe('function');
+ const classifier = createDiffClassifier();
+ expect(classifier).toBeInstanceOf(DiffClassifier);
+ });
+
+ it('should export createCoverageRouter', () => {
+ expect(typeof createCoverageRouter).toBe('function');
+ const router = createCoverageRouter();
+ expect(router).toBeInstanceOf(CoverageRouter);
+ });
+ });
+
+ describe('Graph Analyzer Functions', () => {
+ it('should export buildDependencyGraph', () => {
+ expect(typeof buildDependencyGraph).toBe('function');
+ });
+
+ it('should export analyzeGraph', () => {
+ expect(typeof analyzeGraph).toBe('function');
+ });
+
+ it('should export analyzeMinCutBoundaries', () => {
+ expect(typeof analyzeMinCutBoundaries).toBe('function');
+ });
+
+ it('should export analyzeModuleCommunities', () => {
+ expect(typeof analyzeModuleCommunities).toBe('function');
+ });
+
+ it('should export detectCircularDependencies', () => {
+ expect(typeof detectCircularDependencies).toBe('function');
+ });
+
+ it('should export exportToDot', () => {
+ expect(typeof exportToDot).toBe('function');
+ });
+
+ it('should export loadRuVector', () => {
+ expect(typeof loadRuVector).toBe('function');
+ });
+
+ it('should export fallbackMinCut', () => {
+ expect(typeof fallbackMinCut).toBe('function');
+ });
+
+ it('should export fallbackLouvain', () => {
+ expect(typeof fallbackLouvain).toBe('function');
+ });
+ });
+
+ describe('Class Exports', () => {
+ it('should export QLearningRouter class', () => {
+ expect(QLearningRouter).toBeDefined();
+ const router = new QLearningRouter();
+ expect(router).toBeInstanceOf(QLearningRouter);
+ });
+
+ it('should export ASTAnalyzer class', () => {
+ expect(ASTAnalyzer).toBeDefined();
+ const analyzer = new ASTAnalyzer();
+ expect(analyzer).toBeInstanceOf(ASTAnalyzer);
+ });
+
+ it('should export DiffClassifier class', () => {
+ expect(DiffClassifier).toBeDefined();
+ const classifier = new DiffClassifier();
+ expect(classifier).toBeInstanceOf(DiffClassifier);
+ });
+
+ it('should export CoverageRouter class', () => {
+ expect(CoverageRouter).toBeDefined();
+ const router = new CoverageRouter();
+ expect(router).toBeInstanceOf(CoverageRouter);
+ });
+ });
+});
+
+describe('RuVector Integration Scenarios', () => {
+ describe('Code Analysis Workflow', () => {
+ it('should analyze TypeScript code and extract information', () => {
+ const analyzer = createASTAnalyzer();
+ const code = `
+import { helper } from './utils';
+
+export class UserService {
+ getUsers() {
+ return [];
+ }
+}
+
+export function createUser(name: string) {
+ return { name };
+}
+`;
+
+ const analysis = analyzer.analyze(code, 'user-service.ts');
+
+ expect(analysis.language).toBe('typescript');
+ expect(analysis.classes.length).toBeGreaterThan(0);
+ expect(analysis.functions.length).toBeGreaterThan(0);
+ expect(analysis.imports).toContain('./utils');
+ expect(analysis.exports).toContain('UserService');
+ expect(analysis.exports).toContain('createUser');
+ });
+ });
+
+ describe('Diff Analysis Workflow', () => {
+ it('should analyze diff and provide classification', () => {
+ const classifier = createDiffClassifier();
+ const diff = `diff --git a/src/auth/login.ts b/src/auth/login.ts
+--- a/src/auth/login.ts
++++ b/src/auth/login.ts
+@@ -10,6 +10,10 @@ export async function login(username: string, password: string) {
+ const user = await findUser(username);
++
++ // Add rate limiting
++ if (await isRateLimited(username)) {
++ throw new Error('Too many attempts');
++ }
+
+ if (!user) {
+ throw new Error('User not found');
+`;
+
+ const files = classifier.parseDiff(diff);
+ const analysis = classifier.classify(files);
+
+ expect(analysis.files.length).toBe(1);
+ expect(analysis.overall.impactLevel).toBe('critical'); // auth file
+ expect(analysis.overall.testingStrategy.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Coverage Routing Workflow', () => {
+ it('should route based on coverage and suggest improvements', () => {
+ const router = createCoverageRouter();
+ const coverageData = {
+ 'src/critical/auth.ts': {
+ lineCoverage: 45,
+ branchCoverage: 30,
+ functionCoverage: 50,
+ statementCoverage: 45,
+ uncoveredLines: [10, 20, 30, 40, 50],
+ totalLines: 100,
+ coveredLines: 45,
+ },
+ 'src/utils/helper.ts': {
+ lineCoverage: 90,
+ branchCoverage: 85,
+ functionCoverage: 95,
+ statementCoverage: 90,
+ uncoveredLines: [5],
+ totalLines: 50,
+ coveredLines: 45,
+ },
+ };
+
+ const report = router.parseCoverage(coverageData, 'json');
+ const result = router.route(report);
+
+ expect(result.action).toBe('prioritize'); // Low overall coverage
+ expect(result.targetFiles.length).toBeGreaterThan(0);
+ expect(result.gaps.length).toBeGreaterThan(0);
+ expect(report.uncoveredCritical.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Dependency Graph Workflow', () => {
+ it('should build graph using function-based API', async () => {
+ // The function-based API builds graphs from directories
+ // For testing without actual files, we test that the functions are callable
+ expect(typeof buildDependencyGraph).toBe('function');
+ expect(typeof analyzeGraph).toBe('function');
+ expect(typeof detectCircularDependencies).toBe('function');
+ expect(typeof exportToDot).toBe('function');
+ });
+
+ it('should detect circular dependencies in graphs', () => {
+ // Create a mock graph with circular dependency
+ const graph = {
+ nodes: new Map([
+ ['a.ts', { id: 'a.ts', path: 'a.ts', name: 'a.ts', type: 'file', imports: ['./b'], exports: ['a'], size: 100 }],
+ ['b.ts', { id: 'b.ts', path: 'b.ts', name: 'b.ts', type: 'file', imports: ['./a'], exports: ['b'], size: 100 }],
+ ]),
+ edges: [
+ { source: 'a.ts', target: 'b.ts', type: 'import', weight: 1 },
+ { source: 'b.ts', target: 'a.ts', type: 'import', weight: 1 },
+ ],
+ metadata: { rootDir: '.', totalFiles: 2, totalEdges: 2, buildTime: 0 },
+ };
+
+ const cycles = detectCircularDependencies(graph as any);
+ expect(Array.isArray(cycles)).toBe(true);
+ });
+
+ it('should export graph to DOT format using GraphAnalysisResult', () => {
+ // exportToDot takes GraphAnalysisResult, not DependencyGraph
+ const analysisResult = {
+ graph: {
+ nodes: new Map([
+ ['a.ts', { id: 'a.ts', path: 'a.ts', name: 'a.ts', type: 'file', imports: [], exports: ['a'], size: 100 }],
+ ]),
+ edges: [],
+ metadata: { rootDir: '.', totalFiles: 1, totalEdges: 0, buildTime: 0 },
+ },
+ circularDependencies: [],
+ statistics: { nodeCount: 1, edgeCount: 0, avgDegree: 0, maxDegree: 0, density: 0, componentCount: 1 },
+ };
+
+ const dot = exportToDot(analysisResult as any);
+ expect(dot).toContain('digraph');
+ });
+ });
+
+ describe('Q-Learning Task Routing Workflow', () => {
+ it('should learn and improve routing decisions', async () => {
+ const router = createQLearningRouter({
+ explorationInitial: 0.1, // Low exploration for predictable tests
+ });
+
+ // Train the router with feedback
+ router.update('implement user authentication', 'coder', 10.0);
+ router.update('write unit tests for auth', 'tester', 10.0);
+ router.update('review security of auth module', 'reviewer', 10.0);
+ router.update('design database schema', 'architect', 10.0);
+
+ // After training, router should make informed decisions
+ const coderDecision = router.route('implement new feature', false);
+ const testerDecision = router.route('write tests for feature', false);
+
+ expect(coderDecision.confidence).toBeGreaterThan(0);
+ expect(testerDecision.confidence).toBeGreaterThan(0);
+ expect(coderDecision.alternatives.length).toBeGreaterThan(0);
+ });
+
+ it('should persist and restore learning', () => {
+ const router1 = createQLearningRouter();
+
+ // Train router 1
+ router1.update('task1', 'coder', 10.0);
+ router1.update('task2', 'tester', 8.0);
+
+ // Export state
+ const exported = router1.export();
+
+ // Create new router and import
+ const router2 = createQLearningRouter();
+ router2.import(exported);
+
+ // Verify state was restored
+ expect(router2.getStats().qTableSize).toBe(router1.getStats().qTableSize);
+ });
+ });
+
+ describe('Combined Workflow', () => {
+ it('should use multiple analyzers together', () => {
+ // 1. Analyze code structure
+ const astAnalyzer = createASTAnalyzer();
+ const code = `
+export function processOrder(order: Order) {
+ if (!order.items.length) {
+ throw new Error('Empty order');
+ }
+ return calculateTotal(order);
+}
+`;
+ const astAnalysis = astAnalyzer.analyze(code, 'order.ts');
+
+ // 2. Use function-based graph API with GraphAnalysisResult
+ const mockAnalysisResult = {
+ graph: {
+ nodes: new Map([
+ ['order.ts', { id: 'order.ts', path: 'order.ts', name: 'order.ts', type: 'file', imports: ['./utils'], exports: astAnalysis.exports, size: 200 }],
+ ['utils.ts', { id: 'utils.ts', path: 'utils.ts', name: 'utils.ts', type: 'file', imports: [], exports: ['calculateTotal'], size: 100 }],
+ ]),
+ edges: [{ source: 'order.ts', target: 'utils.ts', type: 'import', weight: 1 }],
+ metadata: { rootDir: '.', totalFiles: 2, totalEdges: 1, buildTime: 0 },
+ },
+ circularDependencies: [],
+ statistics: { nodeCount: 2, edgeCount: 1, avgDegree: 0.5, maxDegree: 1, density: 0.5, componentCount: 1 },
+ };
+ const dotOutput = exportToDot(mockAnalysisResult as any);
+
+ // 3. Check coverage
+ const coverageRouter = createCoverageRouter();
+ const coverageReport = coverageRouter.parseCoverage({
+ 'order.ts': {
+ lineCoverage: 60,
+ branchCoverage: 50,
+ functionCoverage: 100,
+ statementCoverage: 60,
+ uncoveredLines: [3, 4],
+ totalLines: 10,
+ coveredLines: 6,
+ },
+ }, 'json');
+
+ const coverageResult = coverageRouter.route(coverageReport);
+
+ // 4. Route to appropriate agent
+ const qRouter = createQLearningRouter();
+ qRouter.update('write tests for order processing', 'tester', 10.0);
+ const routeDecision = qRouter.route('add tests for order.ts', false);
+
+ // Verify integration
+ expect(astAnalysis.functions.length).toBeGreaterThan(0);
+ expect(mockAnalysisResult.graph.nodes.size).toBeGreaterThan(0);
+ expect(dotOutput).toContain('digraph');
+ expect(coverageResult.targetFiles.length).toBeGreaterThan(0);
+ expect(routeDecision.route).toBeDefined();
+ });
+ });
+});
+
+describe('Error Handling', () => {
+ it('should handle invalid inputs gracefully', () => {
+ const astAnalyzer = createASTAnalyzer();
+ expect(() => astAnalyzer.analyze('', 'empty.ts')).not.toThrow();
+
+ const diffClassifier = createDiffClassifier();
+ expect(() => diffClassifier.parseDiff('')).not.toThrow();
+
+ // Graph analyzer - detectCircularDependencies with proper structure
+ const emptyGraph = {
+ nodes: new Map(),
+ edges: [],
+ metadata: { rootDir: '.', totalFiles: 0, totalEdges: 0, buildTime: 0 },
+ };
+ expect(() => detectCircularDependencies(emptyGraph as any)).not.toThrow();
+
+ // exportToDot requires GraphAnalysisResult
+ const emptyAnalysisResult = {
+ graph: emptyGraph,
+ circularDependencies: [],
+ statistics: { nodeCount: 0, edgeCount: 0, avgDegree: 0, maxDegree: 0, density: 0, componentCount: 0 },
+ };
+ expect(() => exportToDot(emptyAnalysisResult as any)).not.toThrow();
+
+ const coverageRouter = createCoverageRouter();
+ expect(() => coverageRouter.parseCoverage({}, 'json')).not.toThrow();
+
+ const qRouter = createQLearningRouter();
+ expect(() => qRouter.route('')).not.toThrow();
+ });
+
+ it('should handle malformed data gracefully', () => {
+ const coverageRouter = createCoverageRouter();
+
+ // Invalid LCOV
+ expect(() => coverageRouter.parseCoverage('invalid lcov data', 'lcov')).not.toThrow();
+
+ // Invalid Cobertura
+ expect(() => coverageRouter.parseCoverage('<invalid>xml</invalid>', 'cobertura')).not.toThrow();
+
+ // Note: parseCoverage may throw for certain invalid inputs - that's expected behavior
+ // The key is that it handles valid formats properly
+ });
+});
+
+describe('Performance', () => {
+ it('should handle large graph operations efficiently', () => {
+ // Generate large mock graph
+ const nodes = new Map();
+ const graphEdges = [];
+ for (let i = 0; i < 100; i++) {
+ nodes.set(`module${i}/file.ts`, {
+ id: `module${i}/file.ts`,
+ path: `src/module${i}/file.ts`,
+ name: `file${i}.ts`,
+ type: 'file',
+ imports: i > 0 ? [`../module${i-1}/file`] : [],
+ exports: [`export${i}`],
+ size: 100,
+ });
+ if (i > 0) {
+ graphEdges.push({ source: `module${i}/file.ts`, target: `module${i-1}/file.ts`, type: 'import', weight: 1 });
+ }
+ }
+
+ const graph = {
+ nodes,
+ edges: graphEdges,
+ metadata: { rootDir: '.', totalFiles: 100, totalEdges: 99, buildTime: 0 },
+ };
+ const analysisResult = {
+ graph,
+ circularDependencies: [],
+ statistics: { nodeCount: 100, edgeCount: 99, avgDegree: 0.99, maxDegree: 1, density: 0.01, componentCount: 1 },
+ };
+
+ const startTime = performance.now();
+ const cycles = detectCircularDependencies(graph as any);
+ const dot = exportToDot(analysisResult as any);
+ const duration = performance.now() - startTime;
+
+ expect(nodes.size).toBe(100);
+ expect(Array.isArray(cycles)).toBe(true);
+ expect(dot).toContain('digraph');
+ expect(duration).toBeLessThan(1000); // Should complete within 1 second
+ });
+
+ it('should cache results for performance', () => {
+ const astAnalyzer = createASTAnalyzer();
+ const code = 'function test() { return 1; }';
+
+ // First analysis
+ const start1 = performance.now();
+ astAnalyzer.analyze(code, 'test.ts');
+ const duration1 = performance.now() - start1;
+
+ // Cached analysis
+ const start2 = performance.now();
+ astAnalyzer.analyze(code, 'test.ts');
+ const duration2 = performance.now() - start2;
+
+ // Cached should be faster (or at least not significantly slower)
+ expect(duration2).toBeLessThanOrEqual(duration1 + 5);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/q-learning-router.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/q-learning-router.test.ts
new file mode 100644
index 0000000000..7c9ef8f444
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/q-learning-router.test.ts
@@ -0,0 +1,324 @@
+/**
+ * Q-Learning Router Tests
+ *
+ * Tests for the Q-Learning based task routing system.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { QLearningRouter, createQLearningRouter, type RouteDecision } from '../../src/ruvector/q-learning-router';
+
+// Mock the @ruvector/core module
+vi.mock('@ruvector/core', () => ({
+ createQLearning: vi.fn(() => null),
+}));
+
+describe('QLearningRouter', () => {
+ let router: QLearningRouter;
+
+ beforeEach(() => {
+ router = new QLearningRouter();
+ });
+
+ afterEach(() => {
+ router.reset();
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it('should create router with default config', () => {
+ const stats = router.getStats();
+ expect(stats.epsilon).toBe(1.0);
+ expect(stats.qTableSize).toBe(0);
+ expect(stats.updateCount).toBe(0);
+ });
+
+ it('should create router with custom config', () => {
+ const customRouter = new QLearningRouter({
+ learningRate: 0.2,
+ gamma: 0.95,
+ explorationInitial: 0.5,
+ numActions: 4,
+ });
+ const stats = customRouter.getStats();
+ expect(stats.epsilon).toBe(0.5);
+ });
+ });
+
+ describe('initialize', () => {
+ it('should initialize without ruvector (fallback mode)', async () => {
+ await router.initialize();
+ const stats = router.getStats();
+ expect(stats.useNative).toBe(0);
+ });
+
+ it('should handle ruvector import failure gracefully', async () => {
+ vi.doMock('@ruvector/core', () => {
+ throw new Error('Module not found');
+ });
+ await router.initialize();
+ const stats = router.getStats();
+ expect(stats.useNative).toBe(0);
+ });
+ });
+
+ describe('route', () => {
+ it('should return valid route decision', () => {
+ const decision = router.route('implement feature X');
+ expect(decision).toHaveProperty('route');
+ expect(decision).toHaveProperty('confidence');
+ expect(decision).toHaveProperty('qValues');
+ expect(decision).toHaveProperty('explored');
+ expect(decision).toHaveProperty('alternatives');
+ });
+
+ it('should return route from valid ROUTE_NAMES', () => {
+ const validRoutes = ['coder', 'tester', 'reviewer', 'architect', 'researcher', 'optimizer', 'debugger', 'documenter'];
+ const decision = router.route('test task');
+ expect(validRoutes).toContain(decision.route);
+ });
+
+ it('should have confidence between 0 and 1', () => {
+ const decision = router.route('any task');
+ expect(decision.confidence).toBeGreaterThanOrEqual(0);
+ expect(decision.confidence).toBeLessThanOrEqual(1);
+ });
+
+ it('should return qValues array with correct length', () => {
+ const decision = router.route('test');
+ expect(decision.qValues).toHaveLength(8);
+ });
+
+ it('should return alternatives sorted by score', () => {
+ // Update Q-values to have clear ordering
+ router.update('task', 'coder', 10);
+ router.update('task', 'tester', 5);
+ router.update('task', 'reviewer', 3);
+
+ const decision = router.route('task', false);
+ expect(decision.alternatives.length).toBeLessThanOrEqual(3);
+ for (let i = 0; i < decision.alternatives.length - 1; i++) {
+ expect(decision.alternatives[i].score).toBeGreaterThanOrEqual(decision.alternatives[i + 1].score);
+ }
+ });
+
+ it('should explore with high epsilon', () => {
+ // With epsilon = 1.0, should always explore
+ const decisions = Array.from({ length: 100 }, () => router.route('task'));
+ const exploredCount = decisions.filter(d => d.explored).length;
+ expect(exploredCount).toBeGreaterThan(50); // Most should be exploration
+ });
+
+ it('should exploit when explore=false', () => {
+ const decision = router.route('task', false);
+ expect(decision.explored).toBe(false);
+ });
+ });
+
+ describe('update', () => {
+ it('should update Q-values and return TD error', () => {
+ const tdError = router.update('task context', 'coder', 1.0);
+ expect(typeof tdError).toBe('number');
+ });
+
+ it('should increase Q-value for positive reward', () => {
+ const beforeDecision = router.route('context', false);
+ const coderIdx = beforeDecision.qValues.findIndex((v, i) =>
+ ['coder', 'tester', 'reviewer', 'architect', 'researcher', 'optimizer', 'debugger', 'documenter'][i] === 'coder'
+ );
+ const beforeQ = beforeDecision.qValues[coderIdx];
+
+ router.update('context', 'coder', 10.0);
+
+ const afterDecision = router.route('context', false);
+ const afterQ = afterDecision.qValues[coderIdx];
+ expect(afterQ).toBeGreaterThan(beforeQ);
+ });
+
+ it('should handle invalid action gracefully', () => {
+ const tdError = router.update('context', 'invalid_action', 1.0);
+ expect(tdError).toBe(0);
+ });
+
+ it('should decay epsilon over updates', () => {
+ const initialEpsilon = router.getStats().epsilon;
+ for (let i = 0; i < 100; i++) {
+ router.update(`context_${i}`, 'coder', 1.0);
+ }
+ const finalEpsilon = router.getStats().epsilon;
+ expect(finalEpsilon).toBeLessThan(initialEpsilon);
+ });
+
+ it('should track average TD error', () => {
+ router.update('c1', 'coder', 5.0);
+ router.update('c2', 'tester', 3.0);
+ const stats = router.getStats();
+ expect(stats.avgTDError).toBeGreaterThan(0);
+ });
+
+ it('should update with next context (non-terminal)', () => {
+ const tdError = router.update('current', 'coder', 1.0, 'next');
+ expect(typeof tdError).toBe('number');
+ });
+
+ it('should prune Q-table when exceeding maxStates', () => {
+ const smallRouter = new QLearningRouter({ maxStates: 10 });
+ for (let i = 0; i < 20; i++) {
+ smallRouter.update(`unique_context_${i}`, 'coder', 1.0);
+ }
+ const stats = smallRouter.getStats();
+ expect(stats.qTableSize).toBeLessThanOrEqual(10);
+ });
+ });
+
+ describe('getStats', () => {
+ it('should return all expected statistics', () => {
+ const stats = router.getStats();
+ expect(stats).toHaveProperty('updateCount');
+ expect(stats).toHaveProperty('qTableSize');
+ expect(stats).toHaveProperty('epsilon');
+ expect(stats).toHaveProperty('avgTDError');
+ expect(stats).toHaveProperty('stepCount');
+ expect(stats).toHaveProperty('useNative');
+ });
+
+ it('should update stats after operations', () => {
+ const before = router.getStats();
+ expect(before.updateCount).toBe(0);
+
+ router.update('test', 'coder', 1.0);
+
+ const after = router.getStats();
+ expect(after.updateCount).toBe(1);
+ expect(after.qTableSize).toBe(1);
+ });
+ });
+
+ describe('reset', () => {
+ it('should clear Q-table', () => {
+ router.update('test', 'coder', 1.0);
+ expect(router.getStats().qTableSize).toBe(1);
+
+ router.reset();
+ expect(router.getStats().qTableSize).toBe(0);
+ });
+
+ it('should reset epsilon to initial value', () => {
+ for (let i = 0; i < 100; i++) {
+ router.update(`ctx_${i}`, 'coder', 1.0);
+ }
+ expect(router.getStats().epsilon).toBeLessThan(1.0);
+
+ router.reset();
+ expect(router.getStats().epsilon).toBe(1.0);
+ });
+
+ it('should reset update count', () => {
+ router.update('test', 'coder', 1.0);
+ expect(router.getStats().updateCount).toBe(1);
+
+ router.reset();
+ expect(router.getStats().updateCount).toBe(0);
+ });
+ });
+
+ describe('export/import', () => {
+ it('should export Q-table data', () => {
+ router.update('context1', 'coder', 5.0);
+ router.update('context2', 'tester', 3.0);
+
+ const exported = router.export();
+ expect(Object.keys(exported).length).toBe(2);
+ expect(exported).toHaveProperty(Object.keys(exported)[0]);
+ });
+
+ it('should export qValues and visits for each state', () => {
+ router.update('test', 'coder', 1.0);
+ const exported = router.export();
+ const firstKey = Object.keys(exported)[0];
+
+ expect(exported[firstKey]).toHaveProperty('qValues');
+ expect(exported[firstKey]).toHaveProperty('visits');
+ expect(Array.isArray(exported[firstKey].qValues)).toBe(true);
+ });
+
+ it('should import Q-table data', () => {
+ const data = {
+ 'state_123': { qValues: [1, 2, 3, 4, 5, 6, 7, 8], visits: 5 },
+ 'state_456': { qValues: [8, 7, 6, 5, 4, 3, 2, 1], visits: 3 },
+ };
+
+ router.import(data);
+ expect(router.getStats().qTableSize).toBe(2);
+ });
+
+ it('should restore Q-values after import', () => {
+ router.update('original', 'coder', 10.0);
+ const exported = router.export();
+
+ router.reset();
+ expect(router.getStats().qTableSize).toBe(0);
+
+ router.import(exported);
+ expect(router.getStats().qTableSize).toBe(1);
+ });
+
+ it('should clear existing data on import', () => {
+ router.update('old', 'coder', 1.0);
+ router.import({ 'new_state': { qValues: [1,2,3,4,5,6,7,8], visits: 1 } });
+
+ expect(router.getStats().qTableSize).toBe(1);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty context', () => {
+ const decision = router.route('');
+ expect(decision.route).toBeDefined();
+ });
+
+ it('should handle very long context', () => {
+ const longContext = 'x'.repeat(10000);
+ const decision = router.route(longContext);
+ expect(decision.route).toBeDefined();
+ });
+
+ it('should handle unicode in context', () => {
+ const decision = router.route('implement feature with unicode: \u00e9\u00e8\u00ea');
+ expect(decision.route).toBeDefined();
+ });
+
+ it('should handle special characters in context', () => {
+ const decision = router.route('fix bug in file: src/utils/*.ts');
+ expect(decision.route).toBeDefined();
+ });
+
+ it('should handle numeric context', () => {
+ const decision = router.route('12345');
+ expect(decision.route).toBeDefined();
+ });
+
+ it('should maintain consistency for same context', () => {
+ // After learning, same context should give consistent results
+ router.update('consistent_context', 'coder', 100.0);
+
+ const decisions = Array.from({ length: 10 }, () =>
+ router.route('consistent_context', false)
+ );
+
+ const routes = decisions.map(d => d.route);
+ expect(new Set(routes).size).toBe(1); // All same route
+ });
+ });
+});
+
+describe('createQLearningRouter', () => {
+ it('should create router instance', () => {
+ const router = createQLearningRouter();
+ expect(router).toBeInstanceOf(QLearningRouter);
+ });
+
+ it('should accept config', () => {
+ const router = createQLearningRouter({ learningRate: 0.5 });
+ expect(router).toBeInstanceOf(QLearningRouter);
+ });
+});
diff --git a/v3/implementation/adrs/ADR-017-ruvector-integration.md b/v3/implementation/adrs/ADR-017-ruvector-integration.md
index aaf3dce71d..12c606a84f 100644
--- a/v3/implementation/adrs/ADR-017-ruvector-integration.md
+++ b/v3/implementation/adrs/ADR-017-ruvector-integration.md
@@ -1,9 +1,10 @@
# ADR-017: RuVector Integration Architecture
-**Status:** Proposed
+**Status:** Accepted
**Date:** 2026-01-07
+**Completion Date:** 2026-01-07
**Author:** System Architecture Designer
-**Version:** 1.0.0
+**Version:** 1.1.0
## Context