🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
checkpoint: File edit:
rUvcf5829f8233a
diff --git a/v3/@claude-flow/testing/src/fixtures/index.ts b/v3/@claude-flow/testing/src/fixtures/index.tsindex f08bdd9081..2e2e195f7e 100644--- a/v3/@claude-flow/testing/src/fixtures/index.ts+++ b/v3/@claude-flow/testing/src/fixtures/index.ts@@ -4,14 +4,20 @@* Central export for all test fixtures*/-// Agent fixtures-export * from './agents.js';+// Agent fixtures (comprehensive)+export * from './agent-fixtures.js';-// Task fixtures-export * from './tasks.js';+// Memory fixtures (AgentDB, HNSW, ReasoningBank)+export * from './memory-fixtures.js';-// Memory entry fixtures-export * from './memory-entries.js';+// Swarm fixtures (topologies, coordination, consensus)+export * from './swarm-fixtures.js';++// MCP fixtures (tools, resources, prompts)+export * from './mcp-fixtures.js';-// Configuration fixtures+// Legacy exports for backward compatibility+export * from './agents.js';+export * from './tasks.js';+export * from './memory-entries.js';export * from './configurations.js';diff --git a/v3/@claude-flow/testing/src/fixtures/mcp-fixtures.ts b/v3/@claude-flow/testing/src/fixtures/mcp-fixtures.tsnew file mode 100644index 0000000000..ff35f15483--- /dev/null+++ b/v3/@claude-flow/testing/src/fixtures/mcp-fixtures.ts@@ -0,0 +1,1030 @@+/**+ * @claude-flow/testing - MCP Fixtures+ *+ * Comprehensive mock MCP tools, contexts, and server configurations for testing.+ * Supports all MCP protocol operations and Claude-Flow tool integrations.+ *+ * Based on ADR-005 (MCP-first API design) and V3 specifications.+ */+import { vi, type Mock } from 'vitest';++/**+ * MCP transport types+ */+export type MCPTransportType = 'stdio' | 'http' | 'websocket';++/**+ * MCP content types+ */+export type MCPContentType = 'text' | 'image' | 'resource';++/**+ * MCP input schema type (JSON Schema subset)+ */+export interface MCPInputSchema {+ type: 'object';+ properties: Record<string, MCPPropertySchema>;+ required?: string[];+ additionalProperties?: boolean;+}++/**+ * MCP property schema+ */+export interface MCPPropertySchema {+ type: 'string' | 'number' | 'boolean' | 'array' | 'object';+ description?: string;+ enum?: unknown[];+ default?: unknown;+ items?: MCPPropertySchema;+ properties?: Record<string, MCPPropertySchema>;+ required?: string[];+}++/**+ * MCP tool definition+ */+export interface MCPTool {+ name: string;+ description: string;+ inputSchema: MCPInputSchema;+ handler?: (params: Record<string, unknown>) => Promise<MCPToolResult>;+}++/**+ * MCP tool result+ */+export interface MCPToolResult {+ content: MCPContent[];+ isError?: boolean;+}++/**+ * MCP content (text, image, or resource)+ */+export type MCPContent = MCPTextContent | MCPImageContent | MCPResourceContent;++/**+ * MCP text content+ */+export interface MCPTextContent {+ type: 'text';+ text: string;+}++/**+ * MCP image content+ */+export interface MCPImageContent {+ type: 'image';+ data: string;+ mimeType: string;+}++/**+ * MCP resource content+ */+export interface MCPResourceContent {+ type: 'resource';+ resource: {+ uri: string;+ mimeType?: string;+ text?: string;+ blob?: string;+ };+}++/**+ * MCP server configuration+ */+export interface MCPServerConfig {+ name: string;+ version: string;+ transport: MCPTransportConfig;+ tools?: MCPTool[];+ resources?: MCPResource[];+ prompts?: MCPPrompt[];+ capabilities?: MCPCapabilities;+}++/**+ * MCP transport configuration+ */+export interface MCPTransportConfig {+ type: MCPTransportType;+ port?: number;+ host?: string;+ path?: string;+ timeout?: number;+}++/**+ * MCP resource definition+ */+export interface MCPResource {+ uri: string;+ name: string;+ description?: string;+ mimeType?: string;+}++/**+ * MCP prompt definition+ */+export interface MCPPrompt {+ name: string;+ description?: string;+ arguments?: MCPPromptArgument[];+}++/**+ * MCP prompt argument+ */+export interface MCPPromptArgument {+ name: string;+ description?: string;+ required?: boolean;+}++/**+ * MCP capabilities+ */+export interface MCPCapabilities {+ tools?: boolean;+ resources?: boolean;+ prompts?: boolean;+ logging?: boolean;+ experimental?: Record<string, boolean>;+}++/**+ * MCP request base+ */+export interface MCPRequestBase {+ jsonrpc: '2.0';+ id: string | number;+ method: string;+ params?: Record<string, unknown>;+}++/**+ * MCP response base+ */+export interface MCPResponseBase<T = unknown> {+ jsonrpc: '2.0';+ id: string | number;+ result?: T;+ error?: MCPError;+}++/**+ * MCP error+ */+export interface MCPError {+ code: number;+ message: string;+ data?: unknown;+}++/**+ * MCP server status+ */+export interface MCPServerStatus {+ running: boolean;+ transport: MCPTransportType;+ connectedClients: number;+ toolsRegistered: number;+ resourcesRegistered: number;+ promptsRegistered: number;+ requestsHandled: number;+ errorsCount: number;+ uptime: number;+}++/**+ * MCP session context+ */+export interface MCPSessionContext {+ sessionId: string;+ clientInfo: {+ name: string;+ version: string;+ };+ capabilities: MCPCapabilities;+ startedAt: Date;+ lastActivity: Date;+ requestCount: number;+}++/**+ * Pre-defined MCP tools for Claude-Flow+ */+export const mcpTools: Record<string, MCPTool> = {+ // Swarm management tools+ swarmInit: {+ name: 'swarm_init',+ description: 'Initialize a new swarm with specified topology and configuration',+ inputSchema: {+ type: 'object',+ properties: {+ topology: {+ type: 'string',+ description: 'Swarm topology (hierarchical, mesh, adaptive, hierarchical-mesh)',+ enum: ['hierarchical', 'mesh', 'ring', 'star', 'adaptive', 'hierarchical-mesh'],+ },+ maxAgents: {+ type: 'number',+ description: 'Maximum number of agents in the swarm',+ default: 15,+ },+ consensusProtocol: {+ type: 'string',+ description: 'Consensus protocol to use',+ enum: ['raft', 'pbft', 'gossip', 'byzantine'],+ },+ },+ required: ['topology'],+ },+ },++ agentSpawn: {+ name: 'agent_spawn',+ description: 'Spawn a new agent with specified type and configuration',+ inputSchema: {+ type: 'object',+ properties: {+ type: {+ type: 'string',+ description: 'Agent type (queen-coordinator, coder, tester, etc.)',+ },+ name: {+ type: 'string',+ description: 'Agent name',+ },+ capabilities: {+ type: 'array',+ description: 'Agent capabilities',+ items: { type: 'string' },+ },+ priority: {+ type: 'number',+ description: 'Agent priority (0-100)',+ default: 50,+ },+ },+ required: ['type'],+ },+ },++ taskOrchestrate: {+ name: 'task_orchestrate',+ description: 'Orchestrate a task across multiple agents',+ inputSchema: {+ type: 'object',+ properties: {+ taskName: {+ type: 'string',+ description: 'Name of the task',+ },+ taskType: {+ type: 'string',+ description: 'Type of task (security, coding, testing, review)',+ },+ payload: {+ type: 'object',+ description: 'Task payload',+ },+ agents: {+ type: 'array',+ description: 'List of agent IDs to coordinate',+ items: { type: 'string' },+ },+ parallel: {+ type: 'boolean',+ description: 'Execute tasks in parallel',+ default: true,+ },+ },+ required: ['taskName', 'taskType'],+ },+ },++ // Memory tools+ memoryStore: {+ name: 'memory_store',+ description: 'Store a value in memory with optional embedding',+ inputSchema: {+ type: 'object',+ properties: {+ key: {+ type: 'string',+ description: 'Memory key',+ },+ value: {+ type: 'object',+ description: 'Value to store',+ },+ type: {+ type: 'string',+ description: 'Memory type',+ enum: ['short-term', 'long-term', 'semantic', 'episodic'],+ },+ ttl: {+ type: 'number',+ description: 'Time-to-live in milliseconds',+ },+ generateEmbedding: {+ type: 'boolean',+ description: 'Generate vector embedding for semantic search',+ default: false,+ },+ },+ required: ['key', 'value'],+ },+ },++ memorySearch: {+ name: 'memory_search',+ description: 'Search memory using semantic vector search',+ inputSchema: {+ type: 'object',+ properties: {+ query: {+ type: 'string',+ description: 'Search query',+ },+ topK: {+ type: 'number',+ description: 'Number of results to return',+ default: 10,+ },+ threshold: {+ type: 'number',+ description: 'Minimum similarity threshold (0-1)',+ default: 0.7,+ },+ filters: {+ type: 'object',+ description: 'Additional filters',+ },+ },+ required: ['query'],+ },+ },++ // Status tools+ swarmStatus: {+ name: 'swarm_status',+ description: 'Get current swarm status and metrics',+ inputSchema: {+ type: 'object',+ properties: {+ includeMetrics: {+ type: 'boolean',+ description: 'Include detailed metrics',+ default: true,+ },+ includeAgents: {+ type: 'boolean',+ description: 'Include agent details',+ default: false,+ },+ },+ },+ },++ agentList: {+ name: 'agent_list',+ description: 'List all agents in the swarm',+ inputSchema: {+ type: 'object',+ properties: {+ status: {+ type: 'string',+ description: 'Filter by agent status',+ enum: ['idle', 'busy', 'terminated', 'error', 'all'],+ },+ type: {+ type: 'string',+ description: 'Filter by agent type',+ },+ },+ },+ },++ agentMetrics: {+ name: 'agent_metrics',+ description: 'Get metrics for a specific agent',+ inputSchema: {+ type: 'object',+ properties: {+ agentId: {+ type: 'string',+ description: 'Agent ID',+ },+ },+ required: ['agentId'],+ },+ },++ // Neural/Learning tools+ neuralStatus: {+ name: 'neural_status',+ description: 'Get neural learning system status',+ inputSchema: {+ type: 'object',+ properties: {+ includePatterns: {+ type: 'boolean',+ description: 'Include learned patterns summary',+ default: false,+ },+ },+ },+ },++ neuralTrain: {+ name: 'neural_train',+ description: 'Trigger neural training with current data',+ inputSchema: {+ type: 'object',+ properties: {+ algorithm: {+ type: 'string',+ description: 'Training algorithm',+ enum: ['ppo', 'dqn', 'a2c', 'sarsa', 'q-learning'],+ },+ epochs: {+ type: 'number',+ description: 'Number of training epochs',+ default: 10,+ },+ },+ },+ },++ // GitHub integration tools+ githubSwarm: {+ name: 'github_swarm',+ description: 'Initialize GitHub integration for a repository',+ inputSchema: {+ type: 'object',+ properties: {+ repo: {+ type: 'string',+ description: 'Repository in owner/repo format',+ },+ features: {+ type: 'array',+ description: 'Features to enable',+ items: { type: 'string' },+ default: ['issues', 'prs', 'reviews'],+ },+ },+ required: ['repo'],+ },+ },++ codeReview: {+ name: 'code_review',+ description: 'Request code review from swarm agents',+ inputSchema: {+ type: 'object',+ properties: {+ prNumber: {+ type: 'number',+ description: 'Pull request number',+ },+ repo: {+ type: 'string',+ description: 'Repository in owner/repo format',+ },+ focus: {+ type: 'array',+ description: 'Review focus areas',+ items: { type: 'string' },+ default: ['security', 'performance', 'style'],+ },+ },+ required: ['prNumber', 'repo'],+ },+ },+};++/**+ * Pre-defined MCP resources+ */+export const mcpResources: Record<string, MCPResource> = {+ swarmConfig: {+ uri: 'claude-flow://config/swarm',+ name: 'Swarm Configuration',+ description: 'Current swarm configuration',+ mimeType: 'application/json',+ },++ agentRegistry: {+ uri: 'claude-flow://agents/registry',+ name: 'Agent Registry',+ description: 'Registry of all available agent types',+ mimeType: 'application/json',+ },++ memoryStats: {+ uri: 'claude-flow://memory/stats',+ name: 'Memory Statistics',+ description: 'Memory system statistics and metrics',+ mimeType: 'application/json',+ },++ learningPatterns: {+ uri: 'claude-flow://neural/patterns',+ name: 'Learning Patterns',+ description: 'Learned patterns from ReasoningBank',+ mimeType: 'application/json',+ },+};++/**+ * Pre-defined MCP prompts+ */+export const mcpPrompts: Record<string, MCPPrompt> = {+ codeAnalysis: {+ name: 'analyze_code',+ description: 'Analyze code for security, performance, and style issues',+ arguments: [+ { name: 'language', description: 'Programming language', required: true },+ { name: 'focus', description: 'Analysis focus area', required: false },+ ],+ },++ taskPlanning: {+ name: 'plan_task',+ description: 'Generate a task execution plan',+ arguments: [+ { name: 'objective', description: 'Task objective', required: true },+ { name: 'constraints', description: 'Task constraints', required: false },+ ],+ },++ securityReview: {+ name: 'security_review',+ description: 'Perform security review on code or configuration',+ arguments: [+ { name: 'target', description: 'Review target (file, directory, config)', required: true },+ { name: 'severity', description: 'Minimum severity level', required: false },+ ],+ },+};++/**+ * Pre-defined MCP server configurations+ */+export const mcpServerConfigs: Record<string, MCPServerConfig> = {+ development: {+ name: 'claude-flow-dev',+ version: '3.0.0-alpha',+ transport: {+ type: 'http',+ port: 3000,+ host: 'localhost',+ timeout: 30000,+ },+ tools: Object.values(mcpTools),+ resources: Object.values(mcpResources),+ prompts: Object.values(mcpPrompts),+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ logging: true,+ experimental: { streaming: true },+ },+ },++ production: {+ name: 'claude-flow',+ version: '3.0.0',+ transport: {+ type: 'http',+ port: 443,+ host: '0.0.0.0',+ timeout: 15000,+ },+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ logging: false,+ },+ },++ stdio: {+ name: 'claude-flow-stdio',+ version: '3.0.0-alpha',+ transport: {+ type: 'stdio',+ timeout: 60000,+ },+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ logging: true,+ },+ },++ websocket: {+ name: 'claude-flow-ws',+ version: '3.0.0-alpha',+ transport: {+ type: 'websocket',+ port: 8080,+ host: 'localhost',+ path: '/mcp',+ timeout: 30000,+ },+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ logging: true,+ experimental: { streaming: true, multiplexing: true },+ },+ },+};++/**+ * Pre-defined MCP tool results+ */+export const mcpToolResults: Record<string, MCPToolResult> = {+ success: {+ content: [+ {+ type: 'text',+ text: 'Operation completed successfully',+ },+ ],+ },++ swarmInitialized: {+ content: [+ {+ type: 'text',+ text: JSON.stringify({+ swarmId: 'swarm-001',+ topology: 'hierarchical-mesh',+ status: 'active',+ agentCount: 15,+ }),+ },+ ],+ },++ agentSpawned: {+ content: [+ {+ type: 'text',+ text: JSON.stringify({+ agentId: 'agent-coder-001',+ type: 'coder',+ status: 'idle',+ capabilities: ['coding', 'implementation', 'debugging'],+ }),+ },+ ],+ },++ memorySearchResults: {+ content: [+ {+ type: 'text',+ text: JSON.stringify({+ results: [+ { key: 'pattern-001', score: 0.95 },+ { key: 'pattern-002', score: 0.88 },+ ],+ totalCount: 2,+ latencyMs: 15,+ }),+ },+ ],+ },++ error: {+ content: [+ {+ type: 'text',+ text: 'Operation failed: Invalid parameters',+ },+ ],+ isError: true,+ },+};++/**+ * Pre-defined MCP errors+ */+export const mcpErrors: Record<string, MCPError> = {+ parseError: {+ code: -32700,+ message: 'Parse error',+ data: { details: 'Invalid JSON received' },+ },++ invalidRequest: {+ code: -32600,+ message: 'Invalid request',+ data: { details: 'Missing required field' },+ },++ methodNotFound: {+ code: -32601,+ message: 'Method not found',+ data: { method: 'unknown_method' },+ },++ invalidParams: {+ code: -32602,+ message: 'Invalid params',+ data: { param: 'topology', expected: 'string' },+ },++ internalError: {+ code: -32603,+ message: 'Internal error',+ data: { details: 'Unexpected server error' },+ },++ toolNotFound: {+ code: -32001,+ message: 'Tool not found',+ data: { tool: 'unknown_tool' },+ },++ resourceNotFound: {+ code: -32002,+ message: 'Resource not found',+ data: { uri: 'unknown://resource' },+ },+};++/**+ * Pre-defined session contexts+ */+export const mcpSessionContexts: Record<string, MCPSessionContext> = {+ active: {+ sessionId: 'session-001',+ clientInfo: {+ name: 'claude-code',+ version: '1.0.0',+ },+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ },+ startedAt: new Date('2024-01-15T10:00:00Z'),+ lastActivity: new Date(),+ requestCount: 42,+ },++ new: {+ sessionId: 'session-002',+ clientInfo: {+ name: 'test-client',+ version: '0.1.0',+ },+ capabilities: {+ tools: true,+ },+ startedAt: new Date(),+ lastActivity: new Date(),+ requestCount: 0,+ },++ expired: {+ sessionId: 'session-003',+ clientInfo: {+ name: 'old-client',+ version: '0.0.1',+ },+ capabilities: {},+ startedAt: new Date('2024-01-01T00:00:00Z'),+ lastActivity: new Date('2024-01-01T01:00:00Z'),+ requestCount: 5,+ },+};++/**+ * Factory function to create MCP tool+ */+export function createMCPTool(+ base: keyof typeof mcpTools,+ overrides?: Partial<MCPTool>+): MCPTool {+ return {+ ...mcpTools[base],+ ...overrides,+ };+}++/**+ * Factory function to create MCP server config+ */+export function createMCPServerConfig(+ base: keyof typeof mcpServerConfigs = 'development',+ overrides?: Partial<MCPServerConfig>+): MCPServerConfig {+ return {+ ...mcpServerConfigs[base],+ ...overrides,+ };+}++/**+ * Factory function to create MCP request+ */+export function createMCPRequest(+ method: string,+ params?: Record<string, unknown>,+ overrides?: Partial<MCPRequestBase>+): MCPRequestBase {+ return {+ jsonrpc: '2.0',+ id: `req-${Date.now()}`,+ method,+ params,+ ...overrides,+ };+}++/**+ * Factory function to create MCP response+ */+export function createMCPResponse<T>(+ id: string | number,+ result?: T,+ error?: MCPError+): MCPResponseBase<T> {+ return {+ jsonrpc: '2.0',+ id,+ result,+ error,+ };+}++/**+ * Factory function to create MCP tool result+ */+export function createMCPToolResult(+ text: string,+ isError: boolean = false+): MCPToolResult {+ return {+ content: [{ type: 'text', text }],+ isError,+ };+}++/**+ * Factory function to create session context+ */+export function createMCPSessionContext(+ base: keyof typeof mcpSessionContexts = 'active',+ overrides?: Partial<MCPSessionContext>+): MCPSessionContext {+ return {+ ...mcpSessionContexts[base],+ ...overrides,+ sessionId: overrides?.sessionId ?? `session-${Date.now()}`,+ startedAt: overrides?.startedAt ?? new Date(),+ lastActivity: overrides?.lastActivity ?? new Date(),+ };+}++/**+ * Invalid MCP configurations for error testing+ */+export const invalidMCPConfigs = {+ emptyName: {+ ...mcpServerConfigs.development,+ name: '',+ },++ invalidPort: {+ ...mcpServerConfigs.development,+ transport: {+ type: 'http' as MCPTransportType,+ port: -1,+ host: 'localhost',+ },+ },++ missingTransport: {+ name: 'invalid-server',+ version: '1.0.0',+ transport: undefined as unknown as MCPTransportConfig,+ },+};++/**+ * Mock MCP client interface+ */+export interface MockMCPClient {+ connect: Mock<() => Promise<void>>;+ disconnect: Mock<() => Promise<void>>;+ callTool: Mock<(name: string, params: Record<string, unknown>) => Promise<MCPToolResult>>;+ listTools: Mock<() => Promise<MCPTool[]>>;+ readResource: Mock<(uri: string) => Promise<MCPResourceContent>>;+ listResources: Mock<() => Promise<MCPResource[]>>;+ getPrompt: Mock<(name: string, args: Record<string, string>) => Promise<string>>;+ listPrompts: Mock<() => Promise<MCPPrompt[]>>;+ isConnected: Mock<() => boolean>;+ getSessionContext: Mock<() => MCPSessionContext | null>;+}++/**+ * Create a mock MCP client+ */+export function createMockMCPClient(): MockMCPClient {+ return {+ connect: vi.fn().mockResolvedValue(undefined),+ disconnect: vi.fn().mockResolvedValue(undefined),+ callTool: vi.fn().mockResolvedValue(mcpToolResults.success),+ listTools: vi.fn().mockResolvedValue(Object.values(mcpTools)),+ readResource: vi.fn().mockResolvedValue({+ type: 'resource',+ resource: { uri: 'test://resource', text: '{}' },+ }),+ listResources: vi.fn().mockResolvedValue(Object.values(mcpResources)),+ getPrompt: vi.fn().mockResolvedValue('Generated prompt text'),+ listPrompts: vi.fn().mockResolvedValue(Object.values(mcpPrompts)),+ isConnected: vi.fn().mockReturnValue(true),+ getSessionContext: vi.fn().mockReturnValue(mcpSessionContexts.active),+ };+}++/**+ * Mock MCP server interface+ */+export interface MockMCPServer {+ start: Mock<() => Promise<void>>;+ stop: Mock<() => Promise<void>>;+ registerTool: Mock<(tool: MCPTool) => void>;+ registerResource: Mock<(resource: MCPResource) => void>;+ registerPrompt: Mock<(prompt: MCPPrompt) => void>;+ handleRequest: Mock<(request: MCPRequestBase) => Promise<MCPResponseBase>>;+ getStatus: Mock<() => MCPServerStatus>;+}++/**+ * Create a mock MCP server+ */+export function createMockMCPServer(): MockMCPServer {+ return {+ start: vi.fn().mockResolvedValue(undefined),+ stop: vi.fn().mockResolvedValue(undefined),+ registerTool: vi.fn(),+ registerResource: vi.fn(),+ registerPrompt: vi.fn(),+ handleRequest: vi.fn().mockResolvedValue({+ jsonrpc: '2.0',+ id: 1,+ result: { success: true },+ }),+ getStatus: vi.fn().mockReturnValue({+ running: true,+ transport: 'http',+ connectedClients: 1,+ toolsRegistered: Object.keys(mcpTools).length,+ resourcesRegistered: Object.keys(mcpResources).length,+ promptsRegistered: Object.keys(mcpPrompts).length,+ requestsHandled: 100,+ errorsCount: 0,+ uptime: 3600000,+ }),+ };+}++/**+ * Mock transport interface+ */+export interface MockMCPTransport {+ send: Mock<(message: string) => Promise<void>>;+ receive: Mock<() => Promise<string>>;+ close: Mock<() => Promise<void>>;+ isOpen: Mock<() => boolean>;+}++/**+ * Create a mock MCP transport+ */+export function createMockMCPTransport(): MockMCPTransport {+ return {+ send: vi.fn().mockResolvedValue(undefined),+ receive: vi.fn().mockResolvedValue('{}'),+ close: vi.fn().mockResolvedValue(undefined),+ isOpen: vi.fn().mockReturnValue(true),+ };+}diff --git a/v3/@claude-flow/testing/src/helpers/assertion-helpers.ts b/v3/@claude-flow/testing/src/helpers/assertion-helpers.tsnew file mode 100644index 0000000000..19f299625f--- /dev/null+++ b/v3/@claude-flow/testing/src/helpers/assertion-helpers.ts@@ -0,0 +1,623 @@+/**+ * @claude-flow/testing - Assertion Helpers+ *+ * Custom Vitest matchers and assertion utilities for V3 module testing.+ * Implements London School TDD behavior verification patterns.+ */+import { expect, type Mock, type ExpectStatic } from 'vitest';++/**+ * Assert that a mock was called with arguments matching a pattern+ *+ * @example+ * assertCalledWithPattern(mockFn, { userId: expect.any(String) });+ */+export function assertCalledWithPattern(+ mock: Mock,+ pattern: Record<string, unknown> | unknown[]+): void {+ const calls = mock.mock.calls;+ const matched = calls.some(call => {+ if (Array.isArray(pattern)) {+ return pattern.every((expected, i) => {+ if (typeof expected === 'object' && expected !== null && 'asymmetricMatch' in expected) {+ return (expected as { asymmetricMatch: (actual: unknown) => boolean }).asymmetricMatch(call[i]);+ }+ return JSON.stringify(call[i]) === JSON.stringify(expected);+ });+ }++ const callArg = call[0] as Record<string, unknown>;+ return Object.entries(pattern).every(([key, expected]) => {+ if (typeof expected === 'object' && expected !== null && 'asymmetricMatch' in expected) {+ return (expected as { asymmetricMatch: (actual: unknown) => boolean }).asymmetricMatch(callArg[key]);+ }+ return JSON.stringify(callArg[key]) === JSON.stringify(expected);+ });+ });++ expect(matched).toBe(true);+}++/**+ * Assert that events were published in order+ *+ * @example+ * assertEventOrder(mockEventBus.publish, ['UserCreated', 'EmailSent']);+ */+export function assertEventOrder(+ publishMock: Mock,+ expectedEventTypes: string[]+): void {+ const actualEventTypes = publishMock.mock.calls+ .map(call => (call[0] as { type: string }).type)+ .filter(type => expectedEventTypes.includes(type));++ expect(actualEventTypes).toEqual(expectedEventTypes);+}++/**+ * Assert that an event was published with specific payload+ *+ * @example+ * assertEventPublished(mockEventBus, 'UserCreated', { userId: '123' });+ */+export function assertEventPublished(+ eventBusMock: { publish: Mock } | Mock,+ eventType: string,+ expectedPayload?: Record<string, unknown>+): void {+ const publishMock = 'publish' in eventBusMock ? eventBusMock.publish : eventBusMock;+ const calls = publishMock.mock.calls;++ const matchingEvent = calls.find(call => {+ const event = call[0] as { type: string; payload?: unknown };+ return event.type === eventType;+ });++ expect(matchingEvent).toBeDefined();++ if (expectedPayload && matchingEvent) {+ const actualPayload = (matchingEvent[0] as { payload: unknown }).payload;+ expect(actualPayload).toMatchObject(expectedPayload);+ }+}++/**+ * Assert that no event of a specific type was published+ *+ * @example+ * assertEventNotPublished(mockEventBus, 'UserDeleted');+ */+export function assertEventNotPublished(+ eventBusMock: { publish: Mock } | Mock,+ eventType: string+): void {+ const publishMock = 'publish' in eventBusMock ? eventBusMock.publish : eventBusMock;+ const calls = publishMock.mock.calls;++ const matchingEvent = calls.find(call => {+ const event = call[0] as { type: string };+ return event.type === eventType;+ });++ expect(matchingEvent).toBeUndefined();+}++/**+ * Assert that mocks were called in a specific order+ *+ * @example+ * assertMocksCalledInOrder([mockValidate, mockSave, mockNotify]);+ */+export function assertMocksCalledInOrder(mocks: Mock[]): void {+ const orders = mocks.map(mock => {+ if (mock.mock.invocationCallOrder.length === 0) {+ return Infinity;+ }+ return Math.min(...mock.mock.invocationCallOrder);+ });++ for (let i = 1; i < orders.length; i++) {+ expect(orders[i]).toBeGreaterThan(orders[i - 1]);+ }+}++/**+ * Assert that a mock was called exactly n times with specific arguments+ *+ * @example+ * assertCalledNTimesWith(mockFn, 3, ['arg1', 'arg2']);+ */+export function assertCalledNTimesWith(+ mock: Mock,+ times: number,+ args: unknown[]+): void {+ const matchingCalls = mock.mock.calls.filter(+ call => JSON.stringify(call) === JSON.stringify(args)+ );++ expect(matchingCalls).toHaveLength(times);+}++/**+ * Assert that async operations completed within time limit+ *+ * @example+ * await assertCompletesWithin(async () => await slowOp(), 1000);+ */+export async function assertCompletesWithin(+ operation: () => Promise<unknown>,+ maxMs: number+): Promise<void> {+ const start = performance.now();+ await operation();+ const duration = performance.now() - start;++ expect(duration).toBeLessThanOrEqual(maxMs);+}++/**+ * Assert that an operation throws a specific error+ *+ * @example+ * await assertThrowsError(+ * async () => await riskyOp(),+ * ValidationError,+ * 'Invalid input'+ * );+ */+export async function assertThrowsError<E extends Error>(+ operation: () => Promise<unknown>,+ ErrorType: new (...args: unknown[]) => E,+ messagePattern?: string | RegExp+): Promise<E> {+ let error: E | undefined;++ try {+ await operation();+ } catch (e) {+ error = e as E;+ }++ expect(error).toBeInstanceOf(ErrorType);++ if (messagePattern && error) {+ if (typeof messagePattern === 'string') {+ expect(error.message).toContain(messagePattern);+ } else {+ expect(error.message).toMatch(messagePattern);+ }+ }++ return error!;+}++/**+ * Assert that no sensitive data appears in logs+ *+ * @example+ * assertNoSensitiveData(mockLogger.logs, ['password', 'token', 'secret']);+ */+export function assertNoSensitiveData(+ logs: Array<{ message: string; context?: Record<string, unknown> }>,+ sensitivePatterns: string[]+): void {+ for (const log of logs) {+ const content = JSON.stringify(log).toLowerCase();++ for (const pattern of sensitivePatterns) {+ expect(content).not.toContain(pattern.toLowerCase());+ }+ }+}++/**+ * Assert that a value matches a snapshot with custom serialization+ *+ * @example+ * assertMatchesSnapshot(result, { ignoreFields: ['timestamp', 'id'] });+ */+export function assertMatchesSnapshot(+ value: unknown,+ options: SnapshotOptions = {}+): void {+ const { ignoreFields = [], transform } = options;++ let processed = value;++ if (ignoreFields.length > 0 && typeof processed === 'object' && processed !== null) {+ processed = removeFields(processed as Record<string, unknown>, ignoreFields);+ }++ if (transform) {+ processed = transform(processed);+ }++ expect(processed).toMatchSnapshot();+}++/**+ * Snapshot options interface+ */+export interface SnapshotOptions {+ ignoreFields?: string[];+ transform?: (value: unknown) => unknown;+}++/**+ * Remove fields from object for snapshot comparison+ */+function removeFields(obj: Record<string, unknown>, fields: string[]): Record<string, unknown> {+ const result = { ...obj };++ for (const field of fields) {+ delete result[field];+ }++ for (const [key, value] of Object.entries(result)) {+ if (typeof value === 'object' && value !== null) {+ result[key] = removeFields(value as Record<string, unknown>, fields);+ }+ }++ return result;+}++/**+ * Assert that performance metrics meet V3 targets+ *+ * @example+ * assertV3PerformanceTargets({+ * searchSpeedup: 160,+ * memoryReduction: 0.55,+ * });+ */+export function assertV3PerformanceTargets(metrics: V3PerformanceMetrics): void {+ // Search speedup: 150x - 12500x+ if (metrics.searchSpeedup !== undefined) {+ expect(metrics.searchSpeedup).toBeGreaterThanOrEqual(150);+ expect(metrics.searchSpeedup).toBeLessThanOrEqual(12500);+ }++ // Flash attention speedup: 2.49x - 7.47x+ if (metrics.flashAttentionSpeedup !== undefined) {+ expect(metrics.flashAttentionSpeedup).toBeGreaterThanOrEqual(2.49);+ expect(metrics.flashAttentionSpeedup).toBeLessThanOrEqual(7.47);+ }++ // Memory reduction: >= 50%+ if (metrics.memoryReduction !== undefined) {+ expect(metrics.memoryReduction).toBeGreaterThanOrEqual(0.50);+ }++ // Startup time: < 500ms+ if (metrics.startupTimeMs !== undefined) {+ expect(metrics.startupTimeMs).toBeLessThan(500);+ }++ // Response time: sub-100ms+ if (metrics.responseTimeMs !== undefined) {+ expect(metrics.responseTimeMs).toBeLessThan(100);+ }+}++/**+ * V3 performance metrics interface+ */+export interface V3PerformanceMetrics {+ searchSpeedup?: number;+ flashAttentionSpeedup?: number;+ memoryReduction?: number;+ startupTimeMs?: number;+ responseTimeMs?: number;+}++/**+ * Assert that a domain object is valid+ *+ * @example+ * assertValidDomainObject(user, UserSchema);+ */+export function assertValidDomainObject<T>(+ object: T,+ validator: (obj: T) => { valid: boolean; errors?: string[] }+): void {+ const result = validator(object);++ if (!result.valid) {+ throw new Error(`Invalid domain object: ${result.errors?.join(', ')}`);+ }+}++/**+ * Assert that a mock was only called with allowed arguments+ *+ * @example+ * assertOnlyCalledWithAllowed(mockFn, [['valid1'], ['valid2']]);+ */+export function assertOnlyCalledWithAllowed(+ mock: Mock,+ allowedCalls: unknown[][]+): void {+ const calls = mock.mock.calls;++ for (const call of calls) {+ const isAllowed = allowedCalls.some(+ allowed => JSON.stringify(call) === JSON.stringify(allowed)+ );++ if (!isAllowed) {+ throw new Error(+ `Mock was called with unexpected arguments: ${JSON.stringify(call)}\n` ++ `Allowed: ${JSON.stringify(allowedCalls)}`+ );+ }+ }+}++/**+ * Assert that an array contains elements in partial order+ *+ * @example+ * assertPartialOrder(events, [+ * { type: 'Start' },+ * { type: 'Process' },+ * { type: 'End' },+ * ]);+ */+export function assertPartialOrder<T>(+ actual: T[],+ expectedOrder: Partial<T>[]+): void {+ let lastIndex = -1;++ for (const expected of expectedOrder) {+ const index = actual.findIndex((item, i) =>+ i > lastIndex &&+ Object.entries(expected as Record<string, unknown>).every(+ ([key, value]) => (item as Record<string, unknown>)[key] === value+ )+ );++ if (index === -1) {+ throw new Error(+ `Expected to find ${JSON.stringify(expected)} after index ${lastIndex} in array`+ );+ }++ lastIndex = index;+ }+}++/**+ * Assert that all items in a collection pass a predicate+ *+ * @example+ * assertAllPass(results, result => result.success);+ */+export function assertAllPass<T>(+ items: T[],+ predicate: (item: T, index: number) => boolean,+ message?: string+): void {+ for (let i = 0; i < items.length; i++) {+ if (!predicate(items[i], i)) {+ throw new Error(+ message ?? `Item at index ${i} failed predicate: ${JSON.stringify(items[i])}`+ );+ }+ }+}++/**+ * Assert that none of the items in a collection pass a predicate+ *+ * @example+ * assertNonePass(results, result => result.error);+ */+export function assertNonePass<T>(+ items: T[],+ predicate: (item: T, index: number) => boolean,+ message?: string+): void {+ for (let i = 0; i < items.length; i++) {+ if (predicate(items[i], i)) {+ throw new Error(+ message ?? `Item at index ${i} passed predicate but should not have: ${JSON.stringify(items[i])}`+ );+ }+ }+}++/**+ * Assert that two arrays have the same elements regardless of order+ *+ * @example+ * assertSameElements([1, 2, 3], [3, 1, 2]);+ */+export function assertSameElements<T>(actual: T[], expected: T[]): void {+ expect(actual).toHaveLength(expected.length);++ const actualSorted = [...actual].sort((a, b) =>+ JSON.stringify(a).localeCompare(JSON.stringify(b))+ );+ const expectedSorted = [...expected].sort((a, b) =>+ JSON.stringify(a).localeCompare(JSON.stringify(b))+ );++ expect(actualSorted).toEqual(expectedSorted);+}++/**+ * Assert that a mock returns expected results in sequence+ *+ * @example+ * await assertMockReturnsSequence(mockFn, [1, 2, 3]);+ */+export async function assertMockReturnsSequence(+ mock: Mock,+ expectedResults: unknown[]+): Promise<void> {+ for (const expected of expectedResults) {+ const result = await mock();+ expect(result).toEqual(expected);+ }+}++/**+ * Assert state transition is valid+ *+ * @example+ * assertValidStateTransition(+ * 'pending',+ * 'running',+ * { pending: ['running', 'cancelled'], running: ['completed', 'failed'] }+ * );+ */+export function assertValidStateTransition<T extends string>(+ from: T,+ to: T,+ allowedTransitions: Record<T, T[]>+): void {+ const allowed = allowedTransitions[from];++ if (!allowed || !allowed.includes(to)) {+ throw new Error(+ `Invalid state transition from '${from}' to '${to}'. ` ++ `Allowed transitions from '${from}': ${allowed?.join(', ') ?? 'none'}`+ );+ }+}++/**+ * Assert that a retry policy was followed+ *+ * @example+ * assertRetryPattern(mockFn, { attempts: 3, backoffPattern: 'exponential' });+ */+export function assertRetryPattern(+ mock: Mock,+ options: RetryPatternOptions+): void {+ const calls = mock.mock.calls;++ expect(calls).toHaveLength(options.attempts);++ if (options.backoffPattern === 'exponential' && calls.length > 1) {+ // Check that intervals roughly follow exponential pattern+ const invocationOrder = mock.mock.invocationCallOrder;+ for (let i = 2; i < invocationOrder.length; i++) {+ const prevGap = invocationOrder[i - 1] - invocationOrder[i - 2];+ const currentGap = invocationOrder[i] - invocationOrder[i - 1];+ // Allow some variance in timing+ expect(currentGap).toBeGreaterThanOrEqual(prevGap * 0.8);+ }+ }+}++/**+ * Retry pattern options interface+ */+export interface RetryPatternOptions {+ attempts: number;+ backoffPattern?: 'linear' | 'exponential' | 'constant';+ initialDelayMs?: number;+}++/**+ * Assert that a dependency was properly injected+ *+ * @example+ * assertDependencyInjected(service, 'repository', mockRepository);+ */+export function assertDependencyInjected<T extends object>(+ subject: T,+ propertyName: keyof T,+ expectedDependency: unknown+): void {+ expect(subject[propertyName]).toBe(expectedDependency);+}++/**+ * Custom Vitest matcher declarations+ */+declare module 'vitest' {+ interface Assertion<T = unknown> {+ toHaveBeenCalledWithPattern(pattern: Record<string, unknown>): T;+ toHaveEventType(eventType: string): T;+ toMeetV3PerformanceTargets(): T;+ toBeValidTransition(from: string, allowedTransitions: Record<string, string[]>): T;+ }+}++/**+ * Register custom Vitest matchers+ */+export function registerCustomMatchers(): void {+ expect.extend({+ toHaveBeenCalledWithPattern(received: Mock, pattern: Record<string, unknown>) {+ const calls = received.mock.calls;+ const pass = calls.some(call => {+ const callArg = call[0] as Record<string, unknown>;+ return Object.entries(pattern).every(([key, expected]) =>+ JSON.stringify(callArg[key]) === JSON.stringify(expected)+ );+ });++ return {+ pass,+ message: () => pass+ ? `Expected mock not to have been called with pattern ${JSON.stringify(pattern)}`+ : `Expected mock to have been called with pattern ${JSON.stringify(pattern)}`,+ };+ },++ toHaveEventType(received: { type: string }, eventType: string) {+ const pass = received.type === eventType;++ return {+ pass,+ message: () => pass+ ? `Expected event not to have type ${eventType}`+ : `Expected event to have type ${eventType}, but got ${received.type}`,+ };+ },++ toMeetV3PerformanceTargets(received: V3PerformanceMetrics) {+ const issues: string[] = [];++ if (received.searchSpeedup !== undefined) {+ if (received.searchSpeedup < 150) {+ issues.push(`Search speedup ${received.searchSpeedup}x is below minimum 150x`);+ }+ }++ if (received.flashAttentionSpeedup !== undefined) {+ if (received.flashAttentionSpeedup < 2.49) {+ issues.push(`Flash attention speedup ${received.flashAttentionSpeedup}x is below minimum 2.49x`);+ }+ }++ if (received.memoryReduction !== undefined) {+ if (received.memoryReduction < 0.50) {+ issues.push(`Memory reduction ${received.memoryReduction * 100}% is below target 50%`);+ }+ }++ if (received.startupTimeMs !== undefined) {+ if (received.startupTimeMs >= 500) {+ issues.push(`Startup time ${received.startupTimeMs}ms exceeds target 500ms`);+ }+ }++ return {+ pass: issues.length === 0,+ message: () => issues.length === 0+ ? 'Performance metrics meet V3 targets'+ : `Performance issues: ${issues.join('; ')}`,+ };+ },+ });+}diff --git a/v3/@claude-flow/testing/src/helpers/mock-factory.ts b/v3/@claude-flow/testing/src/helpers/mock-factory.tsnew file mode 100644index 0000000000..09e00d5a19--- /dev/null+++ b/v3/@claude-flow/testing/src/helpers/mock-factory.ts@@ -0,0 +1,711 @@+/**+ * @claude-flow/testing - Mock Factory+ *+ * Factory functions for creating comprehensive mocks of V3 services and components.+ * Implements London School TDD patterns with behavior verification.+ */+import { vi, type Mock } from 'vitest';+import { createMock, createMockWithBehavior, type MockedInterface } from './create-mock.js';+import type { V3AgentType, AgentInstance, AgentMetrics } from '../fixtures/agent-fixtures.js';+import type { MemoryEntry, SearchResult, VectorQuery } from '../fixtures/memory-fixtures.js';+import type { SwarmState, SwarmConfig, SwarmTask, SwarmTaskResult, CoordinationResult } from '../fixtures/swarm-fixtures.js';+import type { MCPTool, MCPToolResult, MCPServerConfig, MCPSessionContext } from '../fixtures/mcp-fixtures.js';++/**+ * Event bus interface for DDD events+ */+export interface IEventBus {+ publish(event: DomainEvent): Promise<void>;+ subscribe(eventType: string, handler: EventHandler): () => void;+ unsubscribe(eventType: string, handler: EventHandler): void;+ getSubscriberCount(eventType: string): number;+}++/**+ * Domain event interface+ */+export interface DomainEvent {+ id: string;+ type: string;+ payload: unknown;+ timestamp: Date;+ correlationId?: string;+ causationId?: string;+ metadata?: Record<string, unknown>;+}++/**+ * Event handler type+ */+export type EventHandler = (event: DomainEvent) => Promise<void>;++/**+ * Task manager interface+ */+export interface ITaskManager {+ create(definition: TaskDefinition): Promise<Task>;+ execute(taskId: string): Promise<TaskResult>;+ cancel(taskId: string): Promise<void>;+ getStatus(taskId: string): Promise<TaskStatus>;+ getTask(taskId: string): Promise<Task | null>;+ listTasks(filters?: TaskFilters): Promise<Task[]>;+}++/**+ * Task definition interface+ */+export interface TaskDefinition {+ name: string;+ type: string;+ payload: unknown;+ priority?: number;+ dependencies?: string[];+ deadline?: Date;+}++/**+ * Task interface+ */+export interface Task {+ id: string;+ name: string;+ type: string;+ status: TaskStatus;+ payload: unknown;+ priority: number;+ createdAt: Date;+ startedAt?: Date;+ completedAt?: Date;+}++/**+ * Task status type+ */+export type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';++/**+ * Task result interface+ */+export interface TaskResult {+ taskId: string;+ success: boolean;+ output?: unknown;+ error?: Error;+ duration: number;+}++/**+ * Task filters interface+ */+export interface TaskFilters {+ status?: TaskStatus;+ type?: string;+ assignedTo?: string;+ limit?: number;+ offset?: number;+}++/**+ * Agent lifecycle interface+ */+export interface IAgentLifecycle {+ spawn(config: AgentConfig): Promise<AgentSpawnResult>;+ terminate(agentId: string, options?: TerminateOptions): Promise<void>;+ getAgent(agentId: string): Promise<AgentInstance | null>;+ listAgents(filters?: AgentFilters): Promise<AgentInstance[]>;+ getMetrics(agentId: string): Promise<AgentMetrics>;+ healthCheck(agentId: string): Promise<AgentHealthCheck>;+}++/**+ * Agent config interface+ */+export interface AgentConfig {+ type: V3AgentType;+ name: string;+ capabilities?: string[];+ priority?: number;+}++/**+ * Agent spawn result interface+ */+export interface AgentSpawnResult {+ agent: AgentInstance;+ sessionId: string;+ startupTime: number;+ success: boolean;+}++/**+ * Terminate options interface+ */+export interface TerminateOptions {+ graceful?: boolean;+ timeout?: number;+ cancelTasks?: boolean;+}++/**+ * Agent filters interface+ */+export interface AgentFilters {+ type?: V3AgentType;+ status?: string;+ capability?: string;+}++/**+ * Agent health check interface+ */+export interface AgentHealthCheck {+ healthy: boolean;+ issues?: string[];+ lastActivity: Date;+ metrics: AgentMetrics;+}++/**+ * Memory service interface+ */+export interface IMemoryService {+ store(key: string, value: unknown, metadata?: Record<string, unknown>): Promise<void>;+ retrieve(key: string): Promise<unknown>;+ search(query: VectorQuery): Promise<SearchResult[]>;+ delete(key: string): Promise<void>;+ clear(): Promise<void>;+ getStats(): Promise<MemoryStats>;+ createIndex(name: string, config: IndexConfig): Promise<void>;+}++/**+ * Memory stats interface+ */+export interface MemoryStats {+ totalEntries: number;+ totalSizeBytes: number;+ vectorCount: number;+ cacheHitRate: number;+}++/**+ * Index config interface+ */+export interface IndexConfig {+ dimensions: number;+ metric: 'cosine' | 'euclidean' | 'dot';+ M?: number;+ efConstruction?: number;+}++/**+ * Security service interface+ */+export interface ISecurityService {+ validatePath(path: string): boolean;+ validateInput(input: string, options?: InputValidationOptions): { valid: boolean; errors?: string[] };+ hashPassword(password: string): Promise<string>;+ verifyPassword(password: string, hash: string): Promise<boolean>;+ generateToken(payload: Record<string, unknown>, expiresIn?: number): Promise<string>;+ verifyToken(token: string): Promise<Record<string, unknown>>;+ executeSecurely(command: string, options?: ExecuteOptions): Promise<ExecuteResult>;+}++/**+ * Input validation options+ */+export interface InputValidationOptions {+ maxLength?: number;+ allowedChars?: RegExp;+ sanitize?: boolean;+}++/**+ * Execute options interface+ */+export interface ExecuteOptions {+ timeout?: number;+ cwd?: string;+ shell?: boolean;+ allowedCommands?: string[];+}++/**+ * Execute result interface+ */+export interface ExecuteResult {+ stdout: string;+ stderr: string;+ exitCode: number;+ duration: number;+}++/**+ * Swarm coordinator interface+ */+export interface ISwarmCoordinator {+ initialize(config: SwarmConfig): Promise<SwarmState>;+ coordinate(agents: string[], task: SwarmTask): Promise<CoordinationResult>;+ shutdown(graceful?: boolean): Promise<void>;+ getState(): SwarmState;+ addAgent(agentId: string): Promise<void>;+ removeAgent(agentId: string): Promise<void>;+ broadcast(message: unknown): Promise<void>;+}++/**+ * MCP client interface+ */+export interface IMCPClient {+ connect(): Promise<void>;+ disconnect(): Promise<void>;+ callTool(name: string, params: Record<string, unknown>): Promise<MCPToolResult>;+ listTools(): Promise<MCPTool[]>;+ isConnected(): boolean;+ getSession(): MCPSessionContext | null;+}++/**+ * Logger interface+ */+export interface ILogger {+ debug(message: string, context?: Record<string, unknown>): void;+ info(message: string, context?: Record<string, unknown>): void;+ warn(message: string, context?: Record<string, unknown>): void;+ error(message: string, error?: Error, context?: Record<string, unknown>): void;+}++/**+ * Create mock event bus with behavior tracking+ */+export function createMockEventBus(): MockedInterface<IEventBus> & { publishedEvents: DomainEvent[] } {+ const publishedEvents: DomainEvent[] = [];+ const subscribers = new Map<string, Set<EventHandler>>();++ const mock = createMock<IEventBus>();++ mock.publish.mockImplementation(async (event: DomainEvent) => {+ publishedEvents.push(event);+ const handlers = subscribers.get(event.type);+ if (handlers) {+ for (const handler of handlers) {+ await handler(event);+ }+ }+ });++ mock.subscribe.mockImplementation((eventType: string, handler: EventHandler) => {+ if (!subscribers.has(eventType)) {+ subscribers.set(eventType, new Set());+ }+ subscribers.get(eventType)!.add(handler);+ return () => subscribers.get(eventType)?.delete(handler);+ });++ mock.unsubscribe.mockImplementation((eventType: string, handler: EventHandler) => {+ subscribers.get(eventType)?.delete(handler);+ });++ mock.getSubscriberCount.mockImplementation((eventType: string) => {+ return subscribers.get(eventType)?.size ?? 0;+ });++ return Object.assign(mock, { publishedEvents });+}++/**+ * Create mock task manager with realistic behavior+ */+export function createMockTaskManager(): MockedInterface<ITaskManager> & { tasks: Map<string, Task> } {+ const tasks = new Map<string, Task>();+ let taskCounter = 0;++ const mock = createMock<ITaskManager>();++ mock.create.mockImplementation(async (definition: TaskDefinition) => {+ const task: Task = {+ id: `task-${++taskCounter}`,+ name: definition.name,+ type: definition.type,+ status: 'pending',+ payload: definition.payload,+ priority: definition.priority ?? 50,+ createdAt: new Date(),+ };+ tasks.set(task.id, task);+ return task;+ });++ mock.execute.mockImplementation(async (taskId: string) => {+ const task = tasks.get(taskId);+ if (!task) {+ throw new Error(`Task ${taskId} not found`);+ }+ task.status = 'running';+ task.startedAt = new Date();++ // Simulate execution+ await new Promise(resolve => setTimeout(resolve, 10));++ task.status = 'completed';+ task.completedAt = new Date();++ return {+ taskId,+ success: true,+ duration: task.completedAt.getTime() - task.startedAt.getTime(),+ };+ });++ mock.cancel.mockImplementation(async (taskId: string) => {+ const task = tasks.get(taskId);+ if (task) {+ task.status = 'cancelled';+ }+ });++ mock.getStatus.mockImplementation(async (taskId: string) => {+ const task = tasks.get(taskId);+ return task?.status ?? 'pending';+ });++ mock.getTask.mockImplementation(async (taskId: string) => {+ return tasks.get(taskId) ?? null;+ });++ mock.listTasks.mockImplementation(async (filters?: TaskFilters) => {+ let result = Array.from(tasks.values());++ if (filters?.status) {+ result = result.filter(t => t.status === filters.status);+ }+ if (filters?.type) {+ result = result.filter(t => t.type === filters.type);+ }+ if (filters?.limit) {+ result = result.slice(filters.offset ?? 0, (filters.offset ?? 0) + filters.limit);+ }++ return result;+ });++ return Object.assign(mock, { tasks });+}++/**+ * Create mock agent lifecycle+ */+export function createMockAgentLifecycle(): MockedInterface<IAgentLifecycle> & { agents: Map<string, AgentInstance> } {+ const agents = new Map<string, AgentInstance>();+ let agentCounter = 0;++ const mock = createMock<IAgentLifecycle>();++ mock.spawn.mockImplementation(async (config: AgentConfig) => {+ const agent: AgentInstance = {+ id: `agent-${config.type}-${++agentCounter}`,+ type: config.type,+ name: config.name,+ status: 'idle',+ capabilities: config.capabilities ?? [],+ createdAt: new Date(),+ };+ agents.set(agent.id, agent);++ return {+ agent,+ sessionId: `session-${Date.now()}`,+ startupTime: Math.random() * 100 + 50,+ success: true,+ };+ });++ mock.terminate.mockImplementation(async (agentId: string) => {+ const agent = agents.get(agentId);+ if (agent) {+ agent.status = 'terminated';+ }+ });++ mock.getAgent.mockImplementation(async (agentId: string) => {+ return agents.get(agentId) ?? null;+ });++ mock.listAgents.mockImplementation(async (filters?: AgentFilters) => {+ let result = Array.from(agents.values());++ if (filters?.type) {+ result = result.filter(a => a.type === filters.type);+ }+ if (filters?.status) {+ result = result.filter(a => a.status === filters.status);+ }+ if (filters?.capability) {+ result = result.filter(a => a.capabilities.includes(filters.capability!));+ }++ return result;+ });++ mock.getMetrics.mockImplementation(async () => ({+ tasksCompleted: Math.floor(Math.random() * 100),+ tasksFailed: Math.floor(Math.random() * 10),+ avgTaskDuration: Math.random() * 1000,+ totalDuration: Math.random() * 10000,+ errorRate: Math.random() * 0.1,+ memoryUsageMb: Math.random() * 256,+ }));++ mock.healthCheck.mockImplementation(async (agentId: string) => {+ const agent = agents.get(agentId);+ return {+ healthy: agent?.status !== 'error' && agent?.status !== 'terminated',+ lastActivity: new Date(),+ metrics: {+ tasksCompleted: 50,+ tasksFailed: 1,+ avgTaskDuration: 200,+ totalDuration: 10000,+ errorRate: 0.02,+ memoryUsageMb: 128,+ },+ };+ });++ return Object.assign(mock, { agents });+}++/**+ * Create mock memory service+ */+export function createMockMemoryService(): MockedInterface<IMemoryService> & { entries: Map<string, { value: unknown; metadata?: Record<string, unknown> }> } {+ const entries = new Map<string, { value: unknown; metadata?: Record<string, unknown> }>();++ const mock = createMock<IMemoryService>();++ mock.store.mockImplementation(async (key: string, value: unknown, metadata?: Record<string, unknown>) => {+ entries.set(key, { value, metadata });+ });++ mock.retrieve.mockImplementation(async (key: string) => {+ return entries.get(key)?.value ?? null;+ });++ mock.search.mockImplementation(async () => []);++ mock.delete.mockImplementation(async (key: string) => {+ entries.delete(key);+ });++ mock.clear.mockImplementation(async () => {+ entries.clear();+ });++ mock.getStats.mockImplementation(async () => ({+ totalEntries: entries.size,+ totalSizeBytes: entries.size * 100,+ vectorCount: 0,+ cacheHitRate: 0.85,+ }));++ mock.createIndex.mockResolvedValue(undefined);++ return Object.assign(mock, { entries });+}++/**+ * Create mock security service+ */+export function createMockSecurityService(): MockedInterface<ISecurityService> {+ const mock = createMock<ISecurityService>();++ mock.validatePath.mockImplementation((path: string) => {+ const blocked = ['../', '~/', '/etc/', '/tmp/', '/var/'];+ return !blocked.some(pattern => path.includes(pattern));+ });++ mock.validateInput.mockImplementation((input: string, options?: InputValidationOptions) => {+ const maxLength = options?.maxLength ?? 10000;+ if (input.length > maxLength) {+ return { valid: false, errors: [`Input exceeds maximum length of ${maxLength}`] };+ }+ return { valid: true };+ });++ mock.hashPassword.mockImplementation(async (password: string) => {+ return `hashed:${Buffer.from(password).toString('base64')}`;+ });++ mock.verifyPassword.mockImplementation(async (password: string, hash: string) => {+ return hash === `hashed:${Buffer.from(password).toString('base64')}`;+ });++ mock.generateToken.mockImplementation(async (payload: Record<string, unknown>) => {+ return `token:${Buffer.from(JSON.stringify(payload)).toString('base64')}`;+ });++ mock.verifyToken.mockImplementation(async (token: string) => {+ if (!token.startsWith('token:')) {+ throw new Error('Invalid token');+ }+ return JSON.parse(Buffer.from(token.slice(6), 'base64').toString());+ });++ mock.executeSecurely.mockImplementation(async () => ({+ stdout: '',+ stderr: '',+ exitCode: 0,+ duration: 100,+ }));++ return mock;+}++/**+ * Create mock swarm coordinator+ */+export function createMockSwarmCoordinator(): MockedInterface<ISwarmCoordinator> & { state: SwarmState } {+ const state: SwarmState = {+ id: 'swarm-test',+ topology: 'hierarchical-mesh',+ status: 'active',+ agentCount: 0,+ activeAgentCount: 0,+ createdAt: new Date(),+ };++ const mock = createMock<ISwarmCoordinator>();++ mock.initialize.mockImplementation(async (config: SwarmConfig) => {+ state.topology = config.topology;+ state.status = 'active';+ return state;+ });++ mock.coordinate.mockImplementation(async (agents: string[], task: SwarmTask) => ({+ success: true,+ completedTasks: 1,+ failedTasks: 0,+ totalDuration: 1000,+ agentMetrics: new Map(),+ }));++ mock.shutdown.mockImplementation(async () => {+ state.status = 'shutdown';+ state.activeAgentCount = 0;+ });++ mock.getState.mockImplementation(() => state);++ mock.addAgent.mockImplementation(async () => {+ state.agentCount++;+ state.activeAgentCount++;+ });++ mock.removeAgent.mockImplementation(async () => {+ state.agentCount--;+ state.activeAgentCount--;+ });++ mock.broadcast.mockResolvedValue(undefined);++ return Object.assign(mock, { state });+}++/**+ * Create mock MCP client+ */+export function createMockMCPClient(): MockedInterface<IMCPClient> & { connected: boolean } {+ let connected = false;++ const mock = createMock<IMCPClient>();++ mock.connect.mockImplementation(async () => {+ connected = true;+ });++ mock.disconnect.mockImplementation(async () => {+ connected = false;+ });++ mock.callTool.mockImplementation(async () => ({+ content: [{ type: 'text', text: 'Success' }],+ }));++ mock.listTools.mockResolvedValue([]);++ mock.isConnected.mockImplementation(() => connected);++ mock.getSession.mockReturnValue(null);++ return Object.assign(mock, { connected });+}++/**+ * Create mock logger with captured logs+ */+export function createMockLogger(): MockedInterface<ILogger> & { logs: Array<{ level: string; message: string; context?: Record<string, unknown>; error?: Error }> } {+ const logs: Array<{ level: string; message: string; context?: Record<string, unknown>; error?: Error }> = [];++ const mock = createMock<ILogger>();++ mock.debug.mockImplementation((message: string, context?: Record<string, unknown>) => {+ logs.push({ level: 'debug', message, context });+ });++ mock.info.mockImplementation((message: string, context?: Record<string, unknown>) => {+ logs.push({ level: 'info', message, context });+ });++ mock.warn.mockImplementation((message: string, context?: Record<string, unknown>) => {+ logs.push({ level: 'warn', message, context });+ });++ mock.error.mockImplementation((message: string, error?: Error, context?: Record<string, unknown>) => {+ logs.push({ level: 'error', message, context, error });+ });++ return Object.assign(mock, { logs });+}++/**+ * Create a complete test application with all mock services+ */+export function createMockApplication(): MockApplication {+ return {+ eventBus: createMockEventBus(),+ taskManager: createMockTaskManager(),+ agentLifecycle: createMockAgentLifecycle(),+ memoryService: createMockMemoryService(),+ securityService: createMockSecurityService(),+ swarmCoordinator: createMockSwarmCoordinator(),+ mcpClient: createMockMCPClient(),+ logger: createMockLogger(),+ };+}++/**+ * Mock application type+ */+export interface MockApplication {+ eventBus: ReturnType<typeof createMockEventBus>;+ taskManager: ReturnType<typeof createMockTaskManager>;+ agentLifecycle: ReturnType<typeof createMockAgentLifecycle>;+ memoryService: ReturnType<typeof createMockMemoryService>;+ securityService: ReturnType<typeof createMockSecurityService>;+ swarmCoordinator: ReturnType<typeof createMockSwarmCoordinator>;+ mcpClient: ReturnType<typeof createMockMCPClient>;+ logger: ReturnType<typeof createMockLogger>;+}++/**+ * Reset all mocks in the application+ */+export function resetMockApplication(app: MockApplication): void {+ vi.clearAllMocks();+ app.eventBus.publishedEvents.length = 0;+ app.taskManager.tasks.clear();+ app.agentLifecycle.agents.clear();+ app.memoryService.entries.clear();+ app.logger.logs.length = 0;+}diff --git a/v3/@claude-flow/testing/src/helpers/setup-teardown.ts b/v3/@claude-flow/testing/src/helpers/setup-teardown.tsnew file mode 100644index 0000000000..c57c602831--- /dev/null+++ b/v3/@claude-flow/testing/src/helpers/setup-teardown.ts@@ -0,0 +1,678 @@+/**+ * @claude-flow/testing - Setup & Teardown Helpers+ *+ * Global setup and teardown utilities for V3 module testing.+ * Provides test isolation, resource cleanup, and environment management.+ */+import { vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';++/**+ * Setup context for managing test resources+ */+export interface SetupContext {+ /**+ * Register a cleanup function to be called during teardown+ */+ addCleanup(cleanup: CleanupFunction): void;++ /**+ * Register a resource that needs to be closed/disposed+ */+ registerResource<T extends Disposable>(resource: T): T;++ /**+ * Get a registered resource by name+ */+ getResource<T>(name: string): T | undefined;++ /**+ * Set a named resource+ */+ setResource<T>(name: string, resource: T): void;++ /**+ * Run all cleanup functions+ */+ runCleanup(): Promise<void>;+}++/**+ * Cleanup function type+ */+export type CleanupFunction = () => void | Promise<void>;++/**+ * Disposable interface+ */+export interface Disposable {+ dispose?(): void | Promise<void>;+ close?(): void | Promise<void>;+ destroy?(): void | Promise<void>;+ shutdown?(): void | Promise<void>;+}++/**+ * Create a setup context for managing test resources+ *+ * @example+ * const ctx = createSetupContext();+ * ctx.addCleanup(() => server.close());+ * ctx.registerResource(database);+ * // ... run tests+ * await ctx.runCleanup();+ */+export function createSetupContext(): SetupContext {+ const cleanups: CleanupFunction[] = [];+ const resources = new Map<string, unknown>();+ const disposables: Disposable[] = [];++ return {+ addCleanup(cleanup: CleanupFunction): void {+ cleanups.push(cleanup);+ },++ registerResource<T extends Disposable>(resource: T): T {+ disposables.push(resource);+ return resource;+ },++ getResource<T>(name: string): T | undefined {+ return resources.get(name) as T | undefined;+ },++ setResource<T>(name: string, resource: T): void {+ resources.set(name, resource);+ },++ async runCleanup(): Promise<void> {+ // Run cleanups in reverse order+ for (const cleanup of cleanups.reverse()) {+ try {+ await cleanup();+ } catch (error) {+ console.error('Cleanup error:', error);+ }+ }++ // Dispose resources+ for (const resource of disposables) {+ try {+ if (resource.dispose) {+ await resource.dispose();+ } else if (resource.close) {+ await resource.close();+ } else if (resource.destroy) {+ await resource.destroy();+ } else if (resource.shutdown) {+ await resource.shutdown();+ }+ } catch (error) {+ console.error('Resource disposal error:', error);+ }+ }++ cleanups.length = 0;+ resources.clear();+ disposables.length = 0;+ },+ };+}++/**+ * Global test context that persists across test files+ */+let globalContext: SetupContext | null = null;++/**+ * Get or create the global test context+ */+export function getGlobalContext(): SetupContext {+ if (!globalContext) {+ globalContext = createSetupContext();+ }+ return globalContext;+}++/**+ * Reset the global test context+ */+export async function resetGlobalContext(): Promise<void> {+ if (globalContext) {+ await globalContext.runCleanup();+ globalContext = null;+ }+}++/**+ * Test environment configuration+ */+export interface TestEnvironmentConfig {+ /**+ * Reset all mocks before each test+ */+ resetMocks?: boolean;++ /**+ * Use fake timers+ */+ fakeTimers?: boolean;++ /**+ * Initial fake time+ */+ initialTime?: Date | number;++ /**+ * Environment variables to set+ */+ env?: Record<string, string>;++ /**+ * Suppress console output during tests+ */+ suppressConsole?: boolean | ('log' | 'warn' | 'error' | 'info')[];++ /**+ * Timeout for async operations+ */+ timeout?: number;+}++/**+ * Configure test environment with standard settings+ *+ * @example+ * configureTestEnvironment({+ * resetMocks: true,+ * fakeTimers: true,+ * suppressConsole: ['log', 'warn'],+ * });+ */+export function configureTestEnvironment(config: TestEnvironmentConfig = {}): void {+ const {+ resetMocks = true,+ fakeTimers = false,+ initialTime,+ env = {},+ suppressConsole = false,+ } = config;++ const originalEnv: Record<string, string | undefined> = {};+ const originalConsole: Partial<Console> = {};++ beforeAll(() => {+ // Set environment variables+ for (const [key, value] of Object.entries(env)) {+ originalEnv[key] = process.env[key];+ process.env[key] = value;+ }++ // Suppress console+ if (suppressConsole) {+ const methods = suppressConsole === true+ ? ['log', 'warn', 'error', 'info'] as const+ : suppressConsole;++ for (const method of methods) {+ originalConsole[method] = console[method];+ console[method] = vi.fn();+ }+ }+ });++ afterAll(() => {+ // Restore environment variables+ for (const [key, value] of Object.entries(originalEnv)) {+ if (value === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = value;+ }+ }++ // Restore console+ for (const [method, original] of Object.entries(originalConsole)) {+ if (original) {+ (console as Record<string, unknown>)[method] = original;+ }+ }+ });++ beforeEach(() => {+ if (resetMocks) {+ vi.clearAllMocks();+ }++ if (fakeTimers) {+ vi.useFakeTimers();+ if (initialTime) {+ vi.setSystemTime(initialTime);+ }+ }+ });++ afterEach(() => {+ if (fakeTimers) {+ vi.useRealTimers();+ }++ vi.restoreAllMocks();+ });+}++/**+ * Create a test suite with automatic setup/teardown+ *+ * @example+ * const { beforeEachTest, afterEachTest, getContext } = createTestSuite({+ * resetMocks: true,+ * });+ */+export function createTestSuite(config: TestEnvironmentConfig = {}): TestSuiteHelpers {+ const context = createSetupContext();++ configureTestEnvironment(config);++ return {+ beforeEachTest: (fn: (ctx: SetupContext) => void | Promise<void>) => {+ beforeEach(async () => {+ await fn(context);+ });+ },++ afterEachTest: (fn: (ctx: SetupContext) => void | Promise<void>) => {+ afterEach(async () => {+ await fn(context);+ await context.runCleanup();+ });+ },++ getContext: () => context,+ };+}++/**+ * Test suite helpers interface+ */+export interface TestSuiteHelpers {+ beforeEachTest: (fn: (ctx: SetupContext) => void | Promise<void>) => void;+ afterEachTest: (fn: (ctx: SetupContext) => void | Promise<void>) => void;+ getContext: () => SetupContext;+}++/**+ * Create isolated test scope+ *+ * @example+ * const scope = createTestScope();+ * scope.addMock(mockService);+ * await scope.run(async () => {+ * // test code+ * });+ */+export function createTestScope(): TestScope {+ const mocks: ReturnType<typeof vi.fn>[] = [];+ const cleanups: CleanupFunction[] = [];++ return {+ addMock<T extends ReturnType<typeof vi.fn>>(mock: T): T {+ mocks.push(mock);+ return mock;+ },++ addCleanup(cleanup: CleanupFunction): void {+ cleanups.push(cleanup);+ },++ async run<T>(fn: () => Promise<T>): Promise<T> {+ try {+ return await fn();+ } finally {+ // Clear all mocks+ for (const mock of mocks) {+ mock.mockClear();+ }++ // Run cleanups+ for (const cleanup of cleanups.reverse()) {+ await cleanup();+ }+ }+ },++ clear(): void {+ for (const mock of mocks) {+ mock.mockClear();+ }+ },++ reset(): void {+ for (const mock of mocks) {+ mock.mockReset();+ }+ },+ };+}++/**+ * Test scope interface+ */+export interface TestScope {+ addMock<T extends ReturnType<typeof vi.fn>>(mock: T): T;+ addCleanup(cleanup: CleanupFunction): void;+ run<T>(fn: () => Promise<T>): Promise<T>;+ clear(): void;+ reset(): void;+}++/**+ * Database test helper for memory/agentdb testing+ */+export interface DatabaseTestHelper {+ setup(): Promise<void>;+ teardown(): Promise<void>;+ clear(): Promise<void>;+ seed(data: Record<string, unknown[]>): Promise<void>;+}++/**+ * Create in-memory database helper for testing+ *+ * @example+ * const db = createInMemoryDatabaseHelper();+ * await db.setup();+ * await db.seed({ users: [{ id: 1, name: 'Test' }] });+ * // ... run tests+ * await db.teardown();+ */+export function createInMemoryDatabaseHelper(): DatabaseTestHelper {+ const data = new Map<string, unknown[]>();++ return {+ async setup(): Promise<void> {+ data.clear();+ },++ async teardown(): Promise<void> {+ data.clear();+ },++ async clear(): Promise<void> {+ data.clear();+ },++ async seed(seedData: Record<string, unknown[]>): Promise<void> {+ for (const [table, records] of Object.entries(seedData)) {+ data.set(table, [...records]);+ }+ },+ };+}++/**+ * Network test helper for mocking HTTP/WebSocket+ */+export interface NetworkTestHelper {+ mockFetch(responses: MockFetchResponse[]): void;+ mockWebSocket(handler: (message: unknown) => unknown): void;+ clearMocks(): void;+}++/**+ * Mock fetch response+ */+export interface MockFetchResponse {+ url: string | RegExp;+ method?: string;+ status?: number;+ body?: unknown;+ headers?: Record<string, string>;+ delay?: number;+}++/**+ * Create network test helper+ *+ * @example+ * const network = createNetworkTestHelper();+ * network.mockFetch([+ * { url: '/api/users', body: [{ id: 1 }] },+ * ]);+ */+export function createNetworkTestHelper(): NetworkTestHelper {+ const fetchResponses: MockFetchResponse[] = [];+ let originalFetch: typeof global.fetch;++ return {+ mockFetch(responses: MockFetchResponse[]): void {+ fetchResponses.push(...responses);++ if (!originalFetch) {+ originalFetch = global.fetch;++ global.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString();+ const method = init?.method ?? 'GET';++ const match = fetchResponses.find(r => {+ const urlMatch = typeof r.url === 'string'+ ? url.includes(r.url)+ : r.url.test(url);+ const methodMatch = !r.method || r.method === method;+ return urlMatch && methodMatch;+ });++ if (!match) {+ throw new Error(`No mock found for ${method} ${url}`);+ }++ if (match.delay) {+ await new Promise(resolve => setTimeout(resolve, match.delay));+ }++ return new Response(JSON.stringify(match.body), {+ status: match.status ?? 200,+ headers: match.headers ?? { 'Content-Type': 'application/json' },+ });+ });+ }+ },++ mockWebSocket(handler: (message: unknown) => unknown): void {+ // WebSocket mocking would require more setup+ // This is a placeholder for the interface+ console.warn('WebSocket mocking not yet implemented');+ },++ clearMocks(): void {+ fetchResponses.length = 0;+ if (originalFetch) {+ global.fetch = originalFetch;+ }+ },+ };+}++/**+ * File system test helper+ */+export interface FileSystemTestHelper {+ createTempDir(): Promise<string>;+ createFile(path: string, content: string): Promise<void>;+ readFile(path: string): Promise<string>;+ cleanup(): Promise<void>;+}++/**+ * Create in-memory file system helper+ *+ * @example+ * const fs = createInMemoryFileSystemHelper();+ * await fs.createFile('/test.txt', 'content');+ * const content = await fs.readFile('/test.txt');+ */+export function createInMemoryFileSystemHelper(): FileSystemTestHelper {+ const files = new Map<string, string>();+ const tempDirs: string[] = [];++ return {+ async createTempDir(): Promise<string> {+ const dir = `/tmp/test-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ tempDirs.push(dir);+ return dir;+ },++ async createFile(path: string, content: string): Promise<void> {+ files.set(path, content);+ },++ async readFile(path: string): Promise<string> {+ const content = files.get(path);+ if (content === undefined) {+ throw new Error(`File not found: ${path}`);+ }+ return content;+ },++ async cleanup(): Promise<void> {+ files.clear();+ tempDirs.length = 0;+ },+ };+}++/**+ * Performance test helper+ */+export interface PerformanceTestHelper {+ startMeasurement(name: string): void;+ endMeasurement(name: string): number;+ getMeasurements(): Record<string, number[]>;+ getStats(name: string): { min: number; max: number; avg: number; p95: number };+ clear(): void;+}++/**+ * Create performance test helper+ *+ * @example+ * const perf = createPerformanceTestHelper();+ * perf.startMeasurement('search');+ * await search();+ * const duration = perf.endMeasurement('search');+ */+export function createPerformanceTestHelper(): PerformanceTestHelper {+ const measurements = new Map<string, number[]>();+ const starts = new Map<string, number>();++ return {+ startMeasurement(name: string): void {+ starts.set(name, performance.now());+ },++ endMeasurement(name: string): number {+ const start = starts.get(name);+ if (start === undefined) {+ throw new Error(`No measurement started for: ${name}`);+ }++ const duration = performance.now() - start;+ starts.delete(name);++ if (!measurements.has(name)) {+ measurements.set(name, []);+ }+ measurements.get(name)!.push(duration);++ return duration;+ },++ getMeasurements(): Record<string, number[]> {+ return Object.fromEntries(measurements);+ },++ getStats(name: string): { min: number; max: number; avg: number; p95: number } {+ const values = measurements.get(name);+ if (!values || values.length === 0) {+ return { min: 0, max: 0, avg: 0, p95: 0 };+ }++ const sorted = [...values].sort((a, b) => a - b);+ const sum = sorted.reduce((a, b) => a + b, 0);++ return {+ min: sorted[0],+ max: sorted[sorted.length - 1],+ avg: sum / sorted.length,+ p95: sorted[Math.floor(sorted.length * 0.95)],+ };+ },++ clear(): void {+ measurements.clear();+ starts.clear();+ },+ };+}++/**+ * Standard V3 test setup+ *+ * @example+ * // In your test file:+ * setupV3Tests();+ *+ * describe('MyModule', () => {+ * // tests...+ * });+ */+export function setupV3Tests(config: V3TestConfig = {}): void {+ configureTestEnvironment({+ resetMocks: true,+ suppressConsole: config.suppressConsole ?? false,+ env: {+ NODE_ENV: 'test',+ CLAUDE_FLOW_MODE: 'test',+ ...config.env,+ },+ });+}++/**+ * V3 test configuration+ */+export interface V3TestConfig {+ suppressConsole?: boolean | ('log' | 'warn' | 'error' | 'info')[];+ env?: Record<string, string>;+ timeout?: number;+}++/**+ * Wait for all pending promises to resolve+ *+ * @example+ * await flushPromises();+ */+export function flushPromises(): Promise<void> {+ return new Promise(resolve => setImmediate(resolve));+}++/**+ * Run with timeout+ *+ * @example+ * await withTimeout(async () => {+ * await longRunningOperation();+ * }, 5000);+ */+export async function withTestTimeout<T>(+ fn: () => Promise<T>,+ timeoutMs: number = 5000+): Promise<T> {+ return Promise.race([+ fn(),+ new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error(`Test timed out after ${timeoutMs}ms`)), timeoutMs)+ ),+ ]);+}diff --git a/v3/@claude-flow/testing/src/helpers/test-utils.ts b/v3/@claude-flow/testing/src/helpers/test-utils.tsnew file mode 100644index 0000000000..fb07c8005d--- /dev/null+++ b/v3/@claude-flow/testing/src/helpers/test-utils.ts@@ -0,0 +1,669 @@+/**+ * @claude-flow/testing - Test Utilities+ *+ * Common test utilities for async operations, timing, retries, and more.+ * Designed for robust V3 module testing.+ */+import { vi } from 'vitest';++/**+ * Wait for a condition to be true with timeout+ *+ * @example+ * await waitFor(() => element.isVisible(), { timeout: 5000 });+ */+export async function waitFor<T>(+ condition: () => T | Promise<T>,+ options: WaitForOptions = {}+): Promise<T> {+ const {+ timeout = 5000,+ interval = 50,+ timeoutMessage = 'Condition not met within timeout',+ } = options;++ const startTime = Date.now();++ while (true) {+ try {+ const result = await condition();+ if (result) {+ return result;+ }+ } catch (error) {+ // Condition threw, continue waiting+ }++ if (Date.now() - startTime >= timeout) {+ throw new Error(timeoutMessage);+ }++ await sleep(interval);+ }+}++/**+ * Options for waitFor utility+ */+export interface WaitForOptions {+ timeout?: number;+ interval?: number;+ timeoutMessage?: string;+}++/**+ * Wait until a value changes+ *+ * @example+ * await waitUntilChanged(() => counter.value, { from: 0 });+ */+export async function waitUntilChanged<T>(+ getValue: () => T | Promise<T>,+ options: WaitUntilChangedOptions<T> = {}+): Promise<T> {+ const { from, timeout = 5000, interval = 50 } = options;+ const initialValue = from ?? await getValue();+ const startTime = Date.now();++ while (true) {+ const currentValue = await getValue();+ if (currentValue !== initialValue) {+ return currentValue;+ }++ if (Date.now() - startTime >= timeout) {+ throw new Error(`Value did not change from ${String(initialValue)} within timeout`);+ }++ await sleep(interval);+ }+}++/**+ * Options for waitUntilChanged utility+ */+export interface WaitUntilChangedOptions<T> {+ from?: T;+ timeout?: number;+ interval?: number;+}++/**+ * Retry an operation with exponential backoff+ *+ * @example+ * const result = await retry(+ * async () => await fetchData(),+ * { maxAttempts: 3, backoff: 100 }+ * );+ */+export async function retry<T>(+ operation: () => Promise<T>,+ options: RetryOptions = {}+): Promise<T> {+ const {+ maxAttempts = 3,+ backoff = 100,+ maxBackoff = 10000,+ exponential = true,+ onError,+ shouldRetry = () => true,+ } = options;++ let lastError: Error | undefined;+ let currentBackoff = backoff;++ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ try {+ return await operation();+ } catch (error) {+ lastError = error as Error;++ if (attempt === maxAttempts || !shouldRetry(lastError, attempt)) {+ throw lastError;+ }++ onError?.(lastError, attempt);++ await sleep(currentBackoff);++ if (exponential) {+ currentBackoff = Math.min(currentBackoff * 2, maxBackoff);+ }+ }+ }++ throw lastError;+}++/**+ * Options for retry utility+ */+export interface RetryOptions {+ maxAttempts?: number;+ backoff?: number;+ maxBackoff?: number;+ exponential?: boolean;+ onError?: (error: Error, attempt: number) => void;+ shouldRetry?: (error: Error, attempt: number) => boolean;+}++/**+ * Wrap an operation with a timeout+ *+ * @example+ * const result = await withTimeout(+ * async () => await longRunningOperation(),+ * 5000+ * );+ */+export async function withTimeout<T>(+ operation: () => Promise<T>,+ timeoutMs: number,+ timeoutMessage?: string+): Promise<T> {+ const timeoutPromise = new Promise<never>((_, reject) => {+ const timer = setTimeout(() => {+ reject(new TimeoutError(timeoutMessage ?? `Operation timed out after ${timeoutMs}ms`));+ }, timeoutMs);++ // Cleanup timer if operation completes first+ operation().finally(() => clearTimeout(timer));+ });++ return Promise.race([operation(), timeoutPromise]);+}++/**+ * Custom timeout error+ */+export class TimeoutError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'TimeoutError';+ }+}++/**+ * Sleep for a specified duration+ *+ * @example+ * await sleep(1000); // Sleep for 1 second+ */+export function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}++/**+ * Create a deferred promise that can be resolved/rejected externally+ *+ * @example+ * const deferred = createDeferred<string>();+ * setTimeout(() => deferred.resolve('done'), 1000);+ * const result = await deferred.promise;+ */+export function createDeferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;++ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });++ return { promise, resolve, reject };+}++/**+ * Deferred promise interface+ */+export interface Deferred<T> {+ promise: Promise<T>;+ resolve: (value: T) => void;+ reject: (error: Error) => void;+}++/**+ * Run operations in parallel with concurrency limit+ *+ * @example+ * const results = await parallelLimit(+ * items.map(item => () => processItem(item)),+ * 5 // max 5 concurrent operations+ * );+ */+export async function parallelLimit<T>(+ operations: Array<() => Promise<T>>,+ limit: number+): Promise<T[]> {+ const results: T[] = [];+ const executing: Set<Promise<void>> = new Set();++ for (const operation of operations) {+ const promise = (async () => {+ const result = await operation();+ results.push(result);+ })();++ executing.add(promise);+ promise.finally(() => executing.delete(promise));++ if (executing.size >= limit) {+ await Promise.race(executing);+ }+ }++ await Promise.all(executing);+ return results;+}++/**+ * Measure execution time of an operation+ *+ * @example+ * const { result, duration } = await measureTime(async () => {+ * return await expensiveOperation();+ * });+ */+export async function measureTime<T>(+ operation: () => Promise<T>+): Promise<{ result: T; duration: number }> {+ const start = performance.now();+ const result = await operation();+ const duration = performance.now() - start;+ return { result, duration };+}++/**+ * Create a mock clock for time-dependent tests+ *+ * @example+ * const clock = createMockClock();+ * clock.install();+ * // ... tests with controlled time+ * clock.uninstall();+ */+export function createMockClock(): MockClock {+ let installed = false;+ let currentTime = Date.now();++ return {+ install() {+ if (installed) return;+ vi.useFakeTimers();+ vi.setSystemTime(currentTime);+ installed = true;+ },++ uninstall() {+ if (!installed) return;+ vi.useRealTimers();+ installed = false;+ },++ tick(ms: number) {+ if (!installed) {+ throw new Error('Clock not installed. Call install() first.');+ }+ currentTime += ms;+ vi.advanceTimersByTime(ms);+ },++ setTime(time: number | Date) {+ currentTime = typeof time === 'number' ? time : time.getTime();+ if (installed) {+ vi.setSystemTime(currentTime);+ }+ },++ getTime() {+ return currentTime;+ },++ runAllTimers() {+ if (!installed) {+ throw new Error('Clock not installed. Call install() first.');+ }+ vi.runAllTimers();+ },++ runPendingTimers() {+ if (!installed) {+ throw new Error('Clock not installed. Call install() first.');+ }+ vi.runOnlyPendingTimers();+ },+ };+}++/**+ * Mock clock interface+ */+export interface MockClock {+ install(): void;+ uninstall(): void;+ tick(ms: number): void;+ setTime(time: number | Date): void;+ getTime(): number;+ runAllTimers(): void;+ runPendingTimers(): void;+}++/**+ * Create an event emitter for testing+ *+ * @example+ * const emitter = createTestEmitter<{ message: string }>();+ * const handler = vi.fn();+ * emitter.on('message', handler);+ * emitter.emit('message', 'hello');+ */+export function createTestEmitter<T extends Record<string, unknown>>(): TestEmitter<T> {+ const listeners = new Map<keyof T, Set<(data: unknown) => void>>();++ return {+ on<K extends keyof T>(event: K, handler: (data: T[K]) => void): () => void {+ if (!listeners.has(event)) {+ listeners.set(event, new Set());+ }+ listeners.get(event)!.add(handler as (data: unknown) => void);++ return () => {+ listeners.get(event)?.delete(handler as (data: unknown) => void);+ };+ },++ once<K extends keyof T>(event: K, handler: (data: T[K]) => void): () => void {+ const wrappedHandler = (data: T[K]) => {+ this.off(event, wrappedHandler);+ handler(data);+ };+ return this.on(event, wrappedHandler);+ },++ off<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {+ listeners.get(event)?.delete(handler as (data: unknown) => void);+ },++ emit<K extends keyof T>(event: K, data: T[K]): void {+ listeners.get(event)?.forEach(handler => handler(data));+ },++ removeAllListeners(event?: keyof T): void {+ if (event) {+ listeners.delete(event);+ } else {+ listeners.clear();+ }+ },++ listenerCount(event: keyof T): number {+ return listeners.get(event)?.size ?? 0;+ },+ };+}++/**+ * Test emitter interface+ */+export interface TestEmitter<T extends Record<string, unknown>> {+ on<K extends keyof T>(event: K, handler: (data: T[K]) => void): () => void;+ once<K extends keyof T>(event: K, handler: (data: T[K]) => void): () => void;+ off<K extends keyof T>(event: K, handler: (data: T[K]) => void): void;+ emit<K extends keyof T>(event: K, data: T[K]): void;+ removeAllListeners(event?: keyof T): void;+ listenerCount(event: keyof T): number;+}++/**+ * Create a test spy that records all calls+ *+ * @example+ * const spy = createCallSpy();+ * myFunction = spy.wrap(myFunction);+ * // ... use myFunction+ * expect(spy.calls).toHaveLength(3);+ */+export function createCallSpy<T extends (...args: unknown[]) => unknown>(): CallSpy<T> {+ const calls: Array<{ args: Parameters<T>; result?: ReturnType<T>; error?: Error; timestamp: number }> = [];++ return {+ calls,++ wrap(fn: T): T {+ return ((...args: Parameters<T>) => {+ const call = { args, timestamp: Date.now() } as typeof calls[number];+ calls.push(call);++ try {+ const result = fn(...args);+ call.result = result as ReturnType<T>;+ return result;+ } catch (error) {+ call.error = error as Error;+ throw error;+ }+ }) as T;+ },++ clear() {+ calls.length = 0;+ },++ getLastCall() {+ return calls[calls.length - 1];+ },++ getCallCount() {+ return calls.length;+ },++ wasCalledWith(...args: Partial<Parameters<T>>): boolean {+ return calls.some(call =>+ args.every((arg, i) => arg === undefined || call.args[i] === arg)+ );+ },+ };+}++/**+ * Call spy interface+ */+export interface CallSpy<T extends (...args: unknown[]) => unknown> {+ calls: Array<{ args: Parameters<T>; result?: ReturnType<T>; error?: Error; timestamp: number }>;+ wrap(fn: T): T;+ clear(): void;+ getLastCall(): { args: Parameters<T>; result?: ReturnType<T>; error?: Error; timestamp: number } | undefined;+ getCallCount(): number;+ wasCalledWith(...args: Partial<Parameters<T>>): boolean;+}++/**+ * Create a mock stream for testing streaming operations+ *+ * @example+ * const stream = createMockStream(['chunk1', 'chunk2', 'chunk3']);+ * for await (const chunk of stream) {+ * console.log(chunk);+ * }+ */+export function createMockStream<T>(+ chunks: T[],+ options: MockStreamOptions = {}+): AsyncIterable<T> {+ const { delayMs = 0, errorAt, errorMessage = 'Stream error' } = options;++ return {+ async *[Symbol.asyncIterator]() {+ for (let i = 0; i < chunks.length; i++) {+ if (errorAt !== undefined && i === errorAt) {+ throw new Error(errorMessage);+ }++ if (delayMs > 0) {+ await sleep(delayMs);+ }++ yield chunks[i];+ }+ },+ };+}++/**+ * Mock stream options+ */+export interface MockStreamOptions {+ delayMs?: number;+ errorAt?: number;+ errorMessage?: string;+}++/**+ * Collect all items from an async iterable+ *+ * @example+ * const items = await collectStream(asyncGenerator());+ */+export async function collectStream<T>(stream: AsyncIterable<T>): Promise<T[]> {+ const items: T[] = [];+ for await (const item of stream) {+ items.push(item);+ }+ return items;+}++/**+ * Generate a unique ID for testing+ */+export function generateTestId(prefix: string = 'test'): string {+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;+}++/**+ * Create a test context that provides isolated test data+ *+ * @example+ * const ctx = createTestContext();+ * ctx.set('user', { id: 1, name: 'Test' });+ * const user = ctx.get('user');+ */+export function createTestContext(): TestContext {+ const data = new Map<string, unknown>();++ return {+ set<T>(key: string, value: T): void {+ data.set(key, value);+ },++ get<T>(key: string): T | undefined {+ return data.get(key) as T | undefined;+ },++ has(key: string): boolean {+ return data.has(key);+ },++ delete(key: string): boolean {+ return data.delete(key);+ },++ clear(): void {+ data.clear();+ },++ keys(): string[] {+ return Array.from(data.keys());+ },+ };+}++/**+ * Test context interface+ */+export interface TestContext {+ set<T>(key: string, value: T): void;+ get<T>(key: string): T | undefined;+ has(key: string): boolean;+ delete(key: string): boolean;+ clear(): void;+ keys(): string[];+}++/**+ * Assert that a promise rejects with a specific error type+ *+ * @example+ * await expectToReject(+ * async () => await riskyOperation(),+ * ValidationError+ * );+ */+export async function expectToReject<T extends Error>(+ operation: () => Promise<unknown>,+ ErrorClass?: new (...args: unknown[]) => T+): Promise<T> {+ try {+ await operation();+ throw new Error('Expected operation to reject, but it resolved');+ } catch (error) {+ if (ErrorClass && !(error instanceof ErrorClass)) {+ throw new Error(+ `Expected error to be instance of ${ErrorClass.name}, but got ${(error as Error).constructor.name}`+ );+ }+ return error as T;+ }+}++/**+ * Create a mock function with tracking capabilities+ */+export function createTrackedMock<T extends (...args: unknown[]) => unknown>(+ implementation?: T+): TrackedMock<T> {+ const mock = vi.fn(implementation);+ const calls: Array<{ args: Parameters<T>; result?: ReturnType<T>; error?: Error; duration: number }> = [];++ const tracked = ((...args: Parameters<T>) => {+ const start = performance.now();+ const call: typeof calls[number] = { args, duration: 0 };+ calls.push(call);++ try {+ const result = mock(...args);+ call.result = result as ReturnType<T>;+ call.duration = performance.now() - start;+ return result;+ } catch (error) {+ call.error = error as Error;+ call.duration = performance.now() - start;+ throw error;+ }+ }) as TrackedMock<T>;++ Object.assign(tracked, {+ mock,+ calls,+ getAverageDuration: () => {+ if (calls.length === 0) return 0;+ return calls.reduce((sum, c) => sum + c.duration, 0) / calls.length;+ },+ getTotalDuration: () => calls.reduce((sum, c) => sum + c.duration, 0),+ getErrors: () => calls.filter(c => c.error).map(c => c.error!),+ });++ return tracked;+}++/**+ * Tracked mock interface+ */+export interface TrackedMock<T extends (...args: unknown[]) => unknown> {+ (...args: Parameters<T>): ReturnType<T>;+ mock: ReturnType<typeof vi.fn<T>>;+ calls: Array<{ args: Parameters<T>; result?: ReturnType<T>; error?: Error; duration: number }>;+ getAverageDuration(): number;+ getTotalDuration(): number;+ getErrors(): Error[];+}diff --git a/v3/@claude-flow/testing/src/mocks/index.ts b/v3/@claude-flow/testing/src/mocks/index.tsnew file mode 100644index 0000000000..240784e076--- /dev/null+++ b/v3/@claude-flow/testing/src/mocks/index.ts@@ -0,0 +1,29 @@+/**+ * @claude-flow/testing - Mocks Index+ *+ * Central export for all mock implementations+ */++// Mock services+export {+ MockAgentDB,+ MockSwarmCoordinator,+ MockSwarmAgent,+ MockMemoryService,+ MockEventBus,+ MockSecurityService,+ createMockServices,+ resetMockServices,+ type MockServiceBundle,+} from './mock-services.js';++// Mock MCP client and server+export {+ MockMCPClient,+ MockMCPServer,+ MockMCPConnection,+ MCPClientError,+ createStandardMockMCPClient,+ createFailingMockMCPClient,+ createSlowMockMCPClient,+} from './mock-mcp-client.js';diff --git a/v3/@claude-flow/testing/src/mocks/mock-mcp-client.ts b/v3/@claude-flow/testing/src/mocks/mock-mcp-client.tsnew file mode 100644index 0000000000..bf83dee13d--- /dev/null+++ b/v3/@claude-flow/testing/src/mocks/mock-mcp-client.ts@@ -0,0 +1,723 @@+/**+ * @claude-flow/testing - Mock MCP Client+ *+ * Comprehensive mock MCP client for testing CLI and server interactions.+ * Simulates full MCP protocol behavior with request/response tracking.+ */+import { vi, type Mock } from 'vitest';+import type {+ MCPTool,+ MCPToolResult,+ MCPResource,+ MCPPrompt,+ MCPServerConfig,+ MCPSessionContext,+ MCPError,+ MCPContent,+ mcpTools,+ mcpResources,+ mcpPrompts,+ mcpToolResults,+ mcpErrors,+} from '../fixtures/mcp-fixtures.js';++/**+ * Mock MCP Client with full protocol simulation+ */+export class MockMCPClient {+ private _connected = false;+ private _session: MCPSessionContext | null = null;+ private _tools = new Map<string, MCPTool>();+ private _resources = new Map<string, MCPResource>();+ private _prompts = new Map<string, MCPPrompt>();+ private _requestHistory: MCPRequest[] = [];+ private _responseHistory: MCPResponse[] = [];+ private _toolHandlers = new Map<string, ToolHandler>();+ private _errorSimulation: ErrorSimulation | null = null;+ private _latencySimulation = 0;++ // Mock methods for verification+ connect = vi.fn(async () => {+ if (this._errorSimulation?.onConnect) {+ throw new Error(this._errorSimulation.onConnect);+ }++ await this.simulateLatency();++ this._connected = true;+ this._session = {+ sessionId: `session-${Date.now()}`,+ clientInfo: {+ name: 'mock-client',+ version: '1.0.0',+ },+ capabilities: {+ tools: true,+ resources: true,+ prompts: true,+ },+ startedAt: new Date(),+ lastActivity: new Date(),+ requestCount: 0,+ };+ });++ disconnect = vi.fn(async () => {+ if (this._errorSimulation?.onDisconnect) {+ throw new Error(this._errorSimulation.onDisconnect);+ }++ this._connected = false;+ this._session = null;+ });++ callTool = vi.fn(async (name: string, params: Record<string, unknown>): Promise<MCPToolResult> => {+ this.ensureConnected();++ const request: MCPRequest = {+ id: `req-${Date.now()}`,+ method: 'tools/call',+ params: { name, arguments: params },+ timestamp: new Date(),+ };+ this._requestHistory.push(request);++ if (this._session) {+ this._session.requestCount++;+ this._session.lastActivity = new Date();+ }++ await this.simulateLatency();++ // Check for error simulation+ if (this._errorSimulation?.onToolCall?.[name]) {+ const error = this._errorSimulation.onToolCall[name];+ const response: MCPResponse = {+ id: request.id,+ error: typeof error === 'string' ? { code: -32000, message: error } : error,+ timestamp: new Date(),+ };+ this._responseHistory.push(response);+ throw new MCPClientError(response.error!.message, response.error!.code);+ }++ // Check for custom handler+ const handler = this._toolHandlers.get(name);+ if (handler) {+ const result = await handler(params);+ const response: MCPResponse = {+ id: request.id,+ result,+ timestamp: new Date(),+ };+ this._responseHistory.push(response);+ return result;+ }++ // Check for registered tool+ const tool = this._tools.get(name);+ if (!tool) {+ const response: MCPResponse = {+ id: request.id,+ error: { code: -32601, message: `Tool not found: ${name}` },+ timestamp: new Date(),+ };+ this._responseHistory.push(response);+ throw new MCPClientError(`Tool not found: ${name}`, -32601);+ }++ // Default success response+ const result: MCPToolResult = {+ content: [{ type: 'text', text: JSON.stringify({ success: true, tool: name, params }) }],+ };+ const response: MCPResponse = {+ id: request.id,+ result,+ timestamp: new Date(),+ };+ this._responseHistory.push(response);++ return result;+ });++ listTools = vi.fn(async (): Promise<MCPTool[]> => {+ this.ensureConnected();+ await this.simulateLatency();+ return Array.from(this._tools.values());+ });++ readResource = vi.fn(async (uri: string): Promise<MCPResourceContent> => {+ this.ensureConnected();++ const request: MCPRequest = {+ id: `req-${Date.now()}`,+ method: 'resources/read',+ params: { uri },+ timestamp: new Date(),+ };+ this._requestHistory.push(request);++ await this.simulateLatency();++ const resource = this._resources.get(uri);+ if (!resource) {+ throw new MCPClientError(`Resource not found: ${uri}`, -32002);+ }++ return {+ type: 'resource',+ resource: {+ uri,+ mimeType: resource.mimeType,+ text: JSON.stringify({ name: resource.name, description: resource.description }),+ },+ };+ });++ listResources = vi.fn(async (): Promise<MCPResource[]> => {+ this.ensureConnected();+ await this.simulateLatency();+ return Array.from(this._resources.values());+ });++ getPrompt = vi.fn(async (name: string, args: Record<string, string>): Promise<MCPPromptResult> => {+ this.ensureConnected();++ const prompt = this._prompts.get(name);+ if (!prompt) {+ throw new MCPClientError(`Prompt not found: ${name}`, -32003);+ }++ await this.simulateLatency();++ return {+ messages: [+ {+ role: 'user',+ content: { type: 'text', text: `Prompt: ${name}\nArgs: ${JSON.stringify(args)}` },+ },+ ],+ };+ });++ listPrompts = vi.fn(async (): Promise<MCPPrompt[]> => {+ this.ensureConnected();+ await this.simulateLatency();+ return Array.from(this._prompts.values());+ });++ isConnected = vi.fn(() => this._connected);++ getSession = vi.fn(() => this._session);++ /**+ * Register a tool+ */+ registerTool(tool: MCPTool): void {+ this._tools.set(tool.name, tool);+ }++ /**+ * Register multiple tools+ */+ registerTools(tools: MCPTool[]): void {+ for (const tool of tools) {+ this.registerTool(tool);+ }+ }++ /**+ * Register a custom tool handler+ */+ setToolHandler(name: string, handler: ToolHandler): void {+ this._toolHandlers.set(name, handler);+ }++ /**+ * Register a resource+ */+ registerResource(resource: MCPResource): void {+ this._resources.set(resource.uri, resource);+ }++ /**+ * Register multiple resources+ */+ registerResources(resources: MCPResource[]): void {+ for (const resource of resources) {+ this.registerResource(resource);+ }+ }++ /**+ * Register a prompt+ */+ registerPrompt(prompt: MCPPrompt): void {+ this._prompts.set(prompt.name, prompt);+ }++ /**+ * Register multiple prompts+ */+ registerPrompts(prompts: MCPPrompt[]): void {+ for (const prompt of prompts) {+ this.registerPrompt(prompt);+ }+ }++ /**+ * Configure error simulation+ */+ simulateErrors(config: ErrorSimulation): void {+ this._errorSimulation = config;+ }++ /**+ * Configure latency simulation+ */+ simulateLatency(ms: number): void {+ this._latencySimulation = ms;+ }++ /**+ * Get request history+ */+ getRequestHistory(): MCPRequest[] {+ return [...this._requestHistory];+ }++ /**+ * Get response history+ */+ getResponseHistory(): MCPResponse[] {+ return [...this._responseHistory];+ }++ /**+ * Get last request+ */+ getLastRequest(): MCPRequest | undefined {+ return this._requestHistory[this._requestHistory.length - 1];+ }++ /**+ * Get last response+ */+ getLastResponse(): MCPResponse | undefined {+ return this._responseHistory[this._responseHistory.length - 1];+ }++ /**+ * Clear history+ */+ clearHistory(): void {+ this._requestHistory = [];+ this._responseHistory = [];+ }++ /**+ * Reset client to initial state+ */+ reset(): void {+ this._connected = false;+ this._session = null;+ this._tools.clear();+ this._resources.clear();+ this._prompts.clear();+ this._requestHistory = [];+ this._responseHistory = [];+ this._toolHandlers.clear();+ this._errorSimulation = null;+ this._latencySimulation = 0;+ vi.clearAllMocks();+ }++ private ensureConnected(): void {+ if (!this._connected) {+ throw new MCPClientError('Not connected', -32000);+ }+ }++ private async simulateLatency(): Promise<void> {+ if (this._latencySimulation > 0) {+ await new Promise(resolve => setTimeout(resolve, this._latencySimulation));+ }+ }+}++/**+ * Mock MCP Server for testing server-side behavior+ */+export class MockMCPServer {+ private _running = false;+ private _config: MCPServerConfig | null = null;+ private _tools = new Map<string, MCPTool>();+ private _resources = new Map<string, MCPResource>();+ private _prompts = new Map<string, MCPPrompt>();+ private _connections: MockMCPConnection[] = [];+ private _requestLog: MCPRequest[] = [];+ private _errorCount = 0;++ start = vi.fn(async (config: MCPServerConfig) => {+ this._config = config;+ this._running = true;++ // Register configured tools/resources/prompts+ if (config.tools) {+ for (const tool of config.tools) {+ this._tools.set(tool.name, tool);+ }+ }+ if (config.resources) {+ for (const resource of config.resources) {+ this._resources.set(resource.uri, resource);+ }+ }+ if (config.prompts) {+ for (const prompt of config.prompts) {+ this._prompts.set(prompt.name, prompt);+ }+ }+ });++ stop = vi.fn(async () => {+ for (const conn of this._connections) {+ await conn.close();+ }+ this._connections = [];+ this._running = false;+ });++ handleRequest = vi.fn(async (request: MCPRequest): Promise<MCPResponse> => {+ this._requestLog.push(request);++ try {+ switch (request.method) {+ case 'tools/call':+ return this.handleToolCall(request);+ case 'resources/read':+ return this.handleResourceRead(request);+ case 'prompts/get':+ return this.handlePromptGet(request);+ case 'tools/list':+ return { id: request.id, result: Array.from(this._tools.values()), timestamp: new Date() };+ case 'resources/list':+ return { id: request.id, result: Array.from(this._resources.values()), timestamp: new Date() };+ case 'prompts/list':+ return { id: request.id, result: Array.from(this._prompts.values()), timestamp: new Date() };+ default:+ throw new MCPClientError(`Unknown method: ${request.method}`, -32601);+ }+ } catch (error) {+ this._errorCount++;+ return {+ id: request.id,+ error: { code: -32000, message: (error as Error).message },+ timestamp: new Date(),+ };+ }+ });++ registerTool = vi.fn((tool: MCPTool) => {+ this._tools.set(tool.name, tool);+ });++ registerResource = vi.fn((resource: MCPResource) => {+ this._resources.set(resource.uri, resource);+ });++ registerPrompt = vi.fn((prompt: MCPPrompt) => {+ this._prompts.set(prompt.name, prompt);+ });++ getStatus = vi.fn((): MCPServerStatus => ({+ running: this._running,+ transport: this._config?.transport.type ?? 'stdio',+ connectedClients: this._connections.length,+ toolsRegistered: this._tools.size,+ resourcesRegistered: this._resources.size,+ promptsRegistered: this._prompts.size,+ requestsHandled: this._requestLog.length,+ errorsCount: this._errorCount,+ uptime: this._running ? Date.now() : 0,+ }));++ /**+ * Simulate a client connection+ */+ acceptConnection(): MockMCPConnection {+ const conn = new MockMCPConnection(this);+ this._connections.push(conn);+ return conn;+ }++ /**+ * Get request log+ */+ getRequestLog(): MCPRequest[] {+ return [...this._requestLog];+ }++ /**+ * Reset server+ */+ reset(): void {+ this._running = false;+ this._config = null;+ this._tools.clear();+ this._resources.clear();+ this._prompts.clear();+ this._connections = [];+ this._requestLog = [];+ this._errorCount = 0;+ vi.clearAllMocks();+ }++ private handleToolCall(request: MCPRequest): MCPResponse {+ const { name, arguments: params } = request.params as { name: string; arguments: Record<string, unknown> };+ const tool = this._tools.get(name);++ if (!tool) {+ return {+ id: request.id,+ error: { code: -32601, message: `Tool not found: ${name}` },+ timestamp: new Date(),+ };+ }++ return {+ id: request.id,+ result: {+ content: [{ type: 'text', text: JSON.stringify({ success: true, tool: name }) }],+ },+ timestamp: new Date(),+ };+ }++ private handleResourceRead(request: MCPRequest): MCPResponse {+ const { uri } = request.params as { uri: string };+ const resource = this._resources.get(uri);++ if (!resource) {+ return {+ id: request.id,+ error: { code: -32002, message: `Resource not found: ${uri}` },+ timestamp: new Date(),+ };+ }++ return {+ id: request.id,+ result: {+ type: 'resource',+ resource: { uri, mimeType: resource.mimeType, text: '{}' },+ },+ timestamp: new Date(),+ };+ }++ private handlePromptGet(request: MCPRequest): MCPResponse {+ const { name } = request.params as { name: string };+ const prompt = this._prompts.get(name);++ if (!prompt) {+ return {+ id: request.id,+ error: { code: -32003, message: `Prompt not found: ${name}` },+ timestamp: new Date(),+ };+ }++ return {+ id: request.id,+ result: {+ messages: [{ role: 'user', content: { type: 'text', text: `Prompt: ${name}` } }],+ },+ timestamp: new Date(),+ };+ }+}++/**+ * Mock MCP Connection+ */+export class MockMCPConnection {+ private _open = true;+ private _server: MockMCPServer;++ constructor(server: MockMCPServer) {+ this._server = server;+ }++ send = vi.fn(async (request: MCPRequest): Promise<MCPResponse> => {+ if (!this._open) {+ throw new MCPClientError('Connection closed', -32000);+ }+ return this._server.handleRequest(request);+ });++ close = vi.fn(async () => {+ this._open = false;+ });++ isOpen(): boolean {+ return this._open;+ }+}++/**+ * MCP Client Error+ */+export class MCPClientError extends Error {+ constructor(message: string, public code: number) {+ super(message);+ this.name = 'MCPClientError';+ }+}++// Supporting types+interface MCPRequest {+ id: string;+ method: string;+ params?: Record<string, unknown>;+ timestamp: Date;+}++interface MCPResponse {+ id: string;+ result?: unknown;+ error?: MCPError;+ timestamp: Date;+}++interface MCPResourceContent {+ type: 'resource';+ resource: {+ uri: string;+ mimeType?: string;+ text?: string;+ blob?: string;+ };+}++interface MCPPromptResult {+ messages: Array<{+ role: 'user' | 'assistant';+ content: MCPContent;+ }>;+}++interface MCPServerStatus {+ running: boolean;+ transport: string;+ connectedClients: number;+ toolsRegistered: number;+ resourcesRegistered: number;+ promptsRegistered: number;+ requestsHandled: number;+ errorsCount: number;+ uptime: number;+}++type ToolHandler = (params: Record<string, unknown>) => Promise<MCPToolResult>;++interface ErrorSimulation {+ onConnect?: string;+ onDisconnect?: string;+ onToolCall?: Record<string, string | MCPError>;+}++/**+ * Create a pre-configured mock MCP client with standard tools+ */+export function createStandardMockMCPClient(): MockMCPClient {+ const client = new MockMCPClient();++ // Register standard Claude-Flow tools+ client.registerTool({+ name: 'swarm_init',+ description: 'Initialize a new swarm',+ inputSchema: {+ type: 'object',+ properties: {+ topology: { type: 'string' },+ maxAgents: { type: 'number' },+ },+ required: ['topology'],+ },+ });++ client.registerTool({+ name: 'agent_spawn',+ description: 'Spawn a new agent',+ inputSchema: {+ type: 'object',+ properties: {+ type: { type: 'string' },+ name: { type: 'string' },+ },+ required: ['type'],+ },+ });++ client.registerTool({+ name: 'task_orchestrate',+ description: 'Orchestrate a task',+ inputSchema: {+ type: 'object',+ properties: {+ taskName: { type: 'string' },+ taskType: { type: 'string' },+ },+ required: ['taskName', 'taskType'],+ },+ });++ client.registerTool({+ name: 'memory_store',+ description: 'Store a value in memory',+ inputSchema: {+ type: 'object',+ properties: {+ key: { type: 'string' },+ value: { type: 'object' },+ },+ required: ['key', 'value'],+ },+ });++ client.registerTool({+ name: 'memory_search',+ description: 'Search memory',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string' },+ topK: { type: 'number' },+ },+ required: ['query'],+ },+ });++ return client;+}++/**+ * Create a mock MCP client that simulates failures+ */+export function createFailingMockMCPClient(+ errorConfig: ErrorSimulation+): MockMCPClient {+ const client = new MockMCPClient();+ client.simulateErrors(errorConfig);+ return client;+}++/**+ * Create a mock MCP client with latency+ */+export function createSlowMockMCPClient(latencyMs: number): MockMCPClient {+ const client = new MockMCPClient();+ client.simulateLatency(latencyMs);+ return client;+}diff --git a/v3/@claude-flow/testing/src/mocks/mock-services.ts b/v3/@claude-flow/testing/src/mocks/mock-services.tsnew file mode 100644index 0000000000..db8aca215d--- /dev/null+++ b/v3/@claude-flow/testing/src/mocks/mock-services.ts@@ -0,0 +1,793 @@+/**+ * @claude-flow/testing - Mock Services+ *+ * Comprehensive mock implementations of V3 core services.+ * Provides realistic behavior for testing with full state tracking.+ */+import { vi, type Mock } from 'vitest';+import type { V3AgentType } from '../fixtures/agent-fixtures.js';++/**+ * Mock AgentDB - Vector database mock with HNSW simulation+ */+export class MockAgentDB {+ private vectors = new Map<string, { embedding: number[]; metadata: Record<string, unknown> }>();+ private indexConfig = {+ M: 16,+ efConstruction: 200,+ efSearch: 50,+ dimensions: 384,+ };++ // Mock methods for verification+ insert = vi.fn(async (id: string, embedding: number[], metadata?: Record<string, unknown>) => {+ if (embedding.length !== this.indexConfig.dimensions) {+ throw new Error(`Invalid embedding dimensions: expected ${this.indexConfig.dimensions}, got ${embedding.length}`);+ }+ this.vectors.set(id, { embedding, metadata: metadata ?? {} });+ });++ search = vi.fn(async (embedding: number[], k: number, threshold?: number) => {+ const results: Array<{ id: string; score: number; metadata: Record<string, unknown> }> = [];++ for (const [id, data] of this.vectors) {+ const score = this.cosineSimilarity(embedding, data.embedding);+ if (threshold === undefined || score >= threshold) {+ results.push({ id, score, metadata: data.metadata });+ }+ }++ return results+ .sort((a, b) => b.score - a.score)+ .slice(0, k);+ });++ delete = vi.fn(async (id: string) => {+ this.vectors.delete(id);+ });++ update = vi.fn(async (id: string, embedding: number[], metadata?: Record<string, unknown>) => {+ const existing = this.vectors.get(id);+ if (!existing) {+ throw new Error(`Vector not found: ${id}`);+ }+ this.vectors.set(id, { embedding, metadata: metadata ?? existing.metadata });+ });++ getVector = vi.fn(async (id: string) => {+ return this.vectors.get(id) ?? null;+ });++ getStats = vi.fn(() => ({+ vectorCount: this.vectors.size,+ indexSize: this.vectors.size * this.indexConfig.dimensions * 4, // 4 bytes per float+ dimensions: this.indexConfig.dimensions,+ M: this.indexConfig.M,+ efConstruction: this.indexConfig.efConstruction,+ }));++ rebuildIndex = vi.fn(async () => {+ // Simulate index rebuild+ await new Promise(resolve => setTimeout(resolve, 10));+ });++ clear = vi.fn(() => {+ this.vectors.clear();+ });++ private cosineSimilarity(a: number[], b: number[]): number {+ let dotProduct = 0;+ let normA = 0;+ let normB = 0;++ for (let i = 0; i < a.length; i++) {+ dotProduct += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }++ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));+ }++ /**+ * Configure the mock index+ */+ configure(config: Partial<typeof this.indexConfig>): void {+ Object.assign(this.indexConfig, config);+ }++ /**+ * Get all stored vectors (for testing)+ */+ getAllVectors(): Map<string, { embedding: number[]; metadata: Record<string, unknown> }> {+ return new Map(this.vectors);+ }+}++/**+ * Mock Unified Swarm Coordinator+ */+export class MockSwarmCoordinator {+ private agents = new Map<string, MockSwarmAgent>();+ private state: SwarmState = {+ id: `swarm-${Date.now()}`,+ topology: 'hierarchical-mesh',+ status: 'idle',+ agentCount: 0,+ activeAgentCount: 0,+ leaderId: undefined,+ createdAt: new Date(),+ };+ private messageQueue: SwarmMessage[] = [];+ private taskQueue: SwarmTask[] = [];++ initialize = vi.fn(async (config: SwarmInitConfig) => {+ this.state = {+ ...this.state,+ topology: config.topology ?? 'hierarchical-mesh',+ status: 'active',+ };+ return this.state;+ });++ shutdown = vi.fn(async (graceful: boolean = true) => {+ if (graceful) {+ // Complete pending tasks+ await Promise.all(+ Array.from(this.agents.values()).map(agent => agent.terminate())+ );+ }+ this.state.status = 'shutdown';+ this.agents.clear();+ });++ addAgent = vi.fn(async (config: AgentConfig) => {+ const id = `agent-${config.type}-${Date.now()}`;+ const agent = new MockSwarmAgent(id, config);+ this.agents.set(id, agent);+ this.state.agentCount++;+ this.state.activeAgentCount++;++ if (config.type === 'queen-coordinator' && !this.state.leaderId) {+ this.state.leaderId = id;+ }++ return agent;+ });++ removeAgent = vi.fn(async (agentId: string) => {+ const agent = this.agents.get(agentId);+ if (agent) {+ await agent.terminate();+ this.agents.delete(agentId);+ this.state.agentCount--;+ this.state.activeAgentCount--;++ if (this.state.leaderId === agentId) {+ this.electNewLeader();+ }+ }+ });++ coordinate = vi.fn(async (task: SwarmTask) => {+ this.taskQueue.push(task);++ // Find suitable agents+ const suitableAgents = Array.from(this.agents.values())+ .filter(agent => agent.canHandle(task.type))+ .sort((a, b) => b.priority - a.priority);++ if (suitableAgents.length === 0) {+ return {+ success: false,+ error: 'No suitable agents available',+ taskId: task.id,+ duration: 0,+ };+ }++ const startTime = Date.now();+ const results: TaskResult[] = [];++ for (const agent of suitableAgents.slice(0, task.maxAgents ?? 1)) {+ const result = await agent.execute(task);+ results.push(result);+ }++ return {+ success: results.every(r => r.success),+ taskId: task.id,+ duration: Date.now() - startTime,+ results,+ };+ });++ broadcast = vi.fn(async (message: Omit<SwarmMessage, 'id' | 'timestamp'>) => {+ const fullMessage: SwarmMessage = {+ ...message,+ id: `msg-${Date.now()}`,+ timestamp: new Date(),+ to: 'broadcast',+ };+ this.messageQueue.push(fullMessage);++ for (const agent of this.agents.values()) {+ await agent.receive(fullMessage);+ }+ });++ sendMessage = vi.fn(async (message: SwarmMessage) => {+ this.messageQueue.push(message);++ if (message.to === 'broadcast') {+ for (const agent of this.agents.values()) {+ await agent.receive(message);+ }+ } else {+ const agent = this.agents.get(message.to);+ if (agent) {+ await agent.receive(message);+ }+ }+ });++ requestConsensus = vi.fn(async <T>(request: ConsensusRequest<T>): Promise<ConsensusResponse<T>> => {+ const voters = request.voters ?? Array.from(this.agents.keys());+ const votes = new Map<string, T>();++ for (const voterId of voters) {+ const agent = this.agents.get(voterId);+ if (agent) {+ // Simulate voting - random selection+ const vote = request.options[Math.floor(Math.random() * request.options.length)];+ votes.set(voterId, vote);+ }+ }++ const voteCounts = new Map<string, number>();+ for (const vote of votes.values()) {+ const key = JSON.stringify(vote);+ voteCounts.set(key, (voteCounts.get(key) ?? 0) + 1);+ }++ const majority = Math.floor(voters.length / 2) + 1;+ let decision: T | null = null;+ let consensus = false;++ for (const [key, count] of voteCounts) {+ if (count >= majority) {+ decision = JSON.parse(key);+ consensus = true;+ break;+ }+ }++ return {+ topic: request.topic,+ decision,+ votes,+ consensus,+ votingDuration: 100,+ participatingAgents: Array.from(votes.keys()),+ };+ });++ getState = vi.fn(() => ({ ...this.state }));++ getAgent = vi.fn((id: string) => this.agents.get(id));++ getAgents = vi.fn(() => Array.from(this.agents.values()));++ getMessageQueue = vi.fn(() => [...this.messageQueue]);++ getTaskQueue = vi.fn(() => [...this.taskQueue]);++ private electNewLeader(): void {+ const candidates = Array.from(this.agents.values())+ .filter(a => a.config.type === 'queen-coordinator')+ .sort((a, b) => b.priority - a.priority);++ this.state.leaderId = candidates[0]?.id;+ }++ reset(): void {+ this.agents.clear();+ this.messageQueue = [];+ this.taskQueue = [];+ this.state = {+ id: `swarm-${Date.now()}`,+ topology: 'hierarchical-mesh',+ status: 'idle',+ agentCount: 0,+ activeAgentCount: 0,+ leaderId: undefined,+ createdAt: new Date(),+ };+ vi.clearAllMocks();+ }+}++/**+ * Mock Swarm Agent+ */+export class MockSwarmAgent {+ readonly id: string;+ readonly config: AgentConfig;+ status: 'idle' | 'busy' | 'terminated' = 'idle';+ priority: number;+ private messages: SwarmMessage[] = [];+ private taskResults: TaskResult[] = [];++ execute = vi.fn();+ receive = vi.fn();+ send = vi.fn();+ terminate = vi.fn();++ constructor(id: string, config: AgentConfig) {+ this.id = id;+ this.config = config;+ this.priority = config.priority ?? 50;++ this.execute.mockImplementation(async (task: SwarmTask) => {+ this.status = 'busy';+ await new Promise(resolve => setTimeout(resolve, 10));+ this.status = 'idle';++ const result: TaskResult = {+ taskId: task.id,+ agentId: this.id,+ success: true,+ duration: Math.random() * 100 + 10,+ };+ this.taskResults.push(result);+ return result;+ });++ this.receive.mockImplementation(async (message: SwarmMessage) => {+ this.messages.push(message);+ });++ this.send.mockImplementation(async () => {});++ this.terminate.mockImplementation(async () => {+ this.status = 'terminated';+ });+ }++ canHandle(taskType: string): boolean {+ const capabilities = agentCapabilities[this.config.type] ?? [];+ return capabilities.some(cap =>+ cap.includes(taskType) || taskType.includes(cap)+ );+ }++ getMessages(): SwarmMessage[] {+ return [...this.messages];+ }++ getTaskResults(): TaskResult[] {+ return [...this.taskResults];+ }+}++/**+ * Mock Memory Service with caching+ */+export class MockMemoryService {+ private store = new Map<string, { value: unknown; metadata: MemoryMetadata; expiresAt?: Date }>();+ private cache = new Map<string, { value: unknown; accessCount: number }>();+ private cacheHits = 0;+ private cacheMisses = 0;++ set = vi.fn(async (key: string, value: unknown, metadata?: MemoryMetadata) => {+ const expiresAt = metadata?.ttl ? new Date(Date.now() + metadata.ttl) : undefined;+ this.store.set(key, { value, metadata: metadata ?? { type: 'short-term', tags: [] }, expiresAt });+ this.cache.delete(key); // Invalidate cache+ });++ get = vi.fn(async (key: string) => {+ // Check cache first+ const cached = this.cache.get(key);+ if (cached) {+ this.cacheHits++;+ cached.accessCount++;+ return cached.value;+ }++ this.cacheMisses++;+ const entry = this.store.get(key);++ if (!entry) {+ return null;+ }++ // Check expiration+ if (entry.expiresAt && entry.expiresAt < new Date()) {+ this.store.delete(key);+ return null;+ }++ // Add to cache+ this.cache.set(key, { value: entry.value, accessCount: 1 });++ return entry.value;+ });++ delete = vi.fn(async (key: string) => {+ this.store.delete(key);+ this.cache.delete(key);+ });++ search = vi.fn(async (query: VectorSearchQuery) => {+ // Simulate vector search with filtering+ const results: SearchResult[] = [];++ for (const [key, entry] of this.store) {+ if (query.filters) {+ const matches = Object.entries(query.filters).every(([k, v]) =>+ entry.metadata[k as keyof MemoryMetadata] === v+ );+ if (!matches) continue;+ }++ results.push({+ key,+ value: entry.value,+ score: Math.random() * 0.3 + 0.7, // Random score 0.7-1.0+ metadata: entry.metadata,+ });+ }++ return results+ .filter(r => !query.threshold || r.score >= query.threshold)+ .sort((a, b) => b.score - a.score)+ .slice(0, query.topK);+ });++ clear = vi.fn(async () => {+ this.store.clear();+ this.cache.clear();+ });++ getStats = vi.fn(() => ({+ totalEntries: this.store.size,+ cacheSize: this.cache.size,+ cacheHitRate: this.cacheHits / (this.cacheHits + this.cacheMisses) || 0,+ cacheHits: this.cacheHits,+ cacheMisses: this.cacheMisses,+ }));++ prune = vi.fn(async () => {+ const now = new Date();+ let pruned = 0;++ for (const [key, entry] of this.store) {+ if (entry.expiresAt && entry.expiresAt < now) {+ this.store.delete(key);+ this.cache.delete(key);+ pruned++;+ }+ }++ return pruned;+ });++ reset(): void {+ this.store.clear();+ this.cache.clear();+ this.cacheHits = 0;+ this.cacheMisses = 0;+ vi.clearAllMocks();+ }+}++/**+ * Mock Event Bus with history tracking+ */+export class MockEventBus {+ private subscribers = new Map<string, Set<EventHandler>>();+ private history: DomainEvent[] = [];+ private maxHistorySize = 1000;++ publish = vi.fn(async (event: DomainEvent) => {+ this.history.push(event);+ if (this.history.length > this.maxHistorySize) {+ this.history.shift();+ }++ const handlers = this.subscribers.get(event.type) ?? new Set();+ const wildcardHandlers = this.subscribers.get('*') ?? new Set();++ const allHandlers = [...handlers, ...wildcardHandlers];++ await Promise.all(allHandlers.map(handler => handler(event)));+ });++ subscribe = vi.fn((eventType: string, handler: EventHandler) => {+ if (!this.subscribers.has(eventType)) {+ this.subscribers.set(eventType, new Set());+ }+ this.subscribers.get(eventType)!.add(handler);++ return () => this.unsubscribe(eventType, handler);+ });++ unsubscribe = vi.fn((eventType: string, handler: EventHandler) => {+ this.subscribers.get(eventType)?.delete(handler);+ });++ getHistory(eventType?: string): DomainEvent[] {+ if (eventType) {+ return this.history.filter(e => e.type === eventType);+ }+ return [...this.history];+ }++ getSubscriberCount(eventType: string): number {+ return this.subscribers.get(eventType)?.size ?? 0;+ }++ clear(): void {+ this.history = [];+ vi.clearAllMocks();+ }++ reset(): void {+ this.subscribers.clear();+ this.history = [];+ vi.clearAllMocks();+ }+}++/**+ * Mock Security Service+ */+export class MockSecurityService {+ private blockedPaths = ['../', '~/', '/etc/', '/tmp/', '/var/', '/root/'];+ private allowedCommands = ['npm', 'npx', 'node', 'git'];+ private tokens = new Map<string, { payload: Record<string, unknown>; expiresAt: Date }>();++ validatePath = vi.fn((path: string) => {+ return !this.blockedPaths.some(blocked => path.includes(blocked));+ });++ validateInput = vi.fn((input: string, options?: InputValidationOptions) => {+ const errors: string[] = [];++ if (options?.maxLength && input.length > options.maxLength) {+ errors.push(`Input exceeds maximum length of ${options.maxLength}`);+ }++ if (options?.allowedChars && !options.allowedChars.test(input)) {+ errors.push('Input contains disallowed characters');+ }++ return {+ valid: errors.length === 0,+ sanitized: options?.sanitize ? this.sanitize(input) : input,+ errors: errors.length > 0 ? errors : undefined,+ };+ });++ hashPassword = vi.fn(async (password: string) => {+ // Simulate argon2 hash format+ return `$argon2id$v=19$m=65536,t=3,p=4$${Buffer.from(password).toString('base64')}`;+ });++ verifyPassword = vi.fn(async (password: string, hash: string) => {+ const parts = hash.split('$');+ if (parts.length < 5) return false;+ return Buffer.from(parts[4], 'base64').toString() === password;+ });++ generateToken = vi.fn(async (payload: Record<string, unknown>, expiresIn: number = 3600000) => {+ const token = `token_${Date.now()}_${Math.random().toString(36).slice(2)}`;+ this.tokens.set(token, {+ payload,+ expiresAt: new Date(Date.now() + expiresIn),+ });+ return token;+ });++ verifyToken = vi.fn(async (token: string) => {+ const entry = this.tokens.get(token);+ if (!entry) {+ throw new Error('Invalid token');+ }+ if (entry.expiresAt < new Date()) {+ this.tokens.delete(token);+ throw new Error('Token expired');+ }+ return entry.payload;+ });++ executeSecurely = vi.fn(async (command: string, options?: ExecuteOptions) => {+ const [cmd] = command.split(' ');++ if (!this.allowedCommands.includes(cmd)) {+ throw new Error(`Command not allowed: ${cmd}`);+ }++ return {+ stdout: '',+ stderr: '',+ exitCode: 0,+ duration: Math.random() * 100,+ };+ });++ private sanitize(input: string): string {+ return input+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+ }++ reset(): void {+ this.tokens.clear();+ vi.clearAllMocks();+ }+}++// Supporting types+interface SwarmState {+ id: string;+ topology: string;+ status: string;+ agentCount: number;+ activeAgentCount: number;+ leaderId?: string;+ createdAt: Date;+}++interface SwarmInitConfig {+ topology?: string;+ maxAgents?: number;+}++interface AgentConfig {+ type: V3AgentType;+ name?: string;+ capabilities?: string[];+ priority?: number;+}++interface SwarmTask {+ id: string;+ type: string;+ payload: unknown;+ priority?: number;+ maxAgents?: number;+}++interface SwarmMessage {+ id: string;+ from: string;+ to: string;+ type: string;+ payload: unknown;+ timestamp: Date;+}++interface TaskResult {+ taskId: string;+ agentId: string;+ success: boolean;+ output?: unknown;+ error?: Error;+ duration: number;+}++interface ConsensusRequest<T> {+ topic: string;+ options: T[];+ voters?: string[];+ timeout?: number;+}++interface ConsensusResponse<T> {+ topic: string;+ decision: T | null;+ votes: Map<string, T>;+ consensus: boolean;+ votingDuration: number;+ participatingAgents: string[];+}++interface MemoryMetadata {+ type: 'short-term' | 'long-term' | 'semantic' | 'episodic';+ tags: string[];+ ttl?: number;+ [key: string]: unknown;+}++interface VectorSearchQuery {+ embedding?: number[];+ topK: number;+ threshold?: number;+ filters?: Record<string, unknown>;+}++interface SearchResult {+ key: string;+ value: unknown;+ score: number;+ metadata: MemoryMetadata;+}++interface DomainEvent {+ id: string;+ type: string;+ payload: unknown;+ timestamp: Date;+ correlationId?: string;+}++type EventHandler = (event: DomainEvent) => Promise<void>;++interface InputValidationOptions {+ maxLength?: number;+ allowedChars?: RegExp;+ sanitize?: boolean;+}++interface ExecuteOptions {+ timeout?: number;+ cwd?: string;+ shell?: boolean;+}++// Agent capabilities mapping+const agentCapabilities: Record<V3AgentType, string[]> = {+ 'queen-coordinator': ['orchestration', 'coordination', 'task-distribution'],+ 'security-architect': ['security', 'design', 'threat-modeling'],+ 'security-auditor': ['security', 'audit', 'vulnerability'],+ 'memory-specialist': ['memory', 'optimization', 'caching'],+ 'swarm-specialist': ['coordination', 'consensus', 'communication'],+ 'integration-architect': ['integration', 'api', 'compatibility'],+ 'performance-engineer': ['performance', 'optimization', 'benchmarking'],+ 'core-architect': ['architecture', 'design', 'domain'],+ 'test-architect': ['testing', 'tdd', 'quality'],+ 'project-coordinator': ['project', 'planning', 'scheduling'],+ 'coder': ['coding', 'implementation', 'debugging'],+ 'reviewer': ['review', 'quality', 'suggestions'],+ 'tester': ['testing', 'execution', 'coverage'],+ 'planner': ['planning', 'estimation', 'roadmap'],+ 'researcher': ['research', 'analysis', 'documentation'],+};++/**+ * Create all mock services as a bundle+ */+export function createMockServices(): MockServiceBundle {+ return {+ agentDB: new MockAgentDB(),+ swarmCoordinator: new MockSwarmCoordinator(),+ memoryService: new MockMemoryService(),+ eventBus: new MockEventBus(),+ securityService: new MockSecurityService(),+ };+}++/**+ * Mock service bundle interface+ */+export interface MockServiceBundle {+ agentDB: MockAgentDB;+ swarmCoordinator: MockSwarmCoordinator;+ memoryService: MockMemoryService;+ eventBus: MockEventBus;+ securityService: MockSecurityService;+}++/**+ * Reset all mock services+ */+export function resetMockServices(services: MockServiceBundle): void {+ services.agentDB.clear();+ services.swarmCoordinator.reset();+ services.memoryService.reset();+ services.eventBus.reset();+ services.securityService.reset();+}