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 edit:

rUv64c75638fb2b
diff --git a/v3/@claude-flow/cli/src/commands/start.ts b/v3/@claude-flow/cli/src/commands/start.ts
index c3aa165534..cd8898874d 100644
--- a/v3/@claude-flow/cli/src/commands/start.ts
+++ b/v3/@claude-flow/cli/src/commands/start.ts
@@ -49,9 +49,9 @@ function parseSimpleYaml(content: string): Record<string, unknown> {
value = false;
} else if (value === 'null') {
value = null;
- } else if (!isNaN(Number(value)) && value !== '') {
+ } else if (!isNaN(Number(value as string)) && value !== '') {
value = Number(value);
- } else if (value.startsWith('"') && value.endsWith('"')) {
+ } else if (typeof value === 'string' && value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
diff --git a/v3/@claude-flow/testing/src/v2-compat/api-compat.test.ts b/v3/@claude-flow/testing/src/v2-compat/api-compat.test.ts
new file mode 100644
index 0000000000..45fc19ccfc
--- /dev/null
+++ b/v3/@claude-flow/testing/src/v2-compat/api-compat.test.ts
@@ -0,0 +1,590 @@
+/**
+ * V2 API Compatibility Tests
+ *
+ * Tests that V2 import paths work via aliases and class interfaces match.
+ * Verifies method signatures and type compatibility.
+ *
+ * @module v3/testing/v2-compat/api-compat.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
+import {
+ V2CompatibilityValidator,
+ V2_API_INTERFACES,
+ type V2APIInterface,
+ type ValidationResult,
+} from './compatibility-validator.js';
+
+/**
+ * Mock V3 module registry for testing
+ */
+interface MockModuleRegistry {
+ getClass: Mock<[string], MockClass | null>;
+ getClasses: Mock<[], string[]>;
+ resolveImport: Mock<[string], string | null>;
+ getMethodSignature: Mock<[string, string], string | null>;
+ checkTypeCompatibility: Mock<[string, string], boolean>;
+}
+
+/**
+ * Mock class representation
+ */
+interface MockClass {
+ name: string;
+ v3Name: string;
+ methods: MockMethod[];
+ staticMethods: MockMethod[];
+ properties: MockProperty[];
+}
+
+/**
+ * Mock method representation
+ */
+interface MockMethod {
+ name: string;
+ signature: string;
+ v2Signature?: string;
+ compatible: boolean;
+}
+
+/**
+ * Mock property representation
+ */
+interface MockProperty {
+ name: string;
+ type: string;
+ readonly: boolean;
+}
+
+/**
+ * V3 class implementations mapping
+ */
+const V3_CLASSES: Record<string, MockClass> = {
+ 'UnifiedSwarmCoordinator': {
+ name: 'UnifiedSwarmCoordinator',
+ v3Name: 'UnifiedSwarmCoordinator',
+ methods: [
+ { name: 'initialize', signature: '(config?: SwarmConfig): Promise<void>', compatible: true },
+ { name: 'spawn', signature: '(agentType: string, config?: AgentConfig): Promise<Agent>', v2Signature: '(type: string, config?: AgentConfig): Promise<Agent>', compatible: true },
+ { name: 'addAgent', signature: '(agent: Agent): Promise<void>', compatible: true },
+ { name: 'removeAgent', signature: '(agentId: string): Promise<void>', compatible: true },
+ { name: 'broadcast', signature: '(message: Message): Promise<void>', compatible: true },
+ { name: 'consensus', signature: '(proposal: Proposal): Promise<ConsensusResult>', compatible: true },
+ { name: 'getStatus', signature: '(): Promise<SwarmStatus>', compatible: true },
+ { name: 'shutdown', signature: '(): Promise<void>', compatible: true },
+ { name: 'init', signature: '(topology: string): Promise<void>', compatible: true },
+ ],
+ staticMethods: [],
+ properties: [
+ { name: 'topology', type: 'string', readonly: true },
+ { name: 'agentCount', type: 'number', readonly: true },
+ { name: 'status', type: 'SwarmStatus', readonly: true },
+ ],
+ },
+ 'UnifiedMemoryService': {
+ name: 'UnifiedMemoryService',
+ v3Name: 'UnifiedMemoryService',
+ methods: [
+ { name: 'store', signature: '(entry: MemoryEntry): Promise<string>', compatible: true },
+ { name: 'search', signature: '(query: string, options?: SearchOptions): Promise<MemoryEntry[]>', v2Signature: '(search: string): Promise<MemoryEntry[]>', compatible: true },
+ { name: 'query', signature: '(search: string): Promise<MemoryEntry[]>', compatible: true },
+ { name: 'delete', signature: '(id: string): Promise<boolean>', compatible: true },
+ { name: 'clear', signature: '(): Promise<void>', compatible: true },
+ { name: 'getStats', signature: '(): Promise<MemoryStats>', compatible: true },
+ ],
+ staticMethods: [],
+ properties: [
+ { name: 'backend', type: 'string', readonly: true },
+ { name: 'stats', type: 'MemoryStats', readonly: true },
+ ],
+ },
+ 'AgentLifecycleService': {
+ name: 'AgentLifecycleService',
+ v3Name: 'AgentLifecycleService',
+ methods: [
+ { name: 'spawn', signature: '(config: AgentConfig): Promise<Agent>', compatible: true },
+ { name: 'terminate', signature: '(id: string): Promise<void>', compatible: true },
+ { name: 'list', signature: '(): Promise<Agent[]>', compatible: true },
+ { name: 'getInfo', signature: '(id: string): Promise<AgentInfo>', compatible: true },
+ { name: 'getStatus', signature: '(id: string): Promise<AgentStatus>', compatible: true },
+ ],
+ staticMethods: [],
+ properties: [
+ { name: 'agents', type: 'Map<string, Agent>', readonly: true },
+ ],
+ },
+ 'TaskExecutionService': {
+ name: 'TaskExecutionService',
+ v3Name: 'TaskExecutionService',
+ methods: [
+ { name: 'create', signature: '(definition: TaskDefinition): Promise<Task>', compatible: true },
+ { name: 'assign', signature: '(taskId: string, agentId: string): Promise<void>', compatible: true },
+ { name: 'complete', signature: '(taskId: string, result?: TaskResult): Promise<void>', v2Signature: '(taskId: string, result?: any): Promise<void>', compatible: true },
+ { name: 'getStatus', signature: '(taskId: string): Promise<TaskStatus>', compatible: true },
+ ],
+ staticMethods: [],
+ properties: [
+ { name: 'tasks', type: 'Map<string, Task>', readonly: true },
+ ],
+ },
+};
+
+/**
+ * V2 to V3 import alias mapping
+ */
+const IMPORT_ALIASES: Record<string, string> = {
+ 'claude-flow/hive-mind': '@claude-flow/swarm',
+ 'claude-flow/swarm': '@claude-flow/swarm',
+ 'claude-flow/memory': '@claude-flow/memory',
+ 'claude-flow/agents': '@claude-flow/agent-lifecycle',
+ 'claude-flow/tasks': '@claude-flow/task-execution',
+ 'claude-flow/hooks': '@claude-flow/hooks',
+ 'claude-flow/config': '@claude-flow/config',
+ 'claude-flow': '@claude-flow/core',
+};
+
+/**
+ * V2 to V3 class name mapping
+ */
+const CLASS_ALIASES: Record<string, string> = {
+ 'HiveMind': 'UnifiedSwarmCoordinator',
+ 'SwarmCoordinator': 'UnifiedSwarmCoordinator',
+ 'MemoryManager': 'UnifiedMemoryService',
+ 'AgentManager': 'AgentLifecycleService',
+ 'TaskOrchestrator': 'TaskExecutionService',
+};
+
+/**
+ * Create mock module registry
+ */
+function createMockModuleRegistry(): MockModuleRegistry {
+ return {
+ getClass: vi.fn().mockImplementation((name: string) => {
+ const v3Name = CLASS_ALIASES[name] || name;
+ return V3_CLASSES[v3Name] || null;
+ }),
+ getClasses: vi.fn().mockReturnValue(Object.keys(V3_CLASSES)),
+ resolveImport: vi.fn().mockImplementation((path: string) => {
+ return IMPORT_ALIASES[path] || null;
+ }),
+ getMethodSignature: vi.fn().mockImplementation((className: string, methodName: string) => {
+ const v3Name = CLASS_ALIASES[className] || className;
+ const classInfo = V3_CLASSES[v3Name];
+ if (!classInfo) return null;
+
+ const method = classInfo.methods.find(m => m.name === methodName);
+ return method?.signature || null;
+ }),
+ checkTypeCompatibility: vi.fn().mockImplementation((v2Type: string, v3Type: string) => {
+ // Simplified type compatibility check
+ if (v2Type === v3Type) return true;
+ if (v2Type === 'any') return true;
+ if (v3Type.includes(v2Type)) return true;
+ return false;
+ }),
+ };
+}
+
+describe('V2 API Compatibility', () => {
+ let validator: V2CompatibilityValidator;
+ let mockRegistry: MockModuleRegistry;
+
+ beforeEach(() => {
+ mockRegistry = createMockModuleRegistry();
+ validator = new V2CompatibilityValidator({
+ verbose: false,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('Import Path Aliases', () => {
+ it.each(Object.entries(IMPORT_ALIASES))('should resolve V2 import "%s" to V3 "%s"', (v2Path, v3Path) => {
+ const resolved = mockRegistry.resolveImport(v2Path);
+
+ expect(resolved).toBe(v3Path);
+ });
+
+ it('should resolve claude-flow/hive-mind to @claude-flow/swarm', () => {
+ const resolved = mockRegistry.resolveImport('claude-flow/hive-mind');
+
+ expect(resolved).toBe('@claude-flow/swarm');
+ });
+
+ it('should resolve claude-flow/memory to @claude-flow/memory', () => {
+ const resolved = mockRegistry.resolveImport('claude-flow/memory');
+
+ expect(resolved).toBe('@claude-flow/memory');
+ });
+
+ it('should return null for unknown import paths', () => {
+ const resolved = mockRegistry.resolveImport('unknown-package');
+
+ expect(resolved).toBeNull();
+ });
+ });
+
+ describe('Class Name Aliases', () => {
+ it.each(Object.entries(CLASS_ALIASES))('should map V2 class "%s" to V3 "%s"', (v2Name, v3Name) => {
+ const classInfo = mockRegistry.getClass(v2Name);
+
+ expect(classInfo).not.toBeNull();
+ expect(classInfo?.v3Name).toBe(v3Name);
+ });
+
+ it('should get HiveMind as UnifiedSwarmCoordinator', () => {
+ const classInfo = mockRegistry.getClass('HiveMind');
+
+ expect(classInfo).not.toBeNull();
+ expect(classInfo?.name).toBe('UnifiedSwarmCoordinator');
+ });
+
+ it('should get MemoryManager as UnifiedMemoryService', () => {
+ const classInfo = mockRegistry.getClass('MemoryManager');
+
+ expect(classInfo).not.toBeNull();
+ expect(classInfo?.name).toBe('UnifiedMemoryService');
+ });
+ });
+
+ describe('HiveMind Interface', () => {
+ const hiveMindInterface = V2_API_INTERFACES.find(i => i.name === 'HiveMind')!;
+
+ it('should have all HiveMind methods available', () => {
+ const classInfo = mockRegistry.getClass('HiveMind');
+
+ expect(classInfo).not.toBeNull();
+
+ for (const method of hiveMindInterface.methods) {
+ const hasMethod = classInfo!.methods.some(m => m.name === method.name);
+ expect(hasMethod).toBe(true);
+ }
+ });
+
+ it('should have compatible initialize signature', () => {
+ const signature = mockRegistry.getMethodSignature('HiveMind', 'initialize');
+
+ expect(signature).toContain('Promise<void>');
+ });
+
+ it('should have compatible spawn signature', () => {
+ const signature = mockRegistry.getMethodSignature('HiveMind', 'spawn');
+
+ expect(signature).toContain('Promise<Agent>');
+ });
+
+ it('should have compatible getStatus signature', () => {
+ const signature = mockRegistry.getMethodSignature('HiveMind', 'getStatus');
+
+ expect(signature).toContain('Promise');
+ });
+
+ it('should have compatible shutdown signature', () => {
+ const signature = mockRegistry.getMethodSignature('HiveMind', 'shutdown');
+
+ expect(signature).toContain('Promise<void>');
+ });
+ });
+
+ describe('SwarmCoordinator Interface', () => {
+ const swarmInterface = V2_API_INTERFACES.find(i => i.name === 'SwarmCoordinator')!;
+
+ it('should have all SwarmCoordinator methods available', () => {
+ const classInfo = mockRegistry.getClass('SwarmCoordinator');
+
+ expect(classInfo).not.toBeNull();
+
+ for (const method of swarmInterface.methods) {
+ const hasMethod = classInfo!.methods.some(m => m.name === method.name);
+ expect(hasMethod).toBe(true);
+ }
+ });
+
+ it('should have compatible init signature', () => {
+ const signature = mockRegistry.getMethodSignature('SwarmCoordinator', 'init');
+
+ expect(signature).toContain('topology');
+ expect(signature).toContain('Promise<void>');
+ });
+
+ it('should have compatible addAgent signature', () => {
+ const signature = mockRegistry.getMethodSignature('SwarmCoordinator', 'addAgent');
+
+ expect(signature).toContain('Agent');
+ expect(signature).toContain('Promise<void>');
+ });
+
+ it('should have compatible broadcast signature', () => {
+ const signature = mockRegistry.getMethodSignature('SwarmCoordinator', 'broadcast');
+
+ expect(signature).toContain('Message');
+ });
+
+ it('should have compatible consensus signature', () => {
+ const signature = mockRegistry.getMethodSignature('SwarmCoordinator', 'consensus');
+
+ expect(signature).toContain('Proposal');
+ expect(signature).toContain('ConsensusResult');
+ });
+ });
+
+ describe('MemoryManager Interface', () => {
+ const memoryInterface = V2_API_INTERFACES.find(i => i.name === 'MemoryManager')!;
+
+ it('should have all MemoryManager methods available', () => {
+ const classInfo = mockRegistry.getClass('MemoryManager');
+
+ expect(classInfo).not.toBeNull();
+
+ for (const method of memoryInterface.methods) {
+ const hasMethod = classInfo!.methods.some(m =>
+ m.name === method.name || (method.name === 'query' && m.name === 'search')
+ );
+ expect(hasMethod).toBe(true);
+ }
+ });
+
+ it('should have compatible store signature', () => {
+ const signature = mockRegistry.getMethodSignature('MemoryManager', 'store');
+
+ expect(signature).toContain('MemoryEntry');
+ expect(signature).toContain('Promise<string>');
+ });
+
+ it('should have query aliased to search', () => {
+ const classInfo = mockRegistry.getClass('MemoryManager');
+ const hasQuery = classInfo!.methods.some(m => m.name === 'query');
+ const hasSearch = classInfo!.methods.some(m => m.name === 'search');
+
+ expect(hasQuery || hasSearch).toBe(true);
+ });
+
+ it('should have compatible delete signature', () => {
+ const signature = mockRegistry.getMethodSignature('MemoryManager', 'delete');
+
+ expect(signature).toContain('Promise<boolean>');
+ });
+
+ it('should have compatible getStats signature', () => {
+ const signature = mockRegistry.getMethodSignature('MemoryManager', 'getStats');
+
+ expect(signature).toContain('MemoryStats');
+ });
+ });
+
+ describe('AgentManager Interface', () => {
+ const agentInterface = V2_API_INTERFACES.find(i => i.name === 'AgentManager')!;
+
+ it('should have all AgentManager methods available', () => {
+ const classInfo = mockRegistry.getClass('AgentManager');
+
+ expect(classInfo).not.toBeNull();
+
+ for (const method of agentInterface.methods) {
+ const hasMethod = classInfo!.methods.some(m => m.name === method.name);
+ expect(hasMethod).toBe(true);
+ }
+ });
+
+ it('should have compatible spawn signature', () => {
+ const signature = mockRegistry.getMethodSignature('AgentManager', 'spawn');
+
+ expect(signature).toContain('AgentConfig');
+ expect(signature).toContain('Promise<Agent>');
+ });
+
+ it('should have compatible terminate signature', () => {
+ const signature = mockRegistry.getMethodSignature('AgentManager', 'terminate');
+
+ expect(signature).toContain('Promise<void>');
+ });
+
+ it('should have compatible list signature', () => {
+ const signature = mockRegistry.getMethodSignature('AgentManager', 'list');
+
+ expect(signature).toContain('Promise<Agent[]>');
+ });
+
+ it('should have compatible getInfo signature', () => {
+ const signature = mockRegistry.getMethodSignature('AgentManager', 'getInfo');
+
+ expect(signature).toContain('AgentInfo');
+ });
+ });
+
+ describe('TaskOrchestrator Interface', () => {
+ const taskInterface = V2_API_INTERFACES.find(i => i.name === 'TaskOrchestrator')!;
+
+ it('should have all TaskOrchestrator methods available', () => {
+ const classInfo = mockRegistry.getClass('TaskOrchestrator');
+
+ expect(classInfo).not.toBeNull();
+
+ for (const method of taskInterface.methods) {
+ const hasMethod = classInfo!.methods.some(m => m.name === method.name);
+ expect(hasMethod).toBe(true);
+ }
+ });
+
+ it('should have compatible create signature', () => {
+ const signature = mockRegistry.getMethodSignature('TaskOrchestrator', 'create');
+
+ expect(signature).toContain('TaskDefinition');
+ expect(signature).toContain('Promise<Task>');
+ });
+
+ it('should have compatible assign signature', () => {
+ const signature = mockRegistry.getMethodSignature('TaskOrchestrator', 'assign');
+
+ expect(signature).toContain('taskId');
+ expect(signature).toContain('agentId');
+ });
+
+ it('should have compatible complete signature', () => {
+ const signature = mockRegistry.getMethodSignature('TaskOrchestrator', 'complete');
+
+ expect(signature).toContain('taskId');
+ expect(signature).toContain('Promise<void>');
+ });
+
+ it('should have compatible getStatus signature', () => {
+ const signature = mockRegistry.getMethodSignature('TaskOrchestrator', 'getStatus');
+
+ expect(signature).toContain('TaskStatus');
+ });
+ });
+
+ describe('Type Compatibility', () => {
+ it('should accept any type as compatible', () => {
+ const compatible = mockRegistry.checkTypeCompatibility('any', 'string');
+
+ expect(compatible).toBe(true);
+ });
+
+ it('should accept same types as compatible', () => {
+ const compatible = mockRegistry.checkTypeCompatibility('string', 'string');
+
+ expect(compatible).toBe(true);
+ });
+
+ it('should accept subtype compatibility', () => {
+ const compatible = mockRegistry.checkTypeCompatibility('Agent', 'Agent | null');
+
+ expect(compatible).toBe(true);
+ });
+ });
+
+ describe('Full API Validation', () => {
+ it('should pass full API validation', async () => {
+ const result: ValidationResult = await validator.validateAPI();
+
+ expect(result.category).toBe('api');
+ expect(result.totalChecks).toBeGreaterThan(0);
+ expect(result.passedChecks).toBeGreaterThan(0);
+ });
+
+ it('should detect all V2 API interfaces', async () => {
+ const result = await validator.validateAPI();
+ const classChecks = result.checks.filter(c => c.name.startsWith('API Class:'));
+
+ expect(classChecks.length).toBeGreaterThanOrEqual(V2_API_INTERFACES.length);
+ });
+
+ it('should verify method signatures', async () => {
+ const result = await validator.validateAPI();
+ const methodChecks = result.checks.filter(c => c.name.includes('Method:'));
+
+ expect(methodChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should provide migration paths', async () => {
+ const result = await validator.validateAPI();
+ const withMigration = result.checks.filter(c => c.migrationPath);
+
+ expect(withMigration.length).toBeGreaterThan(0);
+ });
+
+ it('should report minimal breaking changes', async () => {
+ const result = await validator.validateAPI();
+
+ // Most interfaces should be compatible
+ expect(result.breakingChanges).toBeLessThan(result.totalChecks * 0.2);
+ });
+ });
+
+ describe('Backward Compatible Usage Patterns', () => {
+ it('should support V2 HiveMind instantiation pattern', () => {
+ // V2 pattern: const hive = new HiveMind(config);
+ // V3 equivalent: const hive = new UnifiedSwarmCoordinator(config);
+ const classInfo = mockRegistry.getClass('HiveMind');
+
+ expect(classInfo).not.toBeNull();
+ expect(classInfo?.methods.some(m => m.name === 'initialize')).toBe(true);
+ });
+
+ it('should support V2 MemoryManager query pattern', () => {
+ // V2 pattern: const results = await memory.query('search term');
+ // V3 equivalent: const results = await memory.search('search term');
+ const classInfo = mockRegistry.getClass('MemoryManager');
+ const hasQueryOrSearch = classInfo?.methods.some(m =>
+ m.name === 'query' || m.name === 'search'
+ );
+
+ expect(hasQueryOrSearch).toBe(true);
+ });
+
+ it('should support V2 agent spawn pattern', () => {
+ // V2 pattern: const agent = await manager.spawn({ type: 'coder' });
+ // V3 equivalent: const agent = await lifecycle.spawn({ agentType: 'coder' });
+ const classInfo = mockRegistry.getClass('AgentManager');
+
+ expect(classInfo?.methods.some(m => m.name === 'spawn')).toBe(true);
+ });
+ });
+});
+
+describe('API Coverage', () => {
+ it('should define all core V2 API interfaces', () => {
+ const coreInterfaces = ['HiveMind', 'SwarmCoordinator', 'MemoryManager', 'AgentManager', 'TaskOrchestrator'];
+
+ for (const name of coreInterfaces) {
+ const iface = V2_API_INTERFACES.find(i => i.name === name);
+ expect(iface).toBeDefined();
+ }
+ });
+
+ it('should have V3 equivalents for all interfaces', () => {
+ for (const iface of V2_API_INTERFACES) {
+ expect(iface.v3Equivalent).toBeDefined();
+ expect(iface.v3Equivalent).not.toBe('');
+ }
+ });
+
+ it('should define methods for all interfaces', () => {
+ for (const iface of V2_API_INTERFACES) {
+ expect(iface.methods.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('should define method signatures correctly', () => {
+ for (const iface of V2_API_INTERFACES) {
+ for (const method of iface.methods) {
+ expect(method.name).toBeDefined();
+ expect(method.signature).toBeDefined();
+ expect(method.signature).toContain(':');
+ }
+ }
+ });
+
+ it('should cover common method patterns', () => {
+ const allMethods = V2_API_INTERFACES.flatMap(i => i.methods.map(m => m.name));
+
+ expect(allMethods).toContain('initialize');
+ expect(allMethods).toContain('spawn');
+ expect(allMethods).toContain('store');
+ expect(allMethods).toContain('create');
+ expect(allMethods).toContain('getStatus');
+ });
+});
diff --git a/v3/@claude-flow/testing/src/v2-compat/cli-compat.test.ts b/v3/@claude-flow/testing/src/v2-compat/cli-compat.test.ts
new file mode 100644
index 0000000000..6904127daf
--- /dev/null
+++ b/v3/@claude-flow/testing/src/v2-compat/cli-compat.test.ts
@@ -0,0 +1,484 @@
+/**
+ * V2 CLI Compatibility Tests
+ *
+ * Tests all 25 V2 CLI commands work via compatibility layer or native V3 equivalents.
+ * Verifies flag compatibility and output format compatibility.
+ *
+ * @module v3/testing/v2-compat/cli-compat.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
+import {
+ V2CompatibilityValidator,
+ V2_CLI_COMMANDS,
+ type V2CLICommand,
+ type ValidationResult,
+} from './compatibility-validator.js';
+
+/**
+ * Mock CLI executor for testing
+ */
+interface MockCLIExecutor {
+ execute: Mock<[string, string[]], Promise<{ success: boolean; output: string; exitCode: number }>>;
+ getCommands: Mock<[], string[]>;
+ parseOutput: Mock<[string], Record<string, unknown>>;
+}
+
+/**
+ * Create mock CLI executor
+ */
+function createMockCLIExecutor(): MockCLIExecutor {
+ const v3Commands = [
+ 'init', 'start', 'stop', 'status', 'config',
+ 'agent spawn', 'agent list', 'agent terminate', 'agent status',
+ 'swarm init', 'swarm status', 'swarm scale',
+ 'memory list', 'memory search', 'memory clear',
+ 'hooks pre-edit', 'hooks post-edit', 'hooks pre-command', 'hooks post-command',
+ 'hooks route', 'hooks pretrain', 'hooks metrics',
+ ];
+
+ return {
+ execute: vi.fn().mockImplementation(async (command: string, args: string[]) => {
+ // Simulate V3 CLI behavior with V2 command translation
+ const commandTranslation: Record<string, string> = {
+ 'hive-mind init': 'swarm init',
+ 'hive-mind status': 'swarm status',
+ 'hive-mind spawn': 'agent spawn',
+ 'neural init': 'hooks pretrain',
+ 'goal init': 'hooks pretrain',
+ 'memory query': 'memory search',
+ 'agent info': 'agent status',
+ };
+
+ const translatedCommand = commandTranslation[command] || command;
+ const isSupported = v3Commands.some(c =>
+ c === translatedCommand || translatedCommand.startsWith(c.split(' ')[0])
+ );
+
+ if (!isSupported) {
+ return {
+ success: false,
+ output: `Error: Command "${command}" not found`,
+ exitCode: 1,
+ };
+ }
+
+ // Simulate successful output
+ const outputMap: Record<string, string> = {
+ 'status': JSON.stringify({ status: 'running', agents: 0, memory: 'healthy' }),
+ 'agent list': JSON.stringify([]),
+ 'swarm status': JSON.stringify({ topology: 'hierarchical-mesh', agents: 0 }),
+ 'memory list': JSON.stringify([]),
+ 'hooks metrics': JSON.stringify({ patterns: 0, successRate: 0 }),
+ };
+
+ return {
+ success: true,
+ output: outputMap[translatedCommand] || 'OK',
+ exitCode: 0,
+ };
+ }),
+ getCommands: vi.fn().mockReturnValue(v3Commands),
+ parseOutput: vi.fn().mockImplementation((output: string) => {
+ try {
+ return JSON.parse(output);
+ } catch {
+ return { raw: output };
+ }
+ }),
+ };
+}
+
+describe('V2 CLI Compatibility', () => {
+ let validator: V2CompatibilityValidator;
+ let mockCLI: MockCLIExecutor;
+
+ beforeEach(() => {
+ mockCLI = createMockCLIExecutor();
+ validator = new V2CompatibilityValidator({
+ verbose: false,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('Core Commands', () => {
+ const coreCommands = V2_CLI_COMMANDS.filter(c =>
+ ['init', 'start', 'stop', 'status', 'config'].includes(c.name)
+ );
+
+ it.each(coreCommands)('should support V2 command: $name', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ expect(result.success).toBe(true);
+ expect(result.exitCode).toBe(0);
+ });
+
+ it('should support init command with --force flag', async () => {
+ const result = await mockCLI.execute('init', ['--force']);
+
+ expect(result.success).toBe(true);
+ expect(mockCLI.execute).toHaveBeenCalledWith('init', ['--force']);
+ });
+
+ it('should support init command with --template flag', async () => {
+ const result = await mockCLI.execute('init', ['--template', 'minimal']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support status command with --json flag', async () => {
+ const result = await mockCLI.execute('status', ['--json']);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(parsed).toHaveProperty('status');
+ });
+
+ it('should support config command with --list flag', async () => {
+ const result = await mockCLI.execute('config', ['--list']);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Agent Commands', () => {
+ const agentCommands = V2_CLI_COMMANDS.filter(c => c.name.startsWith('agent'));
+
+ it.each(agentCommands)('should support V2 command: $name', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support agent spawn with --type flag', async () => {
+ const result = await mockCLI.execute('agent spawn', ['--type', 'coder']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support agent spawn with --id flag', async () => {
+ const result = await mockCLI.execute('agent spawn', ['--id', 'my-agent']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support agent list with --status filter', async () => {
+ const result = await mockCLI.execute('agent list', ['--status', 'active']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support agent terminate with --force flag', async () => {
+ const result = await mockCLI.execute('agent terminate', ['--force', 'agent-1']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should translate agent info to agent status', async () => {
+ const result = await mockCLI.execute('agent info', ['agent-1']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support alias "a spawn" for "agent spawn"', async () => {
+ // Aliases should be handled by CLI framework
+ const result = await mockCLI.execute('agent spawn', ['--type', 'coder']);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Swarm Commands', () => {
+ const swarmCommands = V2_CLI_COMMANDS.filter(c => c.name.startsWith('swarm'));
+
+ it.each(swarmCommands)('should support V2 command: $name', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support swarm init with --topology flag', async () => {
+ const result = await mockCLI.execute('swarm init', ['--topology', 'hierarchical-mesh']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support swarm init with --max-agents flag', async () => {
+ const result = await mockCLI.execute('swarm init', ['--max-agents', '15']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support swarm status with --detailed flag', async () => {
+ const result = await mockCLI.execute('swarm status', ['--detailed']);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(parsed).toHaveProperty('topology');
+ });
+
+ it('should support swarm scale with --up flag', async () => {
+ const result = await mockCLI.execute('swarm scale', ['--up', '3']);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Memory Commands', () => {
+ const memoryCommands = V2_CLI_COMMANDS.filter(c => c.name.startsWith('memory'));
+
+ it.each(memoryCommands)('should support V2 command: $name', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support memory list with --type filter', async () => {
+ const result = await mockCLI.execute('memory list', ['--type', 'pattern']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should translate memory query to memory search', async () => {
+ const result = await mockCLI.execute('memory query', ['--search', 'test']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support memory clear with --force flag', async () => {
+ const result = await mockCLI.execute('memory clear', ['--force']);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Hooks Commands', () => {
+ const hooksCommands = V2_CLI_COMMANDS.filter(c => c.name.startsWith('hooks'));
+
+ it.each(hooksCommands)('should support V2 command: $name', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support hooks pre-edit with file path', async () => {
+ const result = await mockCLI.execute('hooks pre-edit', ['--file', '/path/to/file.ts']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support hooks post-edit with success flag', async () => {
+ const result = await mockCLI.execute('hooks post-edit', ['--file', '/path/to/file.ts', '--success', 'true']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support hooks route with task description', async () => {
+ const result = await mockCLI.execute('hooks route', ['--task', 'implement feature']);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should support hooks metrics with --dashboard flag', async () => {
+ const result = await mockCLI.execute('hooks metrics', ['--dashboard']);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Deprecated Commands', () => {
+ const deprecatedCommands = V2_CLI_COMMANDS.filter(c => c.deprecated);
+
+ it.each(deprecatedCommands)('should support deprecated command: $name (with warning)', async (cmd: V2CLICommand) => {
+ const result = await mockCLI.execute(cmd.name, []);
+
+ // Deprecated commands should still work
+ expect(result.success).toBe(true);
+ });
+
+ it('should translate hive-mind init to swarm init', async () => {
+ const result = await mockCLI.execute('hive-mind init', []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should translate neural init to hooks pretrain', async () => {
+ const result = await mockCLI.execute('neural init', []);
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should translate goal init to hooks pretrain', async () => {
+ const result = await mockCLI.execute('goal init', []);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Output Format Compatibility', () => {
+ it('should return JSON output for status command', async () => {
+ const result = await mockCLI.execute('status', ['--json']);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(typeof parsed).toBe('object');
+ });
+
+ it('should return agent list as array', async () => {
+ const result = await mockCLI.execute('agent list', []);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(Array.isArray(parsed)).toBe(true);
+ });
+
+ it('should return swarm status as object', async () => {
+ const result = await mockCLI.execute('swarm status', []);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(parsed).toHaveProperty('topology');
+ });
+
+ it('should return memory list as array', async () => {
+ const result = await mockCLI.execute('memory list', []);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(Array.isArray(parsed)).toBe(true);
+ });
+
+ it('should return hooks metrics as object', async () => {
+ const result = await mockCLI.execute('hooks metrics', []);
+
+ expect(result.success).toBe(true);
+ const parsed = mockCLI.parseOutput(result.output);
+ expect(parsed).toHaveProperty('patterns');
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should return error for unknown command', async () => {
+ const result = await mockCLI.execute('unknown-command', []);
+
+ expect(result.success).toBe(false);
+ expect(result.exitCode).toBe(1);
+ expect(result.output).toContain('not found');
+ });
+
+ it('should handle missing required arguments gracefully', async () => {
+ // Most commands should work without arguments for listing operations
+ const result = await mockCLI.execute('agent list', []);
+
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('Full CLI Validation', () => {
+ it('should pass full CLI validation', async () => {
+ const result: ValidationResult = await validator.validateCLI();
+
+ expect(result.category).toBe('cli');
+ expect(result.totalChecks).toBeGreaterThan(0);
+ expect(result.passedChecks).toBeGreaterThan(0);
+ });
+
+ it('should detect all 25 V2 CLI commands', async () => {
+ const result = await validator.validateCLI();
+ const commandChecks = result.checks.filter(c => c.name.startsWith('CLI:'));
+
+ // Should have checks for all 25 commands
+ expect(commandChecks.length).toBeGreaterThanOrEqual(25);
+ });
+
+ it('should identify deprecated commands', async () => {
+ const result = await validator.validateCLI();
+ const deprecatedChecks = result.checks.filter(c =>
+ c.name.includes('hive-mind') || c.name.includes('neural') || c.name.includes('goal')
+ );
+
+ expect(deprecatedChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should verify flag compatibility', async () => {
+ const result = await validator.validateCLI();
+ const flagChecks = result.checks.filter(c => c.name.includes('Flag:'));
+
+ expect(flagChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should report breaking changes for unsupported commands', async () => {
+ const result = await validator.validateCLI();
+
+ // All non-deprecated commands should be supported
+ const breakingNonDeprecated = result.checks.filter(c =>
+ c.breaking && !c.name.includes('deprecated')
+ );
+
+ // Expect minimal breaking changes in supported commands
+ expect(breakingNonDeprecated.length).toBeLessThan(5);
+ });
+
+ it('should provide migration paths', async () => {
+ const result = await validator.validateCLI();
+ const withMigration = result.checks.filter(c => c.migrationPath);
+
+ expect(withMigration.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('Alias Compatibility', () => {
+ it('should check all command aliases', async () => {
+ const result = await validator.validateCLI();
+ const aliasChecks = result.checks.filter(c => c.name.includes('Alias:'));
+
+ expect(aliasChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should verify common aliases work', async () => {
+ const commonAliases = ['i', 's', 'st', 'c', 'a spawn', 'a ls'];
+
+ for (const alias of commonAliases) {
+ // Aliases should map to valid commands
+ const aliasCmd = V2_CLI_COMMANDS.find(c => c.aliases.includes(alias));
+ expect(aliasCmd).toBeDefined();
+ }
+ });
+ });
+});
+
+describe('CLI Command Coverage', () => {
+ it('should test all 25 V2 CLI commands', () => {
+ expect(V2_CLI_COMMANDS.length).toBe(25);
+ });
+
+ it('should have V3 equivalents for all non-deprecated commands', () => {
+ const nonDeprecated = V2_CLI_COMMANDS.filter(c => !c.deprecated);
+
+ for (const cmd of nonDeprecated) {
+ expect(cmd.v3Equivalent).toBeDefined();
+ expect(cmd.v3Equivalent).not.toBe('');
+ }
+ });
+
+ it('should categorize commands correctly', () => {
+ const categories = {
+ core: ['init', 'start', 'stop', 'status', 'config'],
+ agent: V2_CLI_COMMANDS.filter(c => c.name.startsWith('agent')).map(c => c.name),
+ swarm: V2_CLI_COMMANDS.filter(c => c.name.startsWith('swarm')).map(c => c.name),
+ memory: V2_CLI_COMMANDS.filter(c => c.name.startsWith('memory')).map(c => c.name),
+ hooks: V2_CLI_COMMANDS.filter(c => c.name.startsWith('hooks')).map(c => c.name),
+ deprecated: V2_CLI_COMMANDS.filter(c => c.deprecated).map(c => c.name),
+ };
+
+ expect(categories.core.length).toBe(5);
+ expect(categories.agent.length).toBe(4);
+ expect(categories.swarm.length).toBe(3);
+ expect(categories.memory.length).toBe(3);
+ expect(categories.hooks.length).toBe(7);
+ expect(categories.deprecated.length).toBe(3);
+ });
+});
diff --git a/v3/@claude-flow/testing/src/v2-compat/hooks-compat.test.ts b/v3/@claude-flow/testing/src/v2-compat/hooks-compat.test.ts
new file mode 100644
index 0000000000..f74918e26d
--- /dev/null
+++ b/v3/@claude-flow/testing/src/v2-compat/hooks-compat.test.ts
@@ -0,0 +1,602 @@
+/**
+ * V2 Hooks Compatibility Tests
+ *
+ * Tests all 42 V2 hooks trigger correctly via compatibility layer.
+ * Verifies hook result format and learning integration.
+ *
+ * @module v3/testing/v2-compat/hooks-compat.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
+import {
+ V2CompatibilityValidator,
+ V2_HOOKS,
+ type V2Hook,
+ type ValidationResult,
+} from './compatibility-validator.js';
+
+/**
+ * Hook result type
+ */
+interface HookResult {
+ handled: boolean;
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ learningContext?: {
+ pattern?: string;
+ reward?: number;
+ sessionId?: string;
+ };
+}
+
+/**
+ * Mock hooks system for testing
+ */
+interface MockHooksSystem {
+ trigger: Mock<[string, Record<string, unknown>], Promise<HookResult>>;
+ register: Mock<[string, (params: unknown) => Promise<HookResult>], void>;
+ getHooks: Mock<[], string[]>;
+ isRegistered: Mock<[string], boolean>;
+ getHookInfo: Mock<[string], V2Hook | null>;
+ getLearningMetrics: Mock<[], { patterns: number; successRate: number }>;
+}
+
+/**
+ * Create mock hooks system
+ */
+function createMockHooksSystem(): MockHooksSystem {
+ const v3Hooks = V2_HOOKS.map(h => h.v3Equivalent || h.name);
+ const registeredHooks = new Set(v3Hooks);
+
+ return {
+ trigger: vi.fn().mockImplementation(async (name: string, params: Record<string, unknown>) => {
+ const isSupported = registeredHooks.has(name);
+
+ if (!isSupported) {
+ return {
+ handled: false,
+ success: false,
+ error: `Hook "${name}" not registered`,
+ };
+ }
+
+ // Simulate hook execution with learning context
+ return {
+ handled: true,
+ success: true,
+ data: { hookName: name, params },
+ learningContext: {
+ pattern: `${name}:success`,
+ reward: 1.0,
+ sessionId: `session-${Date.now()}`,
+ },
+ };
+ }),
+ register: vi.fn().mockImplementation((name: string) => {
+ registeredHooks.add(name);
+ }),
+ getHooks: vi.fn().mockReturnValue(v3Hooks),
+ isRegistered: vi.fn().mockImplementation((name: string) => registeredHooks.has(name)),
+ getHookInfo: vi.fn().mockImplementation((name: string) => {
+ return V2_HOOKS.find(h => h.name === name || h.v3Equivalent === name) || null;
+ }),
+ getLearningMetrics: vi.fn().mockReturnValue({
+ patterns: 100,
+ successRate: 0.85,
+ }),
+ };
+}
+
+describe('V2 Hooks Compatibility', () => {
+ let validator: V2CompatibilityValidator;
+ let mockHooks: MockHooksSystem;
+
+ beforeEach(() => {
+ mockHooks = createMockHooksSystem();
+ validator = new V2CompatibilityValidator({
+ verbose: false,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('Edit Hooks', () => {
+ const editHooks = V2_HOOKS.filter(h =>
+ h.name.includes('edit') || h.name.includes('create')
+ );
+
+ it.each(editHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ expect(result.success).toBe(true);
+ });
+
+ it('should trigger pre-edit hook with file path', async () => {
+ const result = await mockHooks.trigger('pre-edit', {
+ filePath: '/path/to/file.ts',
+ content: 'new content',
+ });
+
+ expect(result.handled).toBe(true);
+ expect(result.data).toHaveProperty('params');
+ });
+
+ it('should trigger post-edit hook with success status', async () => {
+ const result = await mockHooks.trigger('post-edit', {
+ filePath: '/path/to/file.ts',
+ success: true,
+ changes: { linesAdded: 10, linesRemoved: 5 },
+ });
+
+ expect(result.handled).toBe(true);
+ expect(result.learningContext).toBeDefined();
+ });
+
+ it('should include learning context in edit hooks', async () => {
+ const result = await mockHooks.trigger('post-edit', {
+ filePath: '/path/to/file.ts',
+ success: true,
+ });
+
+ expect(result.learningContext).toHaveProperty('pattern');
+ expect(result.learningContext).toHaveProperty('reward');
+ expect(result.learningContext).toHaveProperty('sessionId');
+ });
+ });
+
+ describe('Command Hooks', () => {
+ const commandHooks = V2_HOOKS.filter(h =>
+ h.name.includes('command') || h.name.includes('bash')
+ );
+
+ it.each(commandHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger pre-command hook with command details', async () => {
+ const result = await mockHooks.trigger('pre-command', {
+ command: 'npm',
+ args: ['install', 'vitest'],
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger post-command hook with exit status', async () => {
+ const result = await mockHooks.trigger('post-command', {
+ command: 'npm',
+ success: true,
+ output: 'added 50 packages',
+ });
+
+ expect(result.handled).toBe(true);
+ expect(result.learningContext?.reward).toBe(1.0);
+ });
+
+ it('should handle pre-bash as pre-command', async () => {
+ // pre-bash should map to pre-command in V3
+ const info = mockHooks.getHookInfo('pre-bash');
+
+ expect(info?.v3Equivalent).toBe('pre-command');
+ });
+ });
+
+ describe('Task Hooks', () => {
+ const taskHooks = V2_HOOKS.filter(h => h.name.includes('task'));
+
+ it.each(taskHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, p === 'task' ? { id: 'task-1' } : 'test'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger pre-task hook before task execution', async () => {
+ const result = await mockHooks.trigger('pre-task', {
+ task: { id: 'task-1', description: 'Test task' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger post-task hook with result', async () => {
+ const result = await mockHooks.trigger('post-task', {
+ task: { id: 'task-1' },
+ result: { success: true, output: 'completed' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger task-fail hook on failure', async () => {
+ const result = await mockHooks.trigger('task-fail', {
+ task: { id: 'task-1' },
+ error: 'Task failed: timeout',
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Agent Hooks', () => {
+ const agentHooks = V2_HOOKS.filter(h => h.name.startsWith('agent-'));
+
+ it.each(agentHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger agent-spawn hook with config', async () => {
+ const result = await mockHooks.trigger('agent-spawn', {
+ agentConfig: { type: 'coder', id: 'agent-1' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger agent-terminate hook with reason', async () => {
+ const result = await mockHooks.trigger('agent-terminate', {
+ agentId: 'agent-1',
+ reason: 'Task completed',
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger agent-message hook for inter-agent communication', async () => {
+ const result = await mockHooks.trigger('agent-message', {
+ from: 'agent-1',
+ to: 'agent-2',
+ message: { type: 'task-update', data: {} },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Swarm Hooks', () => {
+ const swarmHooks = V2_HOOKS.filter(h => h.name.startsWith('swarm-'));
+
+ it.each(swarmHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger swarm-init hook with topology', async () => {
+ const result = await mockHooks.trigger('swarm-init', {
+ topology: 'hierarchical-mesh',
+ config: { maxAgents: 15 },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger swarm-consensus hook with proposal', async () => {
+ const result = await mockHooks.trigger('swarm-consensus', {
+ proposal: { type: 'scale-up', count: 3 },
+ result: { approved: true, votes: 5 },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Memory Hooks', () => {
+ const memoryHooks = V2_HOOKS.filter(h => h.name.startsWith('memory-'));
+
+ it.each(memoryHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, p === 'entry' ? { id: 'mem-1' } : 'test'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger memory-store hook when storing', async () => {
+ const result = await mockHooks.trigger('memory-store', {
+ entry: { id: 'mem-1', content: 'test', type: 'pattern' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger memory-retrieve hook with results', async () => {
+ const result = await mockHooks.trigger('memory-retrieve', {
+ query: 'test search',
+ results: [{ id: 'mem-1', content: 'test' }],
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Learning Hooks', () => {
+ const learningHooks = V2_HOOKS.filter(h => h.name.startsWith('learning-'));
+
+ it.each(learningHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger learning-pattern hook for new patterns', async () => {
+ const result = await mockHooks.trigger('learning-pattern', {
+ pattern: { type: 'success', context: 'file-edit' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger learning-reward hook with trajectory', async () => {
+ const result = await mockHooks.trigger('learning-reward', {
+ trajectory: { actions: ['edit', 'test', 'commit'] },
+ reward: 0.95,
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger learning-distill hook for memory consolidation', async () => {
+ const result = await mockHooks.trigger('learning-distill', {
+ memories: [{ id: 'mem-1' }, { id: 'mem-2' }],
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Session Hooks', () => {
+ const sessionHooks = V2_HOOKS.filter(h => h.name.startsWith('session-'));
+
+ it.each(sessionHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger session-start hook with session ID', async () => {
+ const result = await mockHooks.trigger('session-start', {
+ sessionId: 'session-123',
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger session-end hook with metrics', async () => {
+ const result = await mockHooks.trigger('session-end', {
+ sessionId: 'session-123',
+ metrics: { duration: 3600, tasksCompleted: 10 },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Security Hooks', () => {
+ const securityHooks = V2_HOOKS.filter(h => h.name.startsWith('security-'));
+
+ it.each(securityHooks)('should support V2 hook: $name', async (hook: V2Hook) => {
+ const params = Object.fromEntries(
+ hook.parameters.map(p => [p, 'test-value'])
+ );
+
+ const result = await mockHooks.trigger(hook.v3Equivalent || hook.name, params);
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger security-alert hook for threats', async () => {
+ const result = await mockHooks.trigger('security-alert', {
+ alert: { type: 'suspicious-command', severity: 'high' },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger security-block hook for blocked operations', async () => {
+ const result = await mockHooks.trigger('security-block', {
+ operation: 'file-delete',
+ reason: 'Protected directory',
+ });
+
+ expect(result.handled).toBe(true);
+ });
+
+ it('should trigger security-audit hook for audit trail', async () => {
+ const result = await mockHooks.trigger('security-audit', {
+ action: 'config-change',
+ context: { user: 'system', timestamp: Date.now() },
+ });
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should return handled=false for unregistered hooks', async () => {
+ const result = await mockHooks.trigger('unknown-hook', {});
+
+ expect(result.handled).toBe(false);
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('not registered');
+ });
+
+ it('should handle empty parameters gracefully', async () => {
+ const result = await mockHooks.trigger('pre-edit', {});
+
+ expect(result.handled).toBe(true);
+ });
+ });
+
+ describe('Learning Integration', () => {
+ it('should include learning context in hook results', async () => {
+ const result = await mockHooks.trigger('post-edit', {
+ filePath: '/test.ts',
+ success: true,
+ });
+
+ expect(result.learningContext).toBeDefined();
+ expect(result.learningContext?.pattern).toBeDefined();
+ expect(result.learningContext?.reward).toBeDefined();
+ });
+
+ it('should track learning metrics', () => {
+ const metrics = mockHooks.getLearningMetrics();
+
+ expect(metrics).toHaveProperty('patterns');
+ expect(metrics).toHaveProperty('successRate');
+ expect(metrics.patterns).toBeGreaterThanOrEqual(0);
+ expect(metrics.successRate).toBeGreaterThanOrEqual(0);
+ expect(metrics.successRate).toBeLessThanOrEqual(1);
+ });
+
+ it('should provide session ID in learning context', async () => {
+ const result = await mockHooks.trigger('post-task', {
+ task: { id: 'task-1' },
+ result: { success: true },
+ });
+
+ expect(result.learningContext?.sessionId).toBeDefined();
+ expect(result.learningContext?.sessionId).toMatch(/^session-/);
+ });
+ });
+
+ describe('Full Hooks Validation', () => {
+ it('should pass full hooks validation', async () => {
+ const result: ValidationResult = await validator.validateHooks();
+
+ expect(result.category).toBe('hooks');
+ expect(result.totalChecks).toBeGreaterThan(0);
+ expect(result.passedChecks).toBeGreaterThan(0);
+ });
+
+ it('should detect all 42 V2 hooks', async () => {
+ const result = await validator.validateHooks();
+ const hookChecks = result.checks.filter(c =>
+ c.name.startsWith('Hook:') && !c.name.includes('Param') && !c.name.includes('Return')
+ );
+
+ expect(hookChecks.length).toBeGreaterThanOrEqual(42);
+ });
+
+ it('should verify hook parameters', async () => {
+ const result = await validator.validateHooks();
+ const paramChecks = result.checks.filter(c => c.name.includes('Param:'));
+
+ expect(paramChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should verify return type compatibility', async () => {
+ const result = await validator.validateHooks();
+ const returnChecks = result.checks.filter(c => c.name.includes('Return:'));
+
+ expect(returnChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should report minimal breaking changes', async () => {
+ const result = await validator.validateHooks();
+
+ // Most hooks should be supported
+ expect(result.breakingChanges).toBeLessThan(result.totalChecks * 0.1);
+ });
+ });
+});
+
+describe('Hooks Coverage', () => {
+ it('should test all 42 V2 hooks', () => {
+ expect(V2_HOOKS.length).toBe(42);
+ });
+
+ it('should have V3 equivalents for all hooks', () => {
+ for (const hook of V2_HOOKS) {
+ expect(hook.v3Equivalent).toBeDefined();
+ expect(hook.v3Equivalent).not.toBe('');
+ }
+ });
+
+ it('should categorize hooks correctly', () => {
+ const categories = {
+ edit: V2_HOOKS.filter(h => h.name.includes('edit') || h.name.includes('create')),
+ command: V2_HOOKS.filter(h => h.name.includes('command') || h.name.includes('bash')),
+ task: V2_HOOKS.filter(h => h.name.includes('task')),
+ agent: V2_HOOKS.filter(h => h.name.startsWith('agent-')),
+ swarm: V2_HOOKS.filter(h => h.name.startsWith('swarm-')),
+ memory: V2_HOOKS.filter(h => h.name.startsWith('memory-')),
+ learning: V2_HOOKS.filter(h => h.name.startsWith('learning-')),
+ session: V2_HOOKS.filter(h => h.name.startsWith('session-')),
+ config: V2_HOOKS.filter(h => h.name.startsWith('config-')),
+ error: V2_HOOKS.filter(h => h.name.startsWith('error-')),
+ perf: V2_HOOKS.filter(h => h.name.startsWith('perf-')),
+ security: V2_HOOKS.filter(h => h.name.startsWith('security-')),
+ };
+
+ expect(categories.edit.length).toBe(4);
+ expect(categories.command.length).toBe(4);
+ expect(categories.task.length).toBe(4);
+ expect(categories.agent.length).toBe(4);
+ expect(categories.swarm.length).toBe(4);
+ expect(categories.memory.length).toBe(4);
+ expect(categories.learning.length).toBe(4);
+ expect(categories.session.length).toBe(4);
+ expect(categories.config.length).toBe(3);
+ expect(categories.error.length).toBe(2);
+ expect(categories.perf.length).toBe(2);
+ expect(categories.security.length).toBe(3);
+ });
+
+ it('should define triggers correctly', () => {
+ for (const hook of V2_HOOKS) {
+ expect(hook.trigger).toBeDefined();
+ expect(hook.trigger).toMatch(/^(before|after|on):/);
+ }
+ });
+
+ it('should define parameters correctly', () => {
+ for (const hook of V2_HOOKS) {
+ expect(Array.isArray(hook.parameters)).toBe(true);
+ }
+ });
+
+ it('should define return types correctly', () => {
+ for (const hook of V2_HOOKS) {
+ expect(hook.returnType).toBe('HookResult');
+ }
+ });
+});
diff --git a/v3/@claude-flow/testing/src/v2-compat/mcp-compat.test.ts b/v3/@claude-flow/testing/src/v2-compat/mcp-compat.test.ts
new file mode 100644
index 0000000000..f1148a96bb
--- /dev/null
+++ b/v3/@claude-flow/testing/src/v2-compat/mcp-compat.test.ts
@@ -0,0 +1,557 @@
+/**
+ * V2 MCP Tool Compatibility Tests
+ *
+ * Tests all 65 V2 MCP tools work via name mapping and parameter translation.
+ * Verifies parameter translation and response format compatibility.
+ *
+ * @module v3/testing/v2-compat/mcp-compat.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
+import {
+ V2CompatibilityValidator,
+ V2_MCP_TOOLS,
+ type V2MCPTool,
+ type ValidationResult,
+} from './compatibility-validator.js';
+
+/**
+ * Tool name mapping from V2 to V3
+ */
+const TOOL_NAME_MAPPING: Record<string, string> = {
+ // Agent tools
+ 'dispatch_agent': 'agent/spawn',
+ 'agents/spawn': 'agent/spawn',
+ 'agents/list': 'agent/list',
+ 'agents/terminate': 'agent/terminate',
+ 'agents/info': 'agent/status',
+ 'agent/create': 'agent/spawn',
+
+ // Swarm tools
+ 'swarm_status': 'swarm/status',
+ 'swarm/get-status': 'swarm/status',
+ 'swarm/get-comprehensive-status': 'swarm/status',
+ 'mcp__ruv-swarm__swarm_init': 'swarm/init',
+ 'mcp__ruv-swarm__swarm_status': 'swarm/status',
+ 'mcp__ruv-swarm__agent_spawn': 'agent/spawn',
+ 'mcp__ruv-swarm__agent_list': 'agent/list',
+ 'mcp__ruv-swarm__agent_metrics': 'agent/status',
+
+ // Memory tools
+ 'memory/query': 'memory/search',
+ 'mcp__ruv-swarm__memory_usage': 'memory/list',
+
+ // Config tools
+ 'config/get': 'config/load',
+ 'config/update': 'config/save',
+
+ // Neural tools
+ 'mcp__ruv-swarm__neural_status': 'hooks/metrics',
+ 'mcp__ruv-swarm__neural_train': 'hooks/pretrain',
+};
+
+/**
+ * Mock MCP client for testing
+ */
+interface MockMCPClient {
+ callTool: Mock<[string, Record<string, unknown>], Promise<unknown>>;
+ getTools: Mock<[], string[]>;
+ translateToolName: Mock<[string], string>;
+ translateParams: Mock<[string, Record<string, unknown>], Record<string, unknown>>;
+}
+
+/**
+ * Create mock MCP client
+ */
+function createMockMCPClient(): MockMCPClient {
+ const v3Tools = [
+ 'agent/spawn', 'agent/list', 'agent/terminate', 'agent/status',
+ 'swarm/init', 'swarm/status', 'swarm/scale', 'swarm/consensus', 'swarm/broadcast',
+ 'memory/store', 'memory/search', 'memory/delete', 'memory/list',
+ 'task/create', 'task/assign', 'task/status', 'task/complete',
+ 'config/load', 'config/save',
+ 'hooks/metrics', 'hooks/pretrain',
+ 'github/pr-create', 'github/pr-review', 'github/issue-create',
+ ];
+
+ return {
+ callTool: vi.fn().mockImplementation(async (name: string, params: Record<string, unknown>) => {
+ const v3Name = TOOL_NAME_MAPPING[name] || name;
+
+ if (!v3Tools.includes(v3Name)) {
+ throw new Error(`Tool not found: ${name} (translated: ${v3Name})`);
+ }
+
+ // Simulate tool responses
+ const responses: Record<string, unknown> = {
+ 'agent/spawn': { id: 'agent-1', type: params.agentType || params.type, status: 'active' },
+ 'agent/list': [{ id: 'agent-1', type: 'coder', status: 'active' }],
+ 'agent/terminate': { success: true },
+ 'agent/status': { id: 'agent-1', metrics: { tasksCompleted: 0 } },
+ 'swarm/init': { id: 'swarm-1', topology: 'hierarchical-mesh' },
+ 'swarm/status': { agents: 0, topology: 'hierarchical-mesh', status: 'active' },
+ 'memory/store': { id: 'mem-1', stored: true },
+ 'memory/search': [{ id: 'mem-1', content: 'test' }],
+ 'memory/list': [{ id: 'mem-1', type: 'pattern' }],
+ 'task/create': { id: 'task-1', status: 'pending' },
+ 'config/load': { value: 'test-value' },
+ 'config/save': { success: true },
+ 'hooks/metrics': { patterns: 10, successRate: 0.85 },
+ 'hooks/pretrain': { trained: true, patterns: 100 },
+ };
+
+ return responses[v3Name] || { success: true };
+ }),
+ getTools: vi.fn().mockReturnValue(v3Tools),
+ translateToolName: vi.fn().mockImplementation((v2Name: string) => TOOL_NAME_MAPPING[v2Name] || v2Name),
+ translateParams: vi.fn().mockImplementation((toolName: string, params: Record<string, unknown>) => {
+ // Parameter translation logic
+ if (toolName === 'dispatch_agent' || toolName === 'agents/spawn') {
+ return {
+ agentType: params.type,
+ id: params.name,
+ config: {
+ capabilities: params.capabilities,
+ systemPrompt: params.systemPrompt,
+ },
+ priority: (params.priority as number) > 5 ? 'high' : 'normal',
+ };
+ }
+
+ if (toolName === 'memory/query') {
+ return {
+ query: params.search,
+ searchType: 'hybrid',
+ type: params.type,
+ limit: params.limit || 10,
+ };
+ }
+
+ if (toolName.includes('swarm_init')) {
+ return {
+ topology: params.topology || 'hierarchical-mesh',
+ maxAgents: params.maxAgents || 15,
+ config: {
+ consensusMechanism: params.consensus || 'majority',
+ },
+ };
+ }
+
+ return params;
+ }),
+ };
+}
+
+describe('V2 MCP Tool Compatibility', () => {
+ let validator: V2CompatibilityValidator;
+ let mockMCP: MockMCPClient;
+
+ beforeEach(() => {
+ mockMCP = createMockMCPClient();
+ validator = new V2CompatibilityValidator({
+ verbose: false,
+ });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('Agent Tools', () => {
+ const agentTools = V2_MCP_TOOLS.filter(t =>
+ t.name.includes('agent') || t.name === 'dispatch_agent'
+ );
+
+ it.each(agentTools)('should support V2 tool: $name', async (tool: V2MCPTool) => {
+ const params = Object.fromEntries(
+ Object.entries(tool.parameters)
+ .filter(([, def]) => def.required)
+ .map(([key, def]) => [key, def.type === 'string' ? 'test' : {}])
+ );
+
+ const result = await mockMCP.callTool(tool.name, params);
+
+ expect(result).toBeDefined();
+ });
+
+ it('should translate dispatch_agent to agent/spawn', () => {
+ const v3Name = mockMCP.translateToolName('dispatch_agent');
+
+ expect(v3Name).toBe('agent/spawn');
+ });
+
+ it('should translate agents/spawn to agent/spawn', () => {
+ const v3Name = mockMCP.translateToolName('agents/spawn');
+
+ expect(v3Name).toBe('agent/spawn');
+ });
+
+ it('should translate agents/info to agent/status', () => {
+ const v3Name = mockMCP.translateToolName('agents/info');
+
+ expect(v3Name).toBe('agent/status');
+ });
+
+ it('should translate agent parameters correctly', () => {
+ const v2Params = {
+ type: 'coder',
+ name: 'my-coder',
+ capabilities: ['coding'],
+ priority: 8,
+ };
+
+ const v3Params = mockMCP.translateParams('dispatch_agent', v2Params);
+
+ expect(v3Params.agentType).toBe('coder');
+ expect(v3Params.id).toBe('my-coder');
+ expect(v3Params.priority).toBe('high');
+ });
+
+ it('should handle mcp__ruv-swarm__agent_spawn', async () => {
+ const result = await mockMCP.callTool('mcp__ruv-swarm__agent_spawn', { type: 'coder' });
+
+ expect(result).toHaveProperty('id');
+ expect(result).toHaveProperty('type');
+ });
+ });
+
+ describe('Swarm Tools', () => {
+ const swarmTools = V2_MCP_TOOLS.filter(t => t.name.includes('swarm'));
+
+ it.each(swarmTools)('should support V2 tool: $name', async (tool: V2MCPTool) => {
+ const params = Object.fromEntries(
+ Object.entries(tool.parameters)
+ .filter(([, def]) => def.required)
+ .map(([key, def]) => [key, def.type === 'string' ? 'test' : {}])
+ );
+
+ const result = await mockMCP.callTool(tool.name, params);
+
+ expect(result).toBeDefined();
+ });
+
+ it('should translate swarm_status to swarm/status', () => {
+ const v3Name = mockMCP.translateToolName('swarm_status');
+
+ expect(v3Name).toBe('swarm/status');
+ });
+
+ it('should translate swarm/get-comprehensive-status to swarm/status', () => {
+ const v3Name = mockMCP.translateToolName('swarm/get-comprehensive-status');
+
+ expect(v3Name).toBe('swarm/status');
+ });
+
+ it('should translate swarm init parameters', () => {
+ const v2Params = {
+ topology: 'mesh',
+ maxAgents: 10,
+ consensus: 'quorum',
+ };
+
+ const v3Params = mockMCP.translateParams('mcp__ruv-swarm__swarm_init', v2Params);
+
+ expect(v3Params.topology).toBe('mesh');
+ expect(v3Params.maxAgents).toBe(10);
+ expect(v3Params.config).toHaveProperty('consensusMechanism');
+ });
+
+ it('should return compatible swarm status response', async () => {
+ const result = await mockMCP.callTool('swarm_status', {}) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('agents');
+ expect(result).toHaveProperty('topology');
+ expect(result).toHaveProperty('status');
+ });
+ });
+
+ describe('Memory Tools', () => {
+ const memoryTools = V2_MCP_TOOLS.filter(t => t.name.includes('memory'));
+
+ it.each(memoryTools)('should support V2 tool: $name', async (tool: V2MCPTool) => {
+ const params = Object.fromEntries(
+ Object.entries(tool.parameters)
+ .filter(([, def]) => def.required)
+ .map(([key, def]) => [key, def.type === 'string' ? 'test' : {}])
+ );
+
+ const result = await mockMCP.callTool(tool.name, params);
+
+ expect(result).toBeDefined();
+ });
+
+ it('should translate memory/query to memory/search', () => {
+ const v3Name = mockMCP.translateToolName('memory/query');
+
+ expect(v3Name).toBe('memory/search');
+ });
+
+ it('should translate memory query parameters', () => {
+ const v2Params = {
+ search: 'test query',
+ type: 'pattern',
+ limit: 20,
+ };
+
+ const v3Params = mockMCP.translateParams('memory/query', v2Params);
+
+ expect(v3Params.query).toBe('test query');
+ expect(v3Params.searchType).toBe('hybrid');
+ expect(v3Params.limit).toBe(20);
+ });
+
+ it('should return array from memory search', async () => {
+ const result = await mockMCP.callTool('memory/query', { search: 'test' });
+
+ expect(Array.isArray(result)).toBe(true);
+ });
+ });
+
+ describe('Config Tools', () => {
+ it('should translate config/get to config/load', () => {
+ const v3Name = mockMCP.translateToolName('config/get');
+
+ expect(v3Name).toBe('config/load');
+ });
+
+ it('should translate config/update to config/save', () => {
+ const v3Name = mockMCP.translateToolName('config/update');
+
+ expect(v3Name).toBe('config/save');
+ });
+
+ it('should handle config get operation', async () => {
+ const result = await mockMCP.callTool('config/get', { key: 'test.key' }) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('value');
+ });
+
+ it('should handle config update operation', async () => {
+ const result = await mockMCP.callTool('config/update', {
+ key: 'test.key',
+ value: 'new-value',
+ }) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('success');
+ });
+ });
+
+ describe('Task Tools', () => {
+ const taskTools = V2_MCP_TOOLS.filter(t => t.name.startsWith('task/'));
+
+ it.each(taskTools)('should support V2 tool: $name', async (tool: V2MCPTool) => {
+ const params = Object.fromEntries(
+ Object.entries(tool.parameters)
+ .filter(([, def]) => def.required)
+ .map(([key, def]) => [key, def.type === 'string' ? 'test' : 'test'])
+ );
+
+ const result = await mockMCP.callTool(tool.name, params);
+
+ expect(result).toBeDefined();
+ });
+
+ it('should create task with description', async () => {
+ const result = await mockMCP.callTool('task/create', {
+ description: 'Test task',
+ }) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('id');
+ expect(result).toHaveProperty('status');
+ });
+
+ it('should assign task to agent', async () => {
+ const result = await mockMCP.callTool('task/assign', {
+ taskId: 'task-1',
+ agentId: 'agent-1',
+ });
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('Neural/Learning Tools', () => {
+ it('should translate neural_status to hooks/metrics', () => {
+ const v3Name = mockMCP.translateToolName('mcp__ruv-swarm__neural_status');
+
+ expect(v3Name).toBe('hooks/metrics');
+ });
+
+ it('should translate neural_train to hooks/pretrain', () => {
+ const v3Name = mockMCP.translateToolName('mcp__ruv-swarm__neural_train');
+
+ expect(v3Name).toBe('hooks/pretrain');
+ });
+
+ it('should return compatible metrics response', async () => {
+ const result = await mockMCP.callTool('mcp__ruv-swarm__neural_status', {}) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('patterns');
+ expect(result).toHaveProperty('successRate');
+ });
+
+ it('should handle pretrain operation', async () => {
+ const result = await mockMCP.callTool('mcp__ruv-swarm__neural_train', {
+ data: { source: 'repo' },
+ }) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('trained');
+ });
+ });
+
+ describe('GitHub Tools', () => {
+ const githubTools = V2_MCP_TOOLS.filter(t => t.name.startsWith('github/'));
+
+ it.each(githubTools)('should support V2 tool: $name', async (tool: V2MCPTool) => {
+ const params = Object.fromEntries(
+ Object.entries(tool.parameters)
+ .filter(([, def]) => def.required)
+ .map(([key, def]) => {
+ if (def.type === 'number') return [key, 1];
+ return [key, 'test'];
+ })
+ );
+
+ const result = await mockMCP.callTool(tool.name, params);
+
+ expect(result).toBeDefined();
+ });
+
+ it('should handle PR creation', async () => {
+ const result = await mockMCP.callTool('github/pr-create', {
+ title: 'Test PR',
+ body: 'Test body',
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should handle PR review', async () => {
+ const result = await mockMCP.callTool('github/pr-review', {
+ prNumber: 123,
+ });
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('Error Handling', () => {
+ it('should throw for unknown tool', async () => {
+ await expect(mockMCP.callTool('unknown/tool', {}))
+ .rejects.toThrow('Tool not found');
+ });
+
+ it('should handle missing required parameters gracefully', async () => {
+ // Tool should still be callable even with empty params for testing
+ const result = await mockMCP.callTool('agent/list', {});
+
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('Full MCP Validation', () => {
+ it('should pass full MCP validation', async () => {
+ const result: ValidationResult = await validator.validateMCPTools();
+
+ expect(result.category).toBe('mcp');
+ expect(result.totalChecks).toBeGreaterThan(0);
+ expect(result.passedChecks).toBeGreaterThan(0);
+ });
+
+ it('should detect all V2 MCP tools', async () => {
+ const result = await validator.validateMCPTools();
+ const toolChecks = result.checks.filter(c => c.name.startsWith('MCP Tool:'));
+
+ expect(toolChecks.length).toBeGreaterThanOrEqual(V2_MCP_TOOLS.length);
+ });
+
+ it('should verify parameter translation', async () => {
+ const result = await validator.validateMCPTools();
+ const paramChecks = result.checks.filter(c => c.name.includes('Param:'));
+
+ expect(paramChecks.length).toBeGreaterThan(0);
+ });
+
+ it('should identify V3 equivalents', async () => {
+ const result = await validator.validateMCPTools();
+
+ for (const check of result.checks.filter(c => c.name.startsWith('MCP Tool:'))) {
+ if (check.passed && check.details) {
+ expect(check.details.v3Equivalent).toBeDefined();
+ }
+ }
+ });
+
+ it('should report breaking changes correctly', async () => {
+ const result = await validator.validateMCPTools();
+
+ // Most tools should have V3 equivalents
+ expect(result.breakingChanges).toBeLessThan(result.totalChecks * 0.2);
+ });
+ });
+
+ describe('Response Format Compatibility', () => {
+ it('should return consistent agent info format', async () => {
+ const result = await mockMCP.callTool('dispatch_agent', { type: 'coder' }) as Record<string, unknown>;
+
+ expect(result).toHaveProperty('id');
+ expect(result).toHaveProperty('type');
+ expect(result).toHaveProperty('status');
+ });
+
+ it('should return array for list operations', async () => {
+ const agentList = await mockMCP.callTool('agents/list', {});
+ const memoryList = await mockMCP.callTool('memory/query', { search: 'test' });
+
+ expect(Array.isArray(agentList)).toBe(true);
+ expect(Array.isArray(memoryList)).toBe(true);
+ });
+
+ it('should return success boolean for mutations', async () => {
+ const terminateResult = await mockMCP.callTool('agents/terminate', { id: 'agent-1' }) as Record<string, unknown>;
+ const configResult = await mockMCP.callTool('config/update', { key: 'k', value: 'v' }) as Record<string, unknown>;
+
+ expect(terminateResult).toHaveProperty('success');
+ expect(configResult).toHaveProperty('success');
+ });
+ });
+});
+
+describe('MCP Tool Coverage', () => {
+ it('should define at least 30 V2 MCP tools', () => {
+ expect(V2_MCP_TOOLS.length).toBeGreaterThanOrEqual(30);
+ });
+
+ it('should have V3 equivalents for most tools', () => {
+ const withEquivalent = V2_MCP_TOOLS.filter(t => t.v3Equivalent);
+
+ expect(withEquivalent.length).toBeGreaterThan(V2_MCP_TOOLS.length * 0.8);
+ });
+
+ it('should categorize tools correctly', () => {
+ const categories = {
+ agent: V2_MCP_TOOLS.filter(t => t.name.includes('agent') || t.name === 'dispatch_agent'),
+ swarm: V2_MCP_TOOLS.filter(t => t.name.includes('swarm')),
+ memory: V2_MCP_TOOLS.filter(t => t.name.includes('memory')),
+ config: V2_MCP_TOOLS.filter(t => t.name.includes('config')),
+ task: V2_MCP_TOOLS.filter(t => t.name.startsWith('task/')),
+ neural: V2_MCP_TOOLS.filter(t => t.name.includes('neural')),
+ github: V2_MCP_TOOLS.filter(t => t.name.startsWith('github/')),
+ coordinate: V2_MCP_TOOLS.filter(t => t.name.startsWith('coordinate/')),
+ };
+
+ expect(categories.agent.length).toBeGreaterThanOrEqual(6);
+ expect(categories.swarm.length).toBeGreaterThanOrEqual(5);
+ expect(categories.memory.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it('should define required parameters correctly', () => {
+ for (const tool of V2_MCP_TOOLS) {
+ for (const [, def] of Object.entries(tool.parameters)) {
+ expect(def).toHaveProperty('type');
+ expect(def).toHaveProperty('required');
+ expect(typeof def.required).toBe('boolean');
+ }
+ }
+ });
+});