🌊 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:
rUvc21b756b1896
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.tsindex 7317030130..487a64e6cc 100644--- a/v3/@claude-flow/cli/src/index.ts+++ b/v3/@claude-flow/cli/src/index.ts@@ -336,5 +336,17 @@ export * from './prompt.js';// Commands (internal use)export * from './commands/index.js';+// MCP Server management+export {+ MCPServerManager,+ createMCPServerManager,+ getServerManager,+ startMCPServer,+ stopMCPServer,+ getMCPServerStatus,+ type MCPServerOptions,+ type MCPServerStatus,+} from './mcp-server.js';+// Default exportexport default CLI;diff --git a/v3/@claude-flow/testing/src/fixtures/agent-fixtures.ts b/v3/@claude-flow/testing/src/fixtures/agent-fixtures.tsnew file mode 100644index 0000000000..8e6198ab84--- /dev/null+++ b/v3/@claude-flow/testing/src/fixtures/agent-fixtures.ts@@ -0,0 +1,793 @@+/**+ * @claude-flow/testing - Agent Fixtures+ *+ * Comprehensive mock agents and agent configurations for testing V3 modules.+ * Supports all 15 V3 specialized swarm agents plus core development agents.+ *+ * Based on ADR-002 (Domain-Driven Design) and V3 agent specifications.+ */+import { vi, type Mock } from 'vitest';++/**+ * Agent types for V3 15-agent swarm+ */+export type V3AgentType =+ | 'queen-coordinator'+ | 'security-architect'+ | 'security-auditor'+ | 'memory-specialist'+ | 'swarm-specialist'+ | 'integration-architect'+ | 'performance-engineer'+ | 'core-architect'+ | 'test-architect'+ | 'project-coordinator'+ | 'coder'+ | 'reviewer'+ | 'tester'+ | 'planner'+ | 'researcher';++/**+ * Agent status type+ */+export type AgentStatus = 'idle' | 'busy' | 'terminated' | 'error' | 'starting';++/**+ * Agent configuration interface+ */+export interface AgentConfig {+ type: V3AgentType;+ name: string;+ capabilities: string[];+ priority?: number;+ metadata?: Record<string, unknown>;+ systemPrompt?: string;+ tools?: string[];+ maxConcurrentTasks?: number;+ timeout?: number;+}++/**+ * Agent instance interface+ */+export interface AgentInstance {+ id: string;+ type: V3AgentType;+ name: string;+ status: AgentStatus;+ capabilities: string[];+ createdAt: Date;+ lastActiveAt?: Date;+ currentTaskId?: string;+ metrics?: AgentMetrics;+}++/**+ * Agent metrics interface+ */+export interface AgentMetrics {+ tasksCompleted: number;+ tasksFailed: number;+ avgTaskDuration: number;+ totalDuration: number;+ errorRate: number;+ memoryUsageMb: number;+}++/**+ * Agent permissions interface+ */+export interface AgentPermissions {+ canSpawnAgents: boolean;+ canTerminateAgents: boolean;+ canAccessFiles: boolean;+ canExecuteCommands: boolean;+ canAccessNetwork: boolean;+ canAccessMemory: boolean;+ maxMemoryMb?: number;+ maxCpuPercent?: number;+ allowedPaths?: string[];+ blockedPaths?: string[];+}++/**+ * Agent spawn result interface+ */+export interface AgentSpawnResult {+ agent: AgentInstance;+ sessionId: string;+ startupTime: number;+ success: boolean;+ error?: Error;+}++/**+ * Agent termination result interface+ */+export interface AgentTerminationResult {+ agentId: string;+ success: boolean;+ duration: number;+ tasksTerminated: number;+ error?: Error;+}++/**+ * Agent health check result interface+ */+export interface AgentHealthCheckResult {+ agentId: string;+ status: AgentStatus;+ healthy: boolean;+ lastActivity: Date;+ metrics: AgentMetrics;+ issues?: string[];+}++/**+ * Capability definitions for each agent type+ */+export const agentCapabilities: Record<V3AgentType, string[]> = {+ 'queen-coordinator': [+ 'orchestration',+ 'task-distribution',+ 'agent-management',+ 'priority-scheduling',+ 'conflict-resolution',+ 'github-issue-management',+ ],+ 'security-architect': [+ 'security-design',+ 'threat-modeling',+ 'security-review',+ 'architecture-security',+ 'compliance-verification',+ ],+ 'security-auditor': [+ 'cve-detection',+ 'vulnerability-scanning',+ 'security-testing',+ 'penetration-testing',+ 'audit-reporting',+ ],+ 'memory-specialist': [+ 'memory-optimization',+ 'agentdb-integration',+ 'caching',+ 'vector-search',+ 'hnsw-indexing',+ 'quantization',+ ],+ 'swarm-specialist': [+ 'coordination',+ 'consensus',+ 'communication',+ 'topology-management',+ 'load-balancing',+ ],+ 'integration-architect': [+ 'api-design',+ 'system-integration',+ 'compatibility',+ 'agentic-flow-bridge',+ 'mcp-integration',+ ],+ 'performance-engineer': [+ 'optimization',+ 'benchmarking',+ 'profiling',+ 'flash-attention',+ 'memory-reduction',+ ],+ 'core-architect': [+ 'ddd-design',+ 'architecture',+ 'domain-modeling',+ 'bounded-contexts',+ 'clean-architecture',+ ],+ 'test-architect': [+ 'tdd',+ 'test-design',+ 'quality-assurance',+ 'coverage-analysis',+ 'london-school',+ ],+ 'project-coordinator': [+ 'project-management',+ 'scheduling',+ 'reporting',+ 'cross-domain-coordination',+ 'milestone-tracking',+ ],+ 'coder': [+ 'coding',+ 'implementation',+ 'debugging',+ 'refactoring',+ 'code-generation',+ ],+ 'reviewer': [+ 'code-review',+ 'quality-check',+ 'suggestions',+ 'best-practices',+ 'security-review',+ ],+ 'tester': [+ 'testing',+ 'test-execution',+ 'coverage',+ 'regression-testing',+ 'integration-testing',+ ],+ 'planner': [+ 'planning',+ 'estimation',+ 'roadmap',+ 'task-breakdown',+ 'dependency-analysis',+ ],+ 'researcher': [+ 'research',+ 'analysis',+ 'documentation',+ 'pattern-discovery',+ 'knowledge-synthesis',+ ],+};++/**+ * Pre-defined agent configurations for testing+ */+export const agentConfigs: Record<string, AgentConfig> = {+ // V3 Specialized Agents+ queenCoordinator: {+ type: 'queen-coordinator',+ name: 'Queen Alpha',+ capabilities: agentCapabilities['queen-coordinator'],+ priority: 100,+ metadata: { isLeader: true, domain: 'orchestration' },+ maxConcurrentTasks: 10,+ timeout: 60000,+ },++ securityArchitect: {+ type: 'security-architect',+ name: 'Security Architect',+ capabilities: agentCapabilities['security-architect'],+ priority: 95,+ metadata: { specialization: 'cve-prevention', domain: 'security' },+ maxConcurrentTasks: 3,+ },++ securityAuditor: {+ type: 'security-auditor',+ name: 'Security Auditor',+ capabilities: agentCapabilities['security-auditor'],+ priority: 95,+ metadata: { specialization: 'penetration-testing', domain: 'security' },+ maxConcurrentTasks: 2,+ },++ memorySpecialist: {+ type: 'memory-specialist',+ name: 'Memory Specialist',+ capabilities: agentCapabilities['memory-specialist'],+ priority: 85,+ metadata: { backend: 'agentdb', domain: 'memory' },+ maxConcurrentTasks: 5,+ },++ swarmSpecialist: {+ type: 'swarm-specialist',+ name: 'Swarm Specialist',+ capabilities: agentCapabilities['swarm-specialist'],+ priority: 90,+ metadata: { topology: 'hierarchical-mesh', domain: 'coordination' },+ maxConcurrentTasks: 5,+ },++ integrationArchitect: {+ type: 'integration-architect',+ name: 'Integration Architect',+ capabilities: agentCapabilities['integration-architect'],+ priority: 85,+ metadata: { agentic: true, domain: 'integration' },+ },++ performanceEngineer: {+ type: 'performance-engineer',+ name: 'Performance Engineer',+ capabilities: agentCapabilities['performance-engineer'],+ priority: 80,+ metadata: { targets: { flashAttention: '2.49x-7.47x' }, domain: 'performance' },+ },++ coreArchitect: {+ type: 'core-architect',+ name: 'Core Architect',+ capabilities: agentCapabilities['core-architect'],+ priority: 85,+ metadata: { pattern: 'ddd', domain: 'core' },+ },++ testArchitect: {+ type: 'test-architect',+ name: 'Test Architect',+ capabilities: agentCapabilities['test-architect'],+ priority: 80,+ metadata: { methodology: 'london-school', domain: 'testing' },+ },++ projectCoordinator: {+ type: 'project-coordinator',+ name: 'Project Coordinator',+ capabilities: agentCapabilities['project-coordinator'],+ priority: 75,+ metadata: { domain: 'project-management' },+ },++ // Core Development Agents+ coder: {+ type: 'coder',+ name: 'Coder Agent',+ capabilities: agentCapabilities['coder'],+ priority: 70,+ },++ tester: {+ type: 'tester',+ name: 'Tester Agent',+ capabilities: agentCapabilities['tester'],+ priority: 70,+ },++ reviewer: {+ type: 'reviewer',+ name: 'Reviewer Agent',+ capabilities: agentCapabilities['reviewer'],+ priority: 75,+ },++ planner: {+ type: 'planner',+ name: 'Planner Agent',+ capabilities: agentCapabilities['planner'],+ priority: 75,+ },++ researcher: {+ type: 'researcher',+ name: 'Researcher Agent',+ capabilities: agentCapabilities['researcher'],+ priority: 65,+ },+};++/**+ * Pre-defined agent instances for testing+ */+export const agentInstances: Record<string, AgentInstance> = {+ idleQueen: {+ id: 'agent-queen-001',+ type: 'queen-coordinator',+ name: 'Queen Alpha',+ status: 'idle',+ capabilities: agentCapabilities['queen-coordinator'],+ createdAt: new Date('2024-01-01T00:00:00Z'),+ metrics: {+ tasksCompleted: 150,+ tasksFailed: 2,+ avgTaskDuration: 250,+ totalDuration: 37500,+ errorRate: 0.013,+ memoryUsageMb: 128,+ },+ },++ busySecurityArchitect: {+ id: 'agent-security-001',+ type: 'security-architect',+ name: 'Security Architect',+ status: 'busy',+ capabilities: agentCapabilities['security-architect'],+ createdAt: new Date('2024-01-01T00:00:00Z'),+ lastActiveAt: new Date('2024-01-15T12:00:00Z'),+ currentTaskId: 'task-security-audit-001',+ metrics: {+ tasksCompleted: 45,+ tasksFailed: 0,+ avgTaskDuration: 5000,+ totalDuration: 225000,+ errorRate: 0,+ memoryUsageMb: 256,+ },+ },++ idleMemorySpecialist: {+ id: 'agent-memory-001',+ type: 'memory-specialist',+ name: 'Memory Specialist',+ status: 'idle',+ capabilities: agentCapabilities['memory-specialist'],+ createdAt: new Date('2024-01-01T00:00:00Z'),+ metrics: {+ tasksCompleted: 200,+ tasksFailed: 5,+ avgTaskDuration: 100,+ totalDuration: 20000,+ errorRate: 0.025,+ memoryUsageMb: 512,+ },+ },++ terminatedCoder: {+ id: 'agent-coder-001',+ type: 'coder',+ name: 'Coder Agent',+ status: 'terminated',+ capabilities: agentCapabilities['coder'],+ createdAt: new Date('2024-01-01T00:00:00Z'),+ lastActiveAt: new Date('2024-01-10T08:00:00Z'),+ metrics: {+ tasksCompleted: 80,+ tasksFailed: 3,+ avgTaskDuration: 3000,+ totalDuration: 240000,+ errorRate: 0.036,+ memoryUsageMb: 0,+ },+ },++ errorPerformanceEngineer: {+ id: 'agent-perf-001',+ type: 'performance-engineer',+ name: 'Performance Engineer',+ status: 'error',+ capabilities: agentCapabilities['performance-engineer'],+ createdAt: new Date('2024-01-01T00:00:00Z'),+ lastActiveAt: new Date('2024-01-15T10:00:00Z'),+ currentTaskId: 'task-benchmark-001',+ metrics: {+ tasksCompleted: 30,+ tasksFailed: 5,+ avgTaskDuration: 10000,+ totalDuration: 300000,+ errorRate: 0.143,+ memoryUsageMb: 1024,+ },+ },++ startingSwarmSpecialist: {+ id: 'agent-swarm-001',+ type: 'swarm-specialist',+ name: 'Swarm Specialist',+ status: 'starting',+ capabilities: agentCapabilities['swarm-specialist'],+ createdAt: new Date(),+ },+};++/**+ * Default agent permissions for testing+ */+export const agentPermissions: Record<string, AgentPermissions> = {+ full: {+ canSpawnAgents: true,+ canTerminateAgents: true,+ canAccessFiles: true,+ canExecuteCommands: true,+ canAccessNetwork: true,+ canAccessMemory: true,+ },++ restricted: {+ canSpawnAgents: false,+ canTerminateAgents: false,+ canAccessFiles: true,+ canExecuteCommands: false,+ canAccessNetwork: false,+ canAccessMemory: true,+ allowedPaths: ['./v3/', './src/'],+ blockedPaths: ['/etc/', '/tmp/', '~/', '../'],+ },++ readOnly: {+ canSpawnAgents: false,+ canTerminateAgents: false,+ canAccessFiles: true,+ canExecuteCommands: false,+ canAccessNetwork: false,+ canAccessMemory: true,+ maxMemoryMb: 256,+ },++ coordinator: {+ canSpawnAgents: true,+ canTerminateAgents: true,+ canAccessFiles: true,+ canExecuteCommands: true,+ canAccessNetwork: true,+ canAccessMemory: true,+ maxMemoryMb: 2048,+ maxCpuPercent: 50,+ },+};++/**+ * Factory function to create agent config with overrides+ */+export function createAgentConfig(+ base: keyof typeof agentConfigs | V3AgentType,+ overrides?: Partial<AgentConfig>+): AgentConfig {+ const baseConfig = typeof base === 'string' && base in agentConfigs+ ? agentConfigs[base]+ : {+ type: base as V3AgentType,+ name: `${base} Agent`,+ capabilities: agentCapabilities[base as V3AgentType] ?? [],+ };++ return {+ ...baseConfig,+ ...overrides,+ };+}++/**+ * Factory function to create agent instance with overrides+ */+export function createAgentInstance(+ base: keyof typeof agentInstances | V3AgentType,+ overrides?: Partial<AgentInstance>+): AgentInstance {+ const baseInstance = typeof base === 'string' && base in agentInstances+ ? agentInstances[base]+ : {+ id: `agent-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ type: base as V3AgentType,+ name: `${base} Agent`,+ status: 'idle' as AgentStatus,+ capabilities: agentCapabilities[base as V3AgentType] ?? [],+ createdAt: new Date(),+ };++ return {+ ...baseInstance,+ ...overrides,+ id: overrides?.id ?? baseInstance.id ?? `agent-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ createdAt: overrides?.createdAt ?? baseInstance.createdAt ?? new Date(),+ };+}++/**+ * Factory function to create spawn result+ */+export function createAgentSpawnResult(+ agent: Partial<AgentInstance>,+ overrides?: Partial<AgentSpawnResult>+): AgentSpawnResult {+ const fullAgent = createAgentInstance(agent.type ?? 'coder', agent);++ return {+ agent: fullAgent,+ sessionId: `session-${Date.now()}`,+ startupTime: Math.random() * 100 + 50,+ success: true,+ ...overrides,+ };+}++/**+ * Factory function to create termination result+ */+export function createAgentTerminationResult(+ agentId: string,+ overrides?: Partial<AgentTerminationResult>+): AgentTerminationResult {+ return {+ agentId,+ success: true,+ duration: Math.random() * 50 + 10,+ tasksTerminated: 0,+ ...overrides,+ };+}++/**+ * Factory function to create health check result+ */+export function createAgentHealthCheckResult(+ agentId: string,+ overrides?: Partial<AgentHealthCheckResult>+): AgentHealthCheckResult {+ return {+ agentId,+ status: 'idle',+ healthy: true,+ lastActivity: new Date(),+ metrics: {+ tasksCompleted: 50,+ tasksFailed: 1,+ avgTaskDuration: 200,+ totalDuration: 10000,+ errorRate: 0.02,+ memoryUsageMb: 128,+ },+ ...overrides,+ };+}++/**+ * Create a full 15-agent V3 swarm configuration+ */+export function createV3SwarmAgentConfigs(): AgentConfig[] {+ return [+ agentConfigs.queenCoordinator,+ agentConfigs.securityArchitect,+ agentConfigs.securityAuditor,+ agentConfigs.memorySpecialist,+ agentConfigs.swarmSpecialist,+ agentConfigs.integrationArchitect,+ agentConfigs.performanceEngineer,+ agentConfigs.coreArchitect,+ agentConfigs.testArchitect,+ agentConfigs.projectCoordinator,+ agentConfigs.coder,+ agentConfigs.reviewer,+ agentConfigs.tester,+ agentConfigs.planner,+ agentConfigs.researcher,+ ];+}++/**+ * Create instances for all 15 V3 agents+ */+export function createV3SwarmAgentInstances(): AgentInstance[] {+ return createV3SwarmAgentConfigs().map((config, index) =>+ createAgentInstance(config.type, {+ id: `v3-agent-${config.type}-${index}`,+ name: config.name,+ status: 'idle',+ capabilities: config.capabilities,+ })+ );+}++/**+ * Create agents grouped by domain+ */+export function createAgentsByDomain(): Record<string, AgentConfig[]> {+ return {+ security: [agentConfigs.securityArchitect, agentConfigs.securityAuditor],+ core: [agentConfigs.coreArchitect, agentConfigs.coder, agentConfigs.reviewer],+ memory: [agentConfigs.memorySpecialist],+ coordination: [agentConfigs.queenCoordinator, agentConfigs.swarmSpecialist],+ integration: [agentConfigs.integrationArchitect],+ performance: [agentConfigs.performanceEngineer],+ testing: [agentConfigs.testArchitect, agentConfigs.tester],+ planning: [agentConfigs.projectCoordinator, agentConfigs.planner, agentConfigs.researcher],+ };+}++/**+ * Invalid agent configurations for error testing+ */+export const invalidAgentConfigs = {+ emptyName: {+ type: 'coder' as V3AgentType,+ name: '',+ capabilities: ['coding'],+ },++ noCapabilities: {+ type: 'coder' as V3AgentType,+ name: 'Invalid Agent',+ capabilities: [],+ },++ invalidType: {+ type: 'invalid-type' as V3AgentType,+ name: 'Invalid Agent',+ capabilities: ['something'],+ },++ negativePriority: {+ type: 'coder' as V3AgentType,+ name: 'Invalid Agent',+ capabilities: ['coding'],+ priority: -1,+ },++ zeroTimeout: {+ type: 'coder' as V3AgentType,+ name: 'Invalid Agent',+ capabilities: ['coding'],+ timeout: 0,+ },++ excessiveConcurrency: {+ type: 'coder' as V3AgentType,+ name: 'Invalid Agent',+ capabilities: ['coding'],+ maxConcurrentTasks: 1000,+ },+};++/**+ * Mock agent interface for behavior testing+ */+export interface MockAgent {+ id: string;+ type: V3AgentType;+ status: AgentStatus;+ capabilities: string[];+ execute: Mock<(task: unknown) => Promise<unknown>>;+ communicate: Mock<(message: unknown) => Promise<void>>;+ terminate: Mock<() => Promise<void>>;+ getMetrics: Mock<() => AgentMetrics>;+}++/**+ * Create a mock agent for testing+ */+export function createMockAgent(+ type: V3AgentType = 'coder',+ overrides?: Partial<AgentInstance>+): MockAgent {+ const instance = createAgentInstance(type, overrides);++ return {+ id: instance.id,+ type: instance.type,+ status: instance.status,+ capabilities: instance.capabilities,+ execute: vi.fn().mockResolvedValue({ success: true }),+ communicate: vi.fn().mockResolvedValue(undefined),+ terminate: vi.fn().mockResolvedValue(undefined),+ getMetrics: vi.fn().mockReturnValue(instance.metrics ?? {+ tasksCompleted: 0,+ tasksFailed: 0,+ avgTaskDuration: 0,+ totalDuration: 0,+ errorRate: 0,+ memoryUsageMb: 64,+ }),+ };+}++/**+ * Create multiple mock agents+ */+export function createMockAgents(types: V3AgentType[]): MockAgent[] {+ return types.map(type => createMockAgent(type));+}++/**+ * Create a mock V3 15-agent swarm+ */+export function createMockV3Swarm(): MockAgent[] {+ const types: V3AgentType[] = [+ 'queen-coordinator',+ 'security-architect',+ 'security-auditor',+ 'memory-specialist',+ 'swarm-specialist',+ 'integration-architect',+ 'performance-engineer',+ 'core-architect',+ 'test-architect',+ 'project-coordinator',+ 'coder',+ 'reviewer',+ 'tester',+ 'planner',+ 'researcher',+ ];++ return createMockAgents(types);+}diff --git a/v3/@claude-flow/testing/src/fixtures/memory-fixtures.ts b/v3/@claude-flow/testing/src/fixtures/memory-fixtures.tsnew file mode 100644index 0000000000..e9909e394f--- /dev/null+++ b/v3/@claude-flow/testing/src/fixtures/memory-fixtures.ts@@ -0,0 +1,750 @@+/**+ * @claude-flow/testing - Memory Fixtures+ *+ * Comprehensive mock memory entries and backend configurations for testing.+ * Supports AgentDB, HNSW indexing, vector search, and ReasoningBank patterns.+ *+ * Based on ADR-006 (Unified Memory Service) and ADR-009 (Hybrid Memory Backend).+ */+import { vi, type Mock } from 'vitest';++/**+ * Memory entry types+ */+export type MemoryType = 'short-term' | 'long-term' | 'semantic' | 'episodic' | 'procedural';++/**+ * Memory backend types+ */+export type MemoryBackendType = 'sqlite' | 'agentdb' | 'hybrid' | 'redis' | 'memory';++/**+ * Memory entry interface+ */+export interface MemoryEntry {+ key: string;+ value: unknown;+ metadata: MemoryMetadata;+ embedding?: number[];+ createdAt: Date;+ updatedAt: Date;+ expiresAt?: Date;+ accessCount?: number;+}++/**+ * Memory metadata interface+ */+export interface MemoryMetadata {+ type: MemoryType;+ tags: string[];+ source?: string;+ confidence?: number;+ ttl?: number;+ agentId?: string;+ sessionId?: string;+}++/**+ * Vector query interface+ */+export interface VectorQuery {+ embedding: number[];+ topK: number;+ threshold?: number;+ filters?: Record<string, unknown>;+ includeMetadata?: boolean;+ rerank?: boolean;+}++/**+ * Search result interface+ */+export interface SearchResult {+ key: string;+ value: unknown;+ score: number;+ metadata: MemoryMetadata;+ distance?: number;+}++/**+ * HNSW index configuration+ */+export interface HNSWConfig {+ M: number;+ efConstruction: number;+ efSearch: number;+ dimensions: number;+ metric: 'cosine' | 'euclidean' | 'dot';+}++/**+ * Quantization configuration+ */+export interface QuantizationConfig {+ enabled: boolean;+ bits: 4 | 8 | 16;+ type: 'scalar' | 'product';+ compressionRatio?: number;+}++/**+ * Memory backend configuration+ */+export interface MemoryBackendConfig {+ type: MemoryBackendType;+ path?: string;+ maxSize?: number;+ ttlMs?: number;+ vectorDimensions?: number;+ hnswConfig?: HNSWConfig;+ quantization?: QuantizationConfig;+ caching?: {+ enabled: boolean;+ maxSize: number;+ ttl: number;+ strategy: 'lru' | 'lfu' | 'arc';+ };+}++/**+ * Learned pattern interface (for ReasoningBank)+ */+export interface LearnedPattern {+ id: string;+ sessionId: string;+ task: string;+ input: string;+ output: string;+ reward: number;+ success: boolean;+ critique?: string;+ tokensUsed?: number;+ latencyMs?: number;+ createdAt: Date;+ embedding?: number[];+}++/**+ * Generate deterministic mock embedding vector+ */+export function generateMockEmbedding(dimensions: number, seed: string): number[] {+ const seedHash = hashString(seed);+ return Array.from({ length: dimensions }, (_, i) => {+ const value = Math.sin(seedHash + i * 0.1) * 0.5 + 0.5;+ return Math.round(value * 10000) / 10000;+ });+}++/**+ * Simple string hash function for deterministic embeddings+ */+function hashString(str: string): number {+ let hash = 0;+ for (let i = 0; i < str.length; i++) {+ hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;+ }+ return hash;+}++/**+ * Pre-defined memory entries for testing+ */+export const memoryEntries: Record<string, MemoryEntry> = {+ agentPattern: {+ key: 'pattern:agent:queen-coordinator',+ value: {+ pattern: 'orchestration',+ successRate: 0.95,+ avgDuration: 150,+ commonTasks: ['task-distribution', 'conflict-resolution', 'priority-scheduling'],+ },+ metadata: {+ type: 'semantic',+ tags: ['agent', 'pattern', 'queen', 'coordination'],+ source: 'learning-module',+ confidence: 0.92,+ agentId: 'queen-coordinator-001',+ },+ embedding: generateMockEmbedding(384, 'orchestration'),+ createdAt: new Date('2024-01-01T00:00:00Z'),+ updatedAt: new Date('2024-01-15T12:00:00Z'),+ accessCount: 150,+ },++ securityRule: {+ key: 'rule:security:path-traversal',+ value: {+ rule: 'block-path-traversal',+ patterns: ['../', '~/', '/etc/', '/tmp/', '/var/'],+ severity: 'critical',+ action: 'reject',+ },+ metadata: {+ type: 'long-term',+ tags: ['security', 'rule', 'validation', 'path'],+ source: 'security-module',+ confidence: 1.0,+ },+ embedding: generateMockEmbedding(384, 'security-path-traversal'),+ createdAt: new Date('2024-01-01T00:00:00Z'),+ updatedAt: new Date('2024-01-01T00:00:00Z'),+ },++ taskMemory: {+ key: 'task:memory:impl-001',+ value: {+ taskId: 'impl-001',+ context: 'implementing security module',+ decisions: ['use argon2 for hashing', 'implement path validation', 'add input sanitization'],+ progress: 0.75,+ },+ metadata: {+ type: 'episodic',+ tags: ['task', 'implementation', 'security'],+ ttl: 86400000, // 24 hours+ sessionId: 'session-001',+ },+ embedding: generateMockEmbedding(384, 'implementation-security'),+ createdAt: new Date('2024-01-15T10:00:00Z'),+ updatedAt: new Date('2024-01-15T10:00:00Z'),+ expiresAt: new Date('2024-01-16T10:00:00Z'),+ },++ sessionContext: {+ key: 'session:context:session-001',+ value: {+ sessionId: 'session-001',+ user: 'developer',+ activeAgents: ['queen-coordinator', 'coder', 'tester'],+ currentTask: 'security-implementation',+ startedAt: new Date('2024-01-15T14:00:00Z'),+ },+ metadata: {+ type: 'short-term',+ tags: ['session', 'context', 'active'],+ ttl: 3600000, // 1 hour+ },+ createdAt: new Date('2024-01-15T14:00:00Z'),+ updatedAt: new Date('2024-01-15T14:30:00Z'),+ expiresAt: new Date('2024-01-15T15:30:00Z'),+ },++ learningTrajectory: {+ key: 'learning:trajectory:traj-001',+ value: {+ trajectoryId: 'traj-001',+ steps: [+ { action: 'analyze', result: 'success', reward: 0.8, duration: 100 },+ { action: 'implement', result: 'success', reward: 0.9, duration: 500 },+ { action: 'test', result: 'success', reward: 1.0, duration: 200 },+ ],+ totalReward: 2.7,+ convergenceRate: 0.85,+ },+ metadata: {+ type: 'long-term',+ tags: ['learning', 'trajectory', 'reinforcement', 'reasoningbank'],+ source: 'reasoningbank',+ confidence: 0.88,+ },+ embedding: generateMockEmbedding(384, 'learning-trajectory'),+ createdAt: new Date('2024-01-10T00:00:00Z'),+ updatedAt: new Date('2024-01-15T00:00:00Z'),+ },++ vectorIndex: {+ key: 'index:hnsw:agents',+ value: {+ indexId: 'hnsw-agents',+ dimensions: 384,+ vectorCount: 10000,+ M: 16,+ efConstruction: 200,+ efSearch: 50,+ },+ metadata: {+ type: 'procedural',+ tags: ['index', 'hnsw', 'vector', 'search'],+ source: 'agentdb',+ },+ createdAt: new Date('2024-01-01T00:00:00Z'),+ updatedAt: new Date('2024-01-15T00:00:00Z'),+ },++ cacheEntry: {+ key: 'cache:search:security-patterns',+ value: {+ query: 'security input validation',+ results: ['pattern-001', 'pattern-002', 'pattern-003'],+ hitCount: 45,+ },+ metadata: {+ type: 'short-term',+ tags: ['cache', 'search', 'security'],+ ttl: 300000, // 5 minutes+ },+ createdAt: new Date('2024-01-15T14:00:00Z'),+ updatedAt: new Date('2024-01-15T14:00:00Z'),+ expiresAt: new Date('2024-01-15T14:05:00Z'),+ accessCount: 45,+ },+};++/**+ * Pre-defined search results for testing+ */+export const searchResults: Record<string, SearchResult[]> = {+ securityPatterns: [+ {+ key: 'pattern:security:input-validation',+ value: { pattern: 'validate all inputs', effectiveness: 0.99, applicability: 'universal' },+ score: 0.95,+ metadata: { type: 'semantic', tags: ['security', 'pattern', 'input'] },+ distance: 0.05,+ },+ {+ key: 'pattern:security:output-encoding',+ value: { pattern: 'encode all outputs', effectiveness: 0.97, applicability: 'web' },+ score: 0.88,+ metadata: { type: 'semantic', tags: ['security', 'pattern', 'output'] },+ distance: 0.12,+ },+ {+ key: 'pattern:security:least-privilege',+ value: { pattern: 'minimal permissions', effectiveness: 0.95, applicability: 'universal' },+ score: 0.82,+ metadata: { type: 'semantic', tags: ['security', 'pattern', 'permissions'] },+ distance: 0.18,+ },+ ],++ agentPatterns: [+ {+ key: 'pattern:agent:coordination',+ value: { pattern: 'hierarchical coordination', successRate: 0.92, topology: 'hierarchical-mesh' },+ score: 0.91,+ metadata: { type: 'semantic', tags: ['agent', 'pattern', 'coordination'] },+ distance: 0.09,+ },+ {+ key: 'pattern:agent:communication',+ value: { pattern: 'async messaging', successRate: 0.89, protocol: 'quic' },+ score: 0.85,+ metadata: { type: 'semantic', tags: ['agent', 'pattern', 'communication'] },+ distance: 0.15,+ },+ ],++ memoryOptimization: [+ {+ key: 'pattern:memory:hnsw-tuning',+ value: { M: 16, efConstruction: 200, speedup: '150x' },+ score: 0.94,+ metadata: { type: 'procedural', tags: ['memory', 'optimization', 'hnsw'] },+ distance: 0.06,+ },+ {+ key: 'pattern:memory:quantization',+ value: { bits: 8, compression: '4x', qualityLoss: 0.02 },+ score: 0.89,+ metadata: { type: 'procedural', tags: ['memory', 'optimization', 'quantization'] },+ distance: 0.11,+ },+ ],++ emptyResults: [],+};++/**+ * Pre-defined learned patterns for ReasoningBank testing+ */+export const learnedPatterns: Record<string, LearnedPattern> = {+ successfulImplementation: {+ id: 'pattern-impl-001',+ sessionId: 'session-001',+ task: 'Implement input validation',+ input: 'Create secure input validation for user data',+ output: 'Implemented regex-based validation with sanitization',+ reward: 0.95,+ success: true,+ critique: 'Good coverage of edge cases, could add more specific error messages',+ tokensUsed: 1500,+ latencyMs: 2500,+ createdAt: new Date('2024-01-15T10:00:00Z'),+ embedding: generateMockEmbedding(384, 'input-validation'),+ },++ failedImplementation: {+ id: 'pattern-impl-002',+ sessionId: 'session-001',+ task: 'Implement path validation',+ input: 'Create path traversal protection',+ output: 'Initial implementation had security gaps',+ reward: 0.3,+ success: false,+ critique: 'Did not handle URL-encoded path traversal attempts',+ tokensUsed: 2000,+ latencyMs: 3500,+ createdAt: new Date('2024-01-15T11:00:00Z'),+ embedding: generateMockEmbedding(384, 'path-validation-failed'),+ },++ optimizationPattern: {+ id: 'pattern-opt-001',+ sessionId: 'session-002',+ task: 'Optimize vector search',+ input: 'Improve HNSW search performance',+ output: 'Tuned M=16, efConstruction=200 for 150x speedup',+ reward: 0.98,+ success: true,+ critique: 'Excellent parameter tuning, validated with benchmarks',+ tokensUsed: 800,+ latencyMs: 1200,+ createdAt: new Date('2024-01-14T08:00:00Z'),+ embedding: generateMockEmbedding(384, 'vector-optimization'),+ },+};++/**+ * Pre-defined HNSW configurations+ */+export const hnswConfigs: Record<string, HNSWConfig> = {+ default: {+ M: 16,+ efConstruction: 200,+ efSearch: 50,+ dimensions: 384,+ metric: 'cosine',+ },++ highPerformance: {+ M: 32,+ efConstruction: 400,+ efSearch: 100,+ dimensions: 384,+ metric: 'cosine',+ },++ lowMemory: {+ M: 8,+ efConstruction: 100,+ efSearch: 25,+ dimensions: 384,+ metric: 'dot',+ },++ highDimension: {+ M: 24,+ efConstruction: 300,+ efSearch: 75,+ dimensions: 1536,+ metric: 'euclidean',+ },+};++/**+ * Pre-defined quantization configurations+ */+export const quantizationConfigs: Record<string, QuantizationConfig> = {+ scalar4bit: {+ enabled: true,+ bits: 4,+ type: 'scalar',+ compressionRatio: 8,+ },++ scalar8bit: {+ enabled: true,+ bits: 8,+ type: 'scalar',+ compressionRatio: 4,+ },++ product: {+ enabled: true,+ bits: 8,+ type: 'product',+ compressionRatio: 32,+ },++ disabled: {+ enabled: false,+ bits: 16,+ type: 'scalar',+ },+};++/**+ * Pre-defined memory backend configurations+ */+export const memoryBackendConfigs: Record<string, MemoryBackendConfig> = {+ agentDB: {+ type: 'agentdb',+ vectorDimensions: 384,+ hnswConfig: hnswConfigs.default,+ quantization: quantizationConfigs.scalar8bit,+ caching: {+ enabled: true,+ maxSize: 1000,+ ttl: 3600000,+ strategy: 'lru',+ },+ },++ hybrid: {+ type: 'hybrid',+ path: './data',+ vectorDimensions: 384,+ hnswConfig: hnswConfigs.highPerformance,+ quantization: quantizationConfigs.scalar4bit,+ caching: {+ enabled: true,+ maxSize: 5000,+ ttl: 7200000,+ strategy: 'arc',+ },+ },++ inMemory: {+ type: 'memory',+ maxSize: 10000,+ vectorDimensions: 384,+ hnswConfig: hnswConfigs.lowMemory,+ caching: {+ enabled: false,+ maxSize: 0,+ ttl: 0,+ strategy: 'lru',+ },+ },++ sqlite: {+ type: 'sqlite',+ path: './test.db',+ maxSize: 100000,+ caching: {+ enabled: true,+ maxSize: 2000,+ ttl: 1800000,+ strategy: 'lfu',+ },+ },+};++/**+ * Performance targets from V3 specifications+ */+export const performanceTargets = {+ searchSpeedupMin: 150,+ searchSpeedupMax: 12500,+ memoryReduction: 0.50,+ insertionTime: 1, // ms+ searchTime: 0.1, // ms for 1M vectors+ flashAttentionSpeedup: [2.49, 7.47],+};++/**+ * Factory function to create memory entry with overrides+ */+export function createMemoryEntry(+ base: keyof typeof memoryEntries,+ overrides?: Partial<MemoryEntry>+): MemoryEntry {+ return {+ ...memoryEntries[base],+ ...overrides,+ key: overrides?.key ?? memoryEntries[base].key,+ createdAt: overrides?.createdAt ?? new Date(),+ updatedAt: overrides?.updatedAt ?? new Date(),+ };+}++/**+ * Factory function to create vector query+ */+export function createVectorQuery(overrides?: Partial<VectorQuery>): VectorQuery {+ return {+ embedding: overrides?.embedding ?? generateMockEmbedding(384, 'query'),+ topK: overrides?.topK ?? 10,+ threshold: overrides?.threshold ?? 0.7,+ filters: overrides?.filters,+ includeMetadata: overrides?.includeMetadata ?? true,+ rerank: overrides?.rerank ?? false,+ };+}++/**+ * Factory function to create learned pattern+ */+export function createLearnedPattern(+ base: keyof typeof learnedPatterns,+ overrides?: Partial<LearnedPattern>+): LearnedPattern {+ return {+ ...learnedPatterns[base],+ ...overrides,+ id: overrides?.id ?? `pattern-${Date.now()}`,+ createdAt: overrides?.createdAt ?? new Date(),+ };+}++/**+ * Factory function to create HNSW config+ */+export function createHNSWConfig(+ base: keyof typeof hnswConfigs = 'default',+ overrides?: Partial<HNSWConfig>+): HNSWConfig {+ return {+ ...hnswConfigs[base],+ ...overrides,+ };+}++/**+ * Factory function to create memory backend config+ */+export function createMemoryBackendConfig(+ base: keyof typeof memoryBackendConfigs = 'agentDB',+ overrides?: Partial<MemoryBackendConfig>+): MemoryBackendConfig {+ return {+ ...memoryBackendConfigs[base],+ ...overrides,+ };+}++/**+ * Create batch of memory entries for performance testing+ */+export function createMemoryBatch(+ count: number,+ type: MemoryType = 'semantic',+ dimensions: number = 384+): MemoryEntry[] {+ return Array.from({ length: count }, (_, i) => ({+ key: `batch:entry:${i}`,+ value: { index: i, data: `test data ${i}` },+ metadata: {+ type,+ tags: ['batch', `entry-${i % 10}`],+ },+ embedding: generateMockEmbedding(dimensions, `batch-${i}`),+ createdAt: new Date(),+ updatedAt: new Date(),+ }));+}++/**+ * Create embeddings batch for vector index testing+ */+export function createEmbeddingsBatch(+ count: number,+ dimensions: number = 384+): { id: string; embedding: number[] }[] {+ return Array.from({ length: count }, (_, i) => ({+ id: `embedding-${i}`,+ embedding: generateMockEmbedding(dimensions, `embedding-${i}`),+ }));+}++/**+ * Invalid memory entries for error testing+ */+export const invalidMemoryEntries = {+ emptyKey: {+ key: '',+ value: { data: 'test' },+ metadata: { type: 'short-term' as const, tags: [] },+ createdAt: new Date(),+ updatedAt: new Date(),+ },++ nullValue: {+ key: 'valid-key',+ value: null,+ metadata: { type: 'short-term' as const, tags: [] },+ createdAt: new Date(),+ updatedAt: new Date(),+ },++ invalidEmbeddingDimension: {+ key: 'valid-key',+ value: { data: 'test' },+ metadata: { type: 'semantic' as const, tags: [] },+ embedding: [0.1, 0.2], // Wrong dimension+ createdAt: new Date(),+ updatedAt: new Date(),+ },++ expiredEntry: {+ key: 'expired-key',+ value: { data: 'expired' },+ metadata: { type: 'short-term' as const, tags: [], ttl: -1000 },+ createdAt: new Date('2024-01-01T00:00:00Z'),+ updatedAt: new Date('2024-01-01T00:00:00Z'),+ expiresAt: new Date('2024-01-01T00:01:00Z'),+ },++ invalidTags: {+ key: 'invalid-tags',+ value: { data: 'test' },+ metadata: { type: 'short-term' as const, tags: null as unknown as string[] },+ createdAt: new Date(),+ updatedAt: new Date(),+ },+};++/**+ * Mock memory service interface+ */+export interface MockMemoryService {+ store: Mock<(key: string, value: unknown, metadata?: MemoryMetadata) => Promise<void>>;+ retrieve: Mock<(key: string) => Promise<unknown>>;+ search: Mock<(query: VectorQuery) => Promise<SearchResult[]>>;+ delete: Mock<(key: string) => Promise<void>>;+ clear: Mock<() => Promise<void>>;+ getStats: Mock<() => Promise<{ totalEntries: number; sizeBytes: number }>>;+}++/**+ * Create a mock memory service+ */+export function createMockMemoryService(): MockMemoryService {+ return {+ store: vi.fn().mockResolvedValue(undefined),+ retrieve: vi.fn().mockResolvedValue(null),+ search: vi.fn().mockResolvedValue([]),+ delete: vi.fn().mockResolvedValue(undefined),+ clear: vi.fn().mockResolvedValue(undefined),+ getStats: vi.fn().mockResolvedValue({ totalEntries: 0, sizeBytes: 0 }),+ };+}++/**+ * Mock AgentDB interface+ */+export interface MockAgentDB {+ insert: Mock<(id: string, embedding: number[], metadata?: unknown) => Promise<void>>;+ search: Mock<(embedding: number[], k: number) => Promise<SearchResult[]>>;+ delete: Mock<(id: string) => Promise<void>>;+ update: Mock<(id: string, embedding: number[], metadata?: unknown) => Promise<void>>;+ getStats: Mock<() => Promise<{ vectorCount: number; indexSize: number }>>;+ rebuildIndex: Mock<() => Promise<void>>;+}++/**+ * Create a mock AgentDB instance+ */+export function createMockAgentDB(): MockAgentDB {+ return {+ insert: vi.fn().mockResolvedValue(undefined),+ search: vi.fn().mockResolvedValue([]),+ delete: vi.fn().mockResolvedValue(undefined),+ update: vi.fn().mockResolvedValue(undefined),+ getStats: vi.fn().mockResolvedValue({ vectorCount: 0, indexSize: 0 }),+ rebuildIndex: vi.fn().mockResolvedValue(undefined),+ };+}diff --git a/v3/@claude-flow/testing/src/fixtures/swarm-fixtures.ts b/v3/@claude-flow/testing/src/fixtures/swarm-fixtures.tsnew file mode 100644index 0000000000..e4c3d357e9--- /dev/null+++ b/v3/@claude-flow/testing/src/fixtures/swarm-fixtures.ts@@ -0,0 +1,836 @@+/**+ * @claude-flow/testing - Swarm Fixtures+ *+ * Comprehensive mock swarm configurations, topologies, and coordination fixtures.+ * Supports hierarchical-mesh, adaptive, and all consensus protocols.+ *+ * Based on ADR-003 (Single Coordination Engine) and V3 swarm specifications.+ */+import { vi, type Mock } from 'vitest';+import type { V3AgentType, AgentInstance, MockAgent, createMockAgent } from './agent-fixtures.js';++/**+ * Swarm topology types+ */+export type SwarmTopology =+ | 'hierarchical'+ | 'mesh'+ | 'ring'+ | 'star'+ | 'adaptive'+ | 'hierarchical-mesh';++/**+ * Consensus protocol types+ */+export type ConsensusProtocol = 'raft' | 'pbft' | 'gossip' | 'crdt' | 'byzantine';++/**+ * Coordination status types+ */+export type CoordinationStatus =+ | 'initializing'+ | 'active'+ | 'coordinating'+ | 'consensus'+ | 'error'+ | 'shutdown';++/**+ * Swarm configuration interface+ */+export interface SwarmConfig {+ topology: SwarmTopology;+ maxAgents: number;+ name?: string;+ description?: string;+ coordination: CoordinationConfig;+ communication: CommunicationConfig;+ autoScale?: AutoScaleConfig;+ healthCheck?: HealthCheckConfig;+}++/**+ * Coordination configuration+ */+export interface CoordinationConfig {+ consensusProtocol: ConsensusProtocol;+ heartbeatInterval: number;+ electionTimeout: number;+ consensusRequired?: boolean;+ timeoutMs?: number;+ retryPolicy?: {+ maxRetries: number;+ backoffMs: number;+ };+}++/**+ * Communication configuration+ */+export interface CommunicationConfig {+ protocol: 'quic' | 'tcp' | 'websocket' | 'ipc';+ maxMessageSize: number;+ retryAttempts: number;+ compressionEnabled?: boolean;+ encryptionEnabled?: boolean;+}++/**+ * Auto-scale configuration+ */+export interface AutoScaleConfig {+ enabled: boolean;+ minAgents: number;+ maxAgents: number;+ scaleUpThreshold: number;+ scaleDownThreshold: number;+ cooldownMs?: number;+}++/**+ * Health check configuration+ */+export interface HealthCheckConfig {+ enabled: boolean;+ interval: number;+ timeout: number;+ unhealthyThreshold: number;+ healthyThreshold: number;+}++/**+ * Swarm state interface+ */+export interface SwarmState {+ id: string;+ topology: SwarmTopology;+ status: CoordinationStatus;+ agentCount: number;+ activeAgentCount: number;+ leaderId?: string;+ createdAt: Date;+ lastHeartbeat?: Date;+}++/**+ * Swarm message interface+ */+export interface SwarmMessage<T = unknown> {+ id: string;+ from: string;+ to: string | 'broadcast';+ type: 'task' | 'result' | 'status' | 'coordination' | 'heartbeat' | 'election';+ payload: T;+ timestamp: Date;+ correlationId?: string;+ replyTo?: string;+ ttl?: number;+ priority?: number;+}++/**+ * Swarm task interface+ */+export interface SwarmTask {+ id: string;+ name: string;+ type: string;+ payload: unknown;+ priority: number;+ assignedTo?: string;+ status: 'pending' | 'assigned' | 'running' | 'completed' | 'failed' | 'cancelled';+ dependencies?: string[];+ deadline?: Date;+ createdAt: Date;+ startedAt?: Date;+ completedAt?: Date;+}++/**+ * Swarm task result interface+ */+export interface SwarmTaskResult {+ taskId: string;+ agentId: string;+ success: boolean;+ output?: unknown;+ error?: Error;+ duration: number;+ metrics?: TaskMetrics;+}++/**+ * Task metrics interface+ */+export interface TaskMetrics {+ cpuTime: number;+ memoryUsage: number;+ ioOperations: number;+ networkCalls: number;+}++/**+ * Coordination result interface+ */+export interface CoordinationResult {+ success: boolean;+ completedTasks: number;+ failedTasks: number;+ totalDuration: number;+ agentMetrics: Map<string, AgentCoordinationMetrics>;+ consensusRounds?: number;+}++/**+ * Agent coordination metrics+ */+export interface AgentCoordinationMetrics {+ tasksCompleted: number;+ tasksFailed: number;+ averageTaskDuration: number;+ messagesProcessed: number;+ totalDuration: number;+}++/**+ * Consensus request interface+ */+export interface ConsensusRequest<T = unknown> {+ topic: string;+ options: T[];+ requiredVotes: number | 'majority' | 'all';+ timeout: number;+ voters?: string[];+}++/**+ * Consensus response interface+ */+export interface ConsensusResponse<T = unknown> {+ topic: string;+ decision: T | null;+ votes: Map<string, T>;+ consensus: boolean;+ votingDuration: number;+ participatingAgents: string[];+}++/**+ * Pre-defined swarm configurations for testing+ */+export const swarmConfigs: Record<string, SwarmConfig> = {+ v3Default: {+ topology: 'hierarchical-mesh',+ maxAgents: 15,+ name: 'V3 Default Swarm',+ description: 'Standard V3 15-agent hierarchical-mesh swarm',+ coordination: {+ consensusProtocol: 'raft',+ heartbeatInterval: 1000,+ electionTimeout: 5000,+ consensusRequired: true,+ timeoutMs: 8000,+ retryPolicy: { maxRetries: 3, backoffMs: 1000 },+ },+ communication: {+ protocol: 'quic',+ maxMessageSize: 1048576, // 1MB+ retryAttempts: 3,+ compressionEnabled: true,+ encryptionEnabled: true,+ },+ autoScale: {+ enabled: true,+ minAgents: 5,+ maxAgents: 15,+ scaleUpThreshold: 0.8,+ scaleDownThreshold: 0.3,+ cooldownMs: 30000,+ },+ healthCheck: {+ enabled: true,+ interval: 5000,+ timeout: 2000,+ unhealthyThreshold: 3,+ healthyThreshold: 2,+ },+ },++ minimal: {+ topology: 'mesh',+ maxAgents: 5,+ name: 'Minimal Swarm',+ description: 'Lightweight swarm for testing',+ coordination: {+ consensusProtocol: 'gossip',+ heartbeatInterval: 2000,+ electionTimeout: 10000,+ consensusRequired: false,+ timeoutMs: 5000,+ retryPolicy: { maxRetries: 5, backoffMs: 500 },+ },+ communication: {+ protocol: 'tcp',+ maxMessageSize: 65536, // 64KB+ retryAttempts: 5,+ },+ },++ highPerformance: {+ topology: 'adaptive',+ maxAgents: 50,+ name: 'High Performance Swarm',+ description: 'Optimized for maximum throughput',+ coordination: {+ consensusProtocol: 'pbft',+ heartbeatInterval: 500,+ electionTimeout: 3000,+ consensusRequired: true,+ timeoutMs: 5000,+ retryPolicy: { maxRetries: 2, backoffMs: 250 },+ },+ communication: {+ protocol: 'quic',+ maxMessageSize: 4194304, // 4MB+ retryAttempts: 2,+ compressionEnabled: true,+ encryptionEnabled: true,+ },+ autoScale: {+ enabled: true,+ minAgents: 10,+ maxAgents: 50,+ scaleUpThreshold: 0.7,+ scaleDownThreshold: 0.2,+ cooldownMs: 15000,+ },+ },++ byzantineFault: {+ topology: 'mesh',+ maxAgents: 7,+ name: 'Byzantine Fault Tolerant Swarm',+ description: 'Tolerant to malicious actors',+ coordination: {+ consensusProtocol: 'byzantine',+ heartbeatInterval: 1000,+ electionTimeout: 10000,+ consensusRequired: true,+ timeoutMs: 15000,+ retryPolicy: { maxRetries: 5, backoffMs: 2000 },+ },+ communication: {+ protocol: 'tcp',+ maxMessageSize: 1048576,+ retryAttempts: 3,+ encryptionEnabled: true,+ },+ },++ hierarchicalOnly: {+ topology: 'hierarchical',+ maxAgents: 20,+ name: 'Hierarchical Swarm',+ description: 'Pure hierarchical coordination',+ coordination: {+ consensusProtocol: 'raft',+ heartbeatInterval: 1000,+ electionTimeout: 5000,+ consensusRequired: false,+ timeoutMs: 5000,+ retryPolicy: { maxRetries: 3, backoffMs: 1000 },+ },+ communication: {+ protocol: 'websocket',+ maxMessageSize: 524288, // 512KB+ retryAttempts: 3,+ },+ },++ ringTopology: {+ topology: 'ring',+ maxAgents: 10,+ name: 'Ring Topology Swarm',+ description: 'Token-passing ring coordination',+ coordination: {+ consensusProtocol: 'gossip',+ heartbeatInterval: 1500,+ electionTimeout: 8000,+ consensusRequired: true,+ timeoutMs: 8000,+ retryPolicy: { maxRetries: 4, backoffMs: 750 },+ },+ communication: {+ protocol: 'tcp',+ maxMessageSize: 262144, // 256KB+ retryAttempts: 4,+ },+ },+};++/**+ * Pre-defined swarm states for testing+ */+export const swarmStates: Record<string, SwarmState> = {+ active: {+ id: 'swarm-001',+ topology: 'hierarchical-mesh',+ status: 'active',+ agentCount: 15,+ activeAgentCount: 15,+ leaderId: 'agent-queen-001',+ createdAt: new Date('2024-01-01T00:00:00Z'),+ lastHeartbeat: new Date(),+ },++ initializing: {+ id: 'swarm-002',+ topology: 'mesh',+ status: 'initializing',+ agentCount: 5,+ activeAgentCount: 3,+ createdAt: new Date(),+ },++ coordinating: {+ id: 'swarm-003',+ topology: 'adaptive',+ status: 'coordinating',+ agentCount: 10,+ activeAgentCount: 10,+ leaderId: 'agent-coordinator-001',+ createdAt: new Date('2024-01-10T00:00:00Z'),+ lastHeartbeat: new Date(),+ },++ consensus: {+ id: 'swarm-004',+ topology: 'hierarchical-mesh',+ status: 'consensus',+ agentCount: 15,+ activeAgentCount: 14,+ leaderId: 'agent-queen-001',+ createdAt: new Date('2024-01-05T00:00:00Z'),+ lastHeartbeat: new Date(),+ },++ error: {+ id: 'swarm-005',+ topology: 'mesh',+ status: 'error',+ agentCount: 8,+ activeAgentCount: 3,+ createdAt: new Date('2024-01-01T00:00:00Z'),+ lastHeartbeat: new Date(Date.now() - 60000), // 1 minute ago+ },++ shutdown: {+ id: 'swarm-006',+ topology: 'hierarchical',+ status: 'shutdown',+ agentCount: 10,+ activeAgentCount: 0,+ createdAt: new Date('2024-01-01T00:00:00Z'),+ },+};++/**+ * Pre-defined swarm tasks for testing+ */+export const swarmTasks: Record<string, SwarmTask> = {+ securityScan: {+ id: 'task-security-001',+ name: 'Security Scan',+ type: 'security',+ payload: { target: './src', scanType: 'full', severity: 'high' },+ priority: 100,+ status: 'pending',+ createdAt: new Date(),+ },++ codeReview: {+ id: 'task-review-001',+ name: 'Code Review',+ type: 'review',+ payload: { files: ['src/main.ts'], rules: ['security', 'performance'] },+ priority: 80,+ status: 'assigned',+ assignedTo: 'agent-reviewer-001',+ createdAt: new Date(),+ },++ implementation: {+ id: 'task-impl-001',+ name: 'Feature Implementation',+ type: 'coding',+ payload: { feature: 'path-validation', module: 'security' },+ priority: 70,+ status: 'running',+ assignedTo: 'agent-coder-001',+ createdAt: new Date(Date.now() - 60000),+ startedAt: new Date(Date.now() - 30000),+ },++ testing: {+ id: 'task-test-001',+ name: 'Unit Testing',+ type: 'testing',+ payload: { framework: 'vitest', coverage: 0.90 },+ priority: 75,+ status: 'completed',+ assignedTo: 'agent-tester-001',+ createdAt: new Date(Date.now() - 120000),+ startedAt: new Date(Date.now() - 90000),+ completedAt: new Date(Date.now() - 30000),+ },++ orchestration: {+ id: 'task-orch-001',+ name: 'Task Orchestration',+ type: 'coordination',+ payload: { subtasks: ['task-impl-001', 'task-test-001'], parallel: true },+ priority: 90,+ status: 'running',+ assignedTo: 'agent-queen-001',+ dependencies: ['task-security-001'],+ createdAt: new Date(Date.now() - 180000),+ startedAt: new Date(Date.now() - 120000),+ },+};++/**+ * Pre-defined swarm messages for testing+ */+export const swarmMessages: Record<string, SwarmMessage> = {+ taskAssignment: {+ id: 'msg-001',+ from: 'agent-queen-001',+ to: 'agent-coder-001',+ type: 'task',+ payload: swarmTasks.implementation,+ timestamp: new Date(),+ correlationId: 'corr-001',+ priority: 70,+ },++ taskResult: {+ id: 'msg-002',+ from: 'agent-coder-001',+ to: 'agent-queen-001',+ type: 'result',+ payload: { taskId: 'task-impl-001', success: true, duration: 5000 },+ timestamp: new Date(),+ correlationId: 'corr-001',+ replyTo: 'msg-001',+ },++ heartbeat: {+ id: 'msg-003',+ from: 'agent-queen-001',+ to: 'broadcast',+ type: 'heartbeat',+ payload: { status: 'active', load: 0.6, taskCount: 5 },+ timestamp: new Date(),+ ttl: 5000,+ },++ election: {+ id: 'msg-004',+ from: 'agent-swarm-001',+ to: 'broadcast',+ type: 'election',+ payload: { term: 5, candidateId: 'agent-swarm-001', lastLogIndex: 100 },+ timestamp: new Date(),+ priority: 100,+ },++ coordination: {+ id: 'msg-005',+ from: 'agent-queen-001',+ to: 'agent-swarm-001',+ type: 'coordination',+ payload: { action: 'scale-up', targetAgents: 3 },+ timestamp: new Date(),+ correlationId: 'corr-002',+ },++ statusUpdate: {+ id: 'msg-006',+ from: 'agent-memory-001',+ to: 'agent-queen-001',+ type: 'status',+ payload: { status: 'busy', currentTask: 'indexing', progress: 0.75 },+ timestamp: new Date(),+ },+};++/**+ * Pre-defined coordination results for testing+ */+export const coordinationResults: Record<string, CoordinationResult> = {+ successful: {+ success: true,+ completedTasks: 10,+ failedTasks: 0,+ totalDuration: 15000,+ agentMetrics: new Map([+ ['agent-queen-001', { tasksCompleted: 3, tasksFailed: 0, averageTaskDuration: 200, messagesProcessed: 50, totalDuration: 600 }],+ ['agent-coder-001', { tasksCompleted: 4, tasksFailed: 0, averageTaskDuration: 2000, messagesProcessed: 20, totalDuration: 8000 }],+ ['agent-tester-001', { tasksCompleted: 3, tasksFailed: 0, averageTaskDuration: 1500, messagesProcessed: 15, totalDuration: 4500 }],+ ]),+ consensusRounds: 2,+ },++ partialFailure: {+ success: true,+ completedTasks: 8,+ failedTasks: 2,+ totalDuration: 20000,+ agentMetrics: new Map([+ ['agent-queen-001', { tasksCompleted: 2, tasksFailed: 0, averageTaskDuration: 250, messagesProcessed: 40, totalDuration: 500 }],+ ['agent-coder-001', { tasksCompleted: 4, tasksFailed: 1, averageTaskDuration: 2500, messagesProcessed: 25, totalDuration: 10000 }],+ ['agent-tester-001', { tasksCompleted: 2, tasksFailed: 1, averageTaskDuration: 2000, messagesProcessed: 18, totalDuration: 4000 }],+ ]),+ consensusRounds: 3,+ },++ failed: {+ success: false,+ completedTasks: 2,+ failedTasks: 8,+ totalDuration: 30000,+ agentMetrics: new Map([+ ['agent-queen-001', { tasksCompleted: 1, tasksFailed: 2, averageTaskDuration: 500, messagesProcessed: 60, totalDuration: 500 }],+ ['agent-coder-001', { tasksCompleted: 1, tasksFailed: 3, averageTaskDuration: 5000, messagesProcessed: 30, totalDuration: 5000 }],+ ]),+ consensusRounds: 5,+ },+};++/**+ * Factory function to create swarm config with overrides+ */+export function createSwarmConfig(+ base: keyof typeof swarmConfigs = 'v3Default',+ overrides?: Partial<SwarmConfig>+): SwarmConfig {+ return mergeDeep(swarmConfigs[base], overrides ?? {}) as SwarmConfig;+}++/**+ * Factory function to create swarm state with overrides+ */+export function createSwarmState(+ base: keyof typeof swarmStates = 'active',+ overrides?: Partial<SwarmState>+): SwarmState {+ return {+ ...swarmStates[base],+ ...overrides,+ id: overrides?.id ?? swarmStates[base].id,+ createdAt: overrides?.createdAt ?? swarmStates[base].createdAt,+ };+}++/**+ * Factory function to create swarm task with overrides+ */+export function createSwarmTask(+ base: keyof typeof swarmTasks = 'implementation',+ overrides?: Partial<SwarmTask>+): SwarmTask {+ return {+ ...swarmTasks[base],+ ...overrides,+ id: overrides?.id ?? `task-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ createdAt: overrides?.createdAt ?? new Date(),+ };+}++/**+ * Factory function to create swarm message with overrides+ */+export function createSwarmMessage<T = unknown>(+ type: SwarmMessage['type'],+ payload: T,+ overrides?: Partial<SwarmMessage<T>>+): SwarmMessage<T> {+ return {+ id: `msg-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ from: 'agent-sender',+ to: 'agent-receiver',+ type,+ payload,+ timestamp: new Date(),+ ...overrides,+ };+}++/**+ * Factory function to create consensus request+ */+export function createConsensusRequest<T>(+ topic: string,+ options: T[],+ overrides?: Partial<ConsensusRequest<T>>+): ConsensusRequest<T> {+ return {+ topic,+ options,+ requiredVotes: 'majority',+ timeout: 5000,+ ...overrides,+ };+}++/**+ * Factory function to create coordination result+ */+export function createCoordinationResult(+ base: keyof typeof coordinationResults = 'successful',+ overrides?: Partial<CoordinationResult>+): CoordinationResult {+ return {+ ...coordinationResults[base],+ ...overrides,+ };+}++/**+ * Create a batch of swarm tasks for testing+ */+export function createSwarmTaskBatch(+ count: number,+ type: string = 'coding'+): SwarmTask[] {+ return Array.from({ length: count }, (_, i) => ({+ id: `batch-task-${i}`,+ name: `Batch Task ${i + 1}`,+ type,+ payload: { index: i },+ priority: Math.floor(Math.random() * 100),+ status: 'pending' as const,+ createdAt: new Date(),+ }));+}++/**+ * Deep merge utility+ */+function mergeDeep(+ target: Record<string, unknown>,+ source: Record<string, unknown>+): Record<string, unknown> {+ const output = { ...target };++ for (const key of Object.keys(source)) {+ if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {+ output[key] = mergeDeep(+ (target[key] as Record<string, unknown>) ?? {},+ source[key] as Record<string, unknown>+ );+ } else {+ output[key] = source[key];+ }+ }++ return output;+}++/**+ * Invalid swarm configurations for error testing+ */+export const invalidSwarmConfigs = {+ zeroAgents: createSwarmConfig('v3Default', { maxAgents: 0 }),++ negativeHeartbeat: createSwarmConfig('v3Default', {+ coordination: {+ consensusProtocol: 'raft',+ heartbeatInterval: -100,+ electionTimeout: 5000,+ },+ }),++ invalidTopology: {+ ...swarmConfigs.v3Default,+ topology: 'invalid-topology' as SwarmTopology,+ },++ invalidProtocol: createSwarmConfig('v3Default', {+ coordination: {+ consensusProtocol: 'invalid-protocol' as ConsensusProtocol,+ heartbeatInterval: 1000,+ electionTimeout: 5000,+ },+ }),++ zeroMessageSize: createSwarmConfig('v3Default', {+ communication: {+ protocol: 'quic',+ maxMessageSize: 0,+ retryAttempts: 3,+ },+ }),+};++/**+ * Mock swarm coordinator interface+ */+export interface MockSwarmCoordinator {+ initialize: Mock<(config: SwarmConfig) => Promise<SwarmState>>;+ coordinate: Mock<(agents: string[], task: SwarmTask) => Promise<CoordinationResult>>;+ shutdown: Mock<(graceful?: boolean) => Promise<void>>;+ addAgent: Mock<(agentId: string) => Promise<void>>;+ removeAgent: Mock<(agentId: string) => Promise<void>>;+ getState: Mock<() => SwarmState>;+ broadcast: Mock<(message: SwarmMessage) => Promise<void>>;+ requestConsensus: Mock<<T>(request: ConsensusRequest<T>) => Promise<ConsensusResponse<T>>>;+}++/**+ * Create a mock swarm coordinator+ */+export function createMockSwarmCoordinator(): MockSwarmCoordinator {+ return {+ initialize: vi.fn().mockResolvedValue(swarmStates.active),+ coordinate: vi.fn().mockResolvedValue(coordinationResults.successful),+ shutdown: vi.fn().mockResolvedValue(undefined),+ addAgent: vi.fn().mockResolvedValue(undefined),+ removeAgent: vi.fn().mockResolvedValue(undefined),+ getState: vi.fn().mockReturnValue(swarmStates.active),+ broadcast: vi.fn().mockResolvedValue(undefined),+ requestConsensus: vi.fn().mockResolvedValue({+ topic: 'test',+ decision: 'option-1',+ votes: new Map(),+ consensus: true,+ votingDuration: 100,+ participatingAgents: [],+ }),+ };+}++/**+ * Mock message bus interface+ */+export interface MockMessageBus {+ publish: Mock<(message: SwarmMessage) => Promise<void>>;+ subscribe: Mock<(pattern: string, handler: (message: SwarmMessage) => void) => () => void>;+ unsubscribe: Mock<(pattern: string) => void>;+ request: Mock<(message: SwarmMessage, timeout?: number) => Promise<SwarmMessage>>;+ getStats: Mock<() => { messagesSent: number; messagesReceived: number }>;+}++/**+ * Create a mock message bus+ */+export function createMockMessageBus(): MockMessageBus {+ return {+ publish: vi.fn().mockResolvedValue(undefined),+ subscribe: vi.fn().mockReturnValue(() => {}),+ unsubscribe: vi.fn(),+ request: vi.fn().mockResolvedValue(swarmMessages.taskResult),+ getStats: vi.fn().mockReturnValue({ messagesSent: 0, messagesReceived: 0 }),+ };+}diff --git a/v3/scripts/start-mcp.cmd b/v3/scripts/start-mcp.cmdnew file mode 100644index 0000000000..6e67ad70dc--- /dev/null+++ b/v3/scripts/start-mcp.cmd@@ -0,0 +1,141 @@+@echo off+REM Claude-Flow MCP Server V3 Startup Script (Windows)+REM+REM Usage:+REM start-mcp.cmd [options]+REM+REM Options:+REM --transport <type> Transport: stdio, http, websocket (default: stdio)+REM --host <host> Server host (default: localhost)+REM --port <port> Server port (default: 3000)+REM --log-level <level> Log level: debug, info, warn, error (default: info)+REM --help Show help++setlocal EnableDelayedExpansion++REM Script directory+set "SCRIPT_DIR=%~dp0"+set "V3_DIR=%SCRIPT_DIR%.."+set "PROJECT_ROOT=%V3_DIR%\.."++REM Default configuration+set "TRANSPORT=stdio"+set "HOST=localhost"+set "PORT=3000"+set "LOG_LEVEL=info"++REM PID file location+set "PID_FILE=%TEMP%\claude-flow-mcp.pid"+set "LOG_FILE=%TEMP%\claude-flow-mcp.log"++REM Override from environment variables+if defined MCP_TRANSPORT set "TRANSPORT=%MCP_TRANSPORT%"+if defined MCP_HOST set "HOST=%MCP_HOST%"+if defined MCP_PORT set "PORT=%MCP_PORT%"+if defined MCP_LOG_LEVEL set "LOG_LEVEL=%MCP_LOG_LEVEL%"++REM Parse arguments+:parse_args+if "%~1"=="" goto :start_server+if "%~1"=="--transport" (+ set "TRANSPORT=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="-t" (+ set "TRANSPORT=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="--host" (+ set "HOST=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="--port" (+ set "PORT=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="-p" (+ set "PORT=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="--log-level" (+ set "LOG_LEVEL=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="-l" (+ set "LOG_LEVEL=%~2"+ shift+ shift+ goto :parse_args+)+if "%~1"=="--help" (+ goto :show_help+)+echo [ERROR] Unknown option: %~1+goto :show_help++:show_help+echo.+echo Claude-Flow MCP Server V3 Startup Script (Windows)+echo.+echo Usage:+echo start-mcp.cmd [options]+echo.+echo Options:+echo --transport, -t ^<type^> Transport: stdio, http, websocket (default: stdio)+echo --host ^<host^> Server host (default: localhost)+echo --port, -p ^<port^> Server port (default: 3000)+echo --log-level, -l ^<level^> Log level: debug, info, warn, error (default: info)+echo --help Show this help message+echo.+echo Examples:+echo start-mcp.cmd Start with defaults (stdio)+echo start-mcp.cmd -t http -p 8080 Start HTTP server on port 8080+echo.+echo Environment Variables:+echo MCP_TRANSPORT Override transport type+echo MCP_HOST Override host+echo MCP_PORT Override port+echo MCP_LOG_LEVEL Override log level+echo.+exit /b 0++:start_server+REM Check for Node.js+where node >nul 2>&1+if %ERRORLEVEL% neq 0 (+ echo [ERROR] Node.js is not installed+ exit /b 1+)++REM Server entry point+set "SERVER_ENTRY=%V3_DIR%\mcp\server-entry.ts"++if not exist "%SERVER_ENTRY%" (+ echo [ERROR] Server entry point not found: %SERVER_ENTRY%+ exit /b 1+)++echo [INFO] Starting Claude-Flow MCP Server V3...+echo [INFO] Transport: %TRANSPORT%+echo [INFO] Host: %HOST%+echo [INFO] Port: %PORT%+echo [INFO] Log level: %LOG_LEVEL%+echo [INFO] Mode: foreground (Ctrl+C to stop)+echo.++REM Start server+npx tsx "%SERVER_ENTRY%" --transport %TRANSPORT% --host %HOST% --port %PORT% --log-level %LOG_LEVEL%++endlocaldiff --git a/v3/scripts/start-mcp.sh b/v3/scripts/start-mcp.shnew file mode 100755index 0000000000..c2c7f5155a--- /dev/null+++ b/v3/scripts/start-mcp.sh@@ -0,0 +1,294 @@+#!/bin/bash+#+# Claude-Flow MCP Server V3 Startup Script+#+# Usage:+# ./start-mcp.sh [options]+#+# Options:+# --transport, -t <type> Transport: stdio, http, websocket (default: stdio)+# --host <host> Server host (default: localhost)+# --port, -p <port> Server port (default: 3000)+# --log-level, -l <level> Log level: debug, info, warn, error (default: info)+# --daemon, -d Run as daemon+# --help Show help+#+# Examples:+# ./start-mcp.sh # Start with defaults+# ./start-mcp.sh -t http -p 8080 # Start HTTP on port 8080+# ./start-mcp.sh --daemon # Run as background daemon+#++set -e++# Script directory+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+V3_DIR="$(dirname "$SCRIPT_DIR")"+PROJECT_ROOT="$(dirname "$V3_DIR")"++# Default configuration+TRANSPORT="stdio"+HOST="localhost"+PORT="3000"+LOG_LEVEL="info"+DAEMON=false++# PID file location+PID_FILE="${TMPDIR:-/tmp}/claude-flow-mcp.pid"+LOG_FILE="${TMPDIR:-/tmp}/claude-flow-mcp.log"++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[0;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++# Print functions+print_info() {+ echo -e "${BLUE}[INFO]${NC} $1"+}++print_success() {+ echo -e "${GREEN}[SUCCESS]${NC} $1"+}++print_warning() {+ echo -e "${YELLOW}[WARNING]${NC} $1"+}++print_error() {+ echo -e "${RED}[ERROR]${NC} $1"+}++# Show help+show_help() {+ cat << EOF+Claude-Flow MCP Server V3 Startup Script++Usage:+ ./start-mcp.sh [options]++Options:+ --transport, -t <type> Transport type: stdio, http, websocket (default: stdio)+ --host <host> Server host (default: localhost)+ --port, -p <port> Server port (default: 3000)+ --log-level, -l <level> Log level: debug, info, warn, error (default: info)+ --daemon, -d Run as background daemon+ --stop Stop running server+ --status Show server status+ --help Show this help message++Examples:+ ./start-mcp.sh # Start with defaults (stdio)+ ./start-mcp.sh -t http -p 8080 # Start HTTP server on port 8080+ ./start-mcp.sh --daemon # Run as background daemon+ ./start-mcp.sh --stop # Stop the daemon+ ./start-mcp.sh --status # Check if server is running++Environment Variables:+ MCP_TRANSPORT Override transport type+ MCP_HOST Override host+ MCP_PORT Override port+ MCP_LOG_LEVEL Override log level++EOF+}++# Check if server is running+is_running() {+ if [ -f "$PID_FILE" ]; then+ local pid+ pid=$(cat "$PID_FILE")+ if kill -0 "$pid" 2>/dev/null; then+ return 0+ fi+ fi+ return 1+}++# Get server PID+get_pid() {+ if [ -f "$PID_FILE" ]; then+ cat "$PID_FILE"+ fi+}++# Stop server+stop_server() {+ if ! is_running; then+ print_info "MCP Server is not running"+ return 0+ fi++ local pid+ pid=$(get_pid)+ print_info "Stopping MCP Server (PID: $pid)..."++ # Send SIGTERM for graceful shutdown+ kill -TERM "$pid" 2>/dev/null || true++ # Wait for process to exit+ local timeout=30+ while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do+ sleep 1+ ((timeout--))+ done++ # Force kill if still running+ if kill -0 "$pid" 2>/dev/null; then+ print_warning "Forcing shutdown..."+ kill -KILL "$pid" 2>/dev/null || true+ fi++ # Remove PID file+ rm -f "$PID_FILE"++ print_success "MCP Server stopped"+}++# Show status+show_status() {+ if is_running; then+ local pid+ pid=$(get_pid)+ print_success "MCP Server is running (PID: $pid)"++ # Show additional info if HTTP transport+ if [ -f "$LOG_FILE" ]; then+ echo ""+ echo "Recent logs:"+ tail -n 5 "$LOG_FILE" 2>/dev/null || true+ fi+ else+ print_info "MCP Server is not running"+ return 1+ fi+}++# Parse arguments+while [[ $# -gt 0 ]]; do+ case $1 in+ --transport|-t)+ TRANSPORT="$2"+ shift 2+ ;;+ --host)+ HOST="$2"+ shift 2+ ;;+ --port|-p)+ PORT="$2"+ shift 2+ ;;+ --log-level|-l)+ LOG_LEVEL="$2"+ shift 2+ ;;+ --daemon|-d)+ DAEMON=true+ shift+ ;;+ --stop)+ stop_server+ exit 0+ ;;+ --status)+ show_status+ exit $?+ ;;+ --help)+ show_help+ exit 0+ ;;+ *)+ print_error "Unknown option: $1"+ show_help+ exit 1+ ;;+ esac+done++# Override from environment variables+TRANSPORT="${MCP_TRANSPORT:-$TRANSPORT}"+HOST="${MCP_HOST:-$HOST}"+PORT="${MCP_PORT:-$PORT}"+LOG_LEVEL="${MCP_LOG_LEVEL:-$LOG_LEVEL}"++# Check if already running+if is_running; then+ local pid+ pid=$(get_pid)+ print_warning "MCP Server already running (PID: $pid)"+ print_info "Use --stop to stop the server first"+ exit 1+fi++# Check for Node.js+if ! command -v node &> /dev/null; then+ print_error "Node.js is not installed"+ exit 1+fi++# Check for npx+if ! command -v npx &> /dev/null; then+ print_error "npx is not available"+ exit 1+fi++# Server entry point+SERVER_ENTRY="$V3_DIR/mcp/server-entry.ts"++if [ ! -f "$SERVER_ENTRY" ]; then+ print_error "Server entry point not found: $SERVER_ENTRY"+ exit 1+fi++# Build command+CMD="npx tsx $SERVER_ENTRY \+ --transport $TRANSPORT \+ --host $HOST \+ --port $PORT \+ --log-level $LOG_LEVEL"++# Start server+print_info "Starting Claude-Flow MCP Server V3..."+print_info " Transport: $TRANSPORT"+print_info " Host: $HOST"+print_info " Port: $PORT"+print_info " Log level: $LOG_LEVEL"++if [ "$DAEMON" = true ]; then+ print_info " Mode: daemon"++ # Start in background+ nohup $CMD >> "$LOG_FILE" 2>&1 &+ echo $! > "$PID_FILE"++ # Wait a moment for startup+ sleep 2++ if is_running; then+ local pid+ pid=$(get_pid)+ print_success "MCP Server started (PID: $pid)"+ print_info "Logs: $LOG_FILE"++ if [ "$TRANSPORT" = "http" ]; then+ print_info "Health check: http://$HOST:$PORT/health"+ print_info "RPC endpoint: http://$HOST:$PORT/rpc"+ elif [ "$TRANSPORT" = "websocket" ]; then+ print_info "WebSocket: ws://$HOST:$PORT/ws"+ fi+ else+ print_error "Failed to start MCP Server"+ print_info "Check logs: $LOG_FILE"+ exit 1+ fi+else+ print_info " Mode: foreground (Ctrl+C to stop)"+ echo ""++ # Run in foreground+ exec $CMD+fi