claude-flow 2.7.34 → 2.7.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/claude-flow +1 -1
  3. package/dist/src/__tests__/benchmarks/performance.bench.js +0 -19
  4. package/dist/src/__tests__/benchmarks/performance.bench.js.map +1 -1
  5. package/dist/src/__tests__/hook-matchers.test.js.map +1 -1
  6. package/dist/src/agents/agent-registry.js.map +1 -1
  7. package/dist/src/api/auth-service.js.map +1 -1
  8. package/dist/src/api/claude-client-enhanced.js +4 -2
  9. package/dist/src/api/claude-client-enhanced.js.map +1 -1
  10. package/dist/src/api/claude-client.js +4 -2
  11. package/dist/src/api/claude-client.js.map +1 -1
  12. package/dist/src/api/database-service.js.map +1 -1
  13. package/dist/src/api/swarm-api.js +1 -1
  14. package/dist/src/api/swarm-api.js.map +1 -1
  15. package/dist/src/cli/commands/hive-mind/wizard.js +1 -1
  16. package/dist/src/cli/commands/hive-mind/wizard.js.map +1 -1
  17. package/dist/src/cli/help-formatter.js +0 -5
  18. package/dist/src/cli/init/index.js +55 -33
  19. package/dist/src/cli/init/index.js.map +1 -1
  20. package/dist/src/cli/simple-commands/init/skills-copier.js +1 -1
  21. package/dist/src/cli/simple-commands/init/skills-copier.js.map +1 -1
  22. package/dist/src/cli/simple-orchestrator.js +1 -1
  23. package/dist/src/cli/simple-orchestrator.js.map +1 -1
  24. package/dist/src/coordination/conflict-resolution.js +1 -1
  25. package/dist/src/coordination/conflict-resolution.js.map +1 -1
  26. package/dist/src/coordination/load-balancer.js +1 -1
  27. package/dist/src/coordination/load-balancer.js.map +1 -1
  28. package/dist/src/core/DatabaseManager.js +39 -9
  29. package/dist/src/core/DatabaseManager.js.map +1 -1
  30. package/dist/src/core/config.js +1 -1
  31. package/dist/src/core/config.js.map +1 -1
  32. package/dist/src/enterprise/audit-manager.js +1 -1
  33. package/dist/src/enterprise/audit-manager.js.map +1 -1
  34. package/dist/src/providers/openai-provider.js +2 -2
  35. package/dist/src/providers/openai-provider.js.map +1 -1
  36. package/dist/src/sdk/checkpoint-manager.js +1 -1
  37. package/dist/src/sdk/checkpoint-manager.js.map +1 -1
  38. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js +1 -1
  39. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js.map +1 -1
  40. package/dist/src/swarm/coordinator.js +1 -1
  41. package/dist/src/swarm/coordinator.js.map +1 -1
  42. package/dist/src/utils/error-recovery.js +215 -0
  43. package/dist/src/utils/error-recovery.js.map +1 -0
  44. package/dist/src/utils/key-redactor.js.map +1 -1
  45. package/dist/src/utils/metrics-reader.js +10 -0
  46. package/dist/src/verification/rollback.js +2 -2
  47. package/dist/src/verification/rollback.js.map +1 -1
  48. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js +4 -2
  49. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js.map +1 -1
  50. package/docs/.claude-flow/metrics/performance.json +3 -3
  51. package/docs/.claude-flow/metrics/task-metrics.json +3 -3
  52. package/docs/architecture/README.md +555 -0
  53. package/docs/architecture/github-workflows-optimization-strategy.md +1079 -0
  54. package/docs/architecture/workflow-architecture-diagram.md +615 -0
  55. package/docs/architecture/workflow-optimization-implementation-guide.md +593 -0
  56. package/docs/features/AUTOMATIC_ERROR_RECOVERY_v2.7.35.md +321 -0
  57. package/docs/features/automatic-error-recovery.md +333 -0
  58. package/docs/fixes/WORKFLOW_FIXES.md +292 -0
  59. package/docs/fixes/WORKFLOW_FIXES_FINAL_STATUS.md +291 -0
  60. package/docs/fixes/github-workflow-fixes-pr888.md +279 -0
  61. package/docs/fixes/workflow-fixes-action-plan.md +388 -0
  62. package/docs/github-issues/README.md +88 -0
  63. package/docs/github-issues/wsl-enotempty-automatic-recovery.md +470 -0
  64. package/docs/github-workflow-fixes.md +219 -0
  65. package/docs/reviews/github-workflows-analysis-report.md +820 -0
  66. package/docs/reviews/pr-888-review-report.md +560 -0
  67. package/docs/testing/CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md +384 -0
  68. package/docs/testing/DOCKER_TEST_RESULTS_v2.7.35.md +305 -0
  69. package/docs/troubleshooting/wsl-better-sqlite3-error.md +239 -0
  70. package/docs/validation/workflow-fix-verification.md +206 -0
  71. package/package.json +7 -7
  72. package/scripts/create-github-issue.sh +64 -0
  73. package/scripts/test-docker-wsl.sh +198 -0
  74. package/src/__tests__/benchmarks/performance.bench.ts +2 -25
  75. package/src/__tests__/hook-matchers.test.ts +2 -0
  76. package/src/agents/agent-registry.ts +1 -1
  77. package/src/api/auth-service.ts +1 -1
  78. package/src/api/claude-client-enhanced.ts +2 -1
  79. package/src/api/claude-client.ts +2 -2
  80. package/src/api/database-service.ts +1 -2
  81. package/src/api/swarm-api.ts +2 -2
  82. package/src/cli/commands/hive-mind/wizard.ts +1 -1
  83. package/src/cli/init/index.ts +72 -42
  84. package/src/cli/simple-commands/init/skills-copier.js +1 -1
  85. package/src/cli/simple-orchestrator.ts +1 -1
  86. package/src/coordination/conflict-resolution.ts +1 -1
  87. package/src/coordination/load-balancer.ts +1 -1
  88. package/src/core/DatabaseManager.ts +55 -9
  89. package/src/core/config.ts +1 -1
  90. package/src/enterprise/audit-manager.ts +1 -1
  91. package/src/providers/openai-provider.ts +2 -2
  92. package/src/sdk/checkpoint-manager.ts +1 -1
  93. package/src/services/agentic-flow-hooks/workflow-hooks.ts +1 -1
  94. package/src/swarm/coordinator.ts +1 -1
  95. package/src/utils/error-recovery.ts +325 -0
  96. package/src/verification/rollback.ts +2 -2
  97. package/src/verification/tests/mocks/false-reporting-scenarios.test.ts +6 -3
  98. /package/docs/{BUG_REPORT_MEMORY_STATS.md → bug-reports/BUG_REPORT_MEMORY_STATS.md} +0 -0
  99. /package/docs/{MCP_2025_FEATURE_CONFIRMATION.md → features/MCP_2025_FEATURE_CONFIRMATION.md} +0 -0
  100. /package/docs/{OPTIONAL_LOCAL_EMBEDDINGS.md → features/OPTIONAL_LOCAL_EMBEDDINGS.md} +0 -0
  101. /package/docs/{mcp-2025-implementation-summary.md → features/mcp-2025-implementation-summary.md} +0 -0
  102. /package/docs/{mcp-spec-2025-implementation-plan.md → features/mcp-spec-2025-implementation-plan.md} +0 -0
  103. /package/docs/{AGENTIC_FLOW_ENABLED_LOG_FIX.md → fixes/AGENTIC_FLOW_ENABLED_LOG_FIX.md} +0 -0
  104. /package/docs/{MEMORY_COMMAND_FIX.md → fixes/MEMORY_COMMAND_FIX.md} +0 -0
  105. /package/docs/{NPX_MEMORY_FIX_v2.7.19.md → fixes/NPX_MEMORY_FIX_v2.7.19.md} +0 -0
  106. /package/docs/{REMOTE_INSTALL_FIX.md → fixes/REMOTE_INSTALL_FIX.md} +0 -0
  107. /package/docs/{SQLITE_FIX_COMPLETE_v2.7.21.md → fixes/SQLITE_FIX_COMPLETE_v2.7.21.md} +0 -0
  108. /package/docs/{NPM_PUBLISH_GUIDE_v2.7.33.md → guides/NPM_PUBLISH_GUIDE_v2.7.33.md} +0 -0
  109. /package/docs/{SWARM_INITIALIZATION_GUIDE.md → guides/SWARM_INITIALIZATION_GUIDE.md} +0 -0
  110. /package/docs/{AGENTDB_BRANCH_MERGE_VERIFICATION.md → integration/AGENTDB_BRANCH_MERGE_VERIFICATION.md} +0 -0
  111. /package/docs/{INTEGRATION_STATUS_FINAL.md → integration/INTEGRATION_STATUS_FINAL.md} +0 -0
  112. /package/docs/{agentic-flow-agentdb-mcp-integration.md → integration/agentic-flow-agentdb-mcp-integration.md} +0 -0
  113. /package/docs/{phase-1-2-implementation-summary.md → integration/phase-1-2-implementation-summary.md} +0 -0
  114. /package/docs/{.github-release-issue-v2.7.33.md → releases/.github-release-issue-v2.7.33.md} +0 -0
  115. /package/docs/{RELEASE_NOTES_v2.7.15.md → releases/RELEASE_NOTES_v2.7.15.md} +0 -0
  116. /package/docs/{RELEASE_NOTES_v2.7.33.md → releases/RELEASE_NOTES_v2.7.33.md} +0 -0
  117. /package/docs/{RELEASE_READINESS_SUMMARY.md → releases/RELEASE_READINESS_SUMMARY.md} +0 -0
  118. /package/docs/{RELEASE_SUMMARY_v2.7.33.md → releases/RELEASE_SUMMARY_v2.7.33.md} +0 -0
  119. /package/docs/{V2.7.14_RELEASE_NOTES.md → releases/V2.7.14_RELEASE_NOTES.md} +0 -0
  120. /package/docs/{V2.7.25_RELEASE_NOTES.md → releases/V2.7.25_RELEASE_NOTES.md} +0 -0
  121. /package/docs/{V2.7.26_RELEASE_SUMMARY.md → releases/V2.7.26_RELEASE_SUMMARY.md} +0 -0
  122. /package/docs/{V2.7.27_RELEASE_NOTES.md → releases/V2.7.27_RELEASE_NOTES.md} +0 -0
  123. /package/docs/{V2.7.28_RELEASE_NOTES.md → releases/V2.7.28_RELEASE_NOTES.md} +0 -0
  124. /package/docs/{AGENTIC_FLOW_INTEGRATION_REVIEW.md → reviews/AGENTIC_FLOW_INTEGRATION_REVIEW.md} +0 -0
  125. /package/docs/{BRANCH_REVIEW_SUMMARY.md → reviews/BRANCH_REVIEW_SUMMARY.md} +0 -0
  126. /package/docs/{DEEP_CODE_REVIEW_v2.7.33.md → reviews/DEEP_CODE_REVIEW_v2.7.33.md} +0 -0
  127. /package/docs/{LATEST_LIBRARIES_REVIEW.md → reviews/LATEST_LIBRARIES_REVIEW.md} +0 -0
  128. /package/docs/{REGRESSION_TEST_REPORT_v2.7.33.md → testing/REGRESSION_TEST_REPORT_v2.7.33.md} +0 -0
  129. /package/docs/{V2.7.27_TEST_REPORT.md → testing/V2.7.27_TEST_REPORT.md} +0 -0
  130. /package/docs/{regression-analysis-phase-1-2.md → testing/regression-analysis-phase-1-2.md} +0 -0
  131. /package/docs/{TRANSFORMER_INITIALIZATION_ISSUE.md → troubleshooting/TRANSFORMER_INITIALIZATION_ISSUE.md} +0 -0
  132. /package/docs/{FIX_VERIFICATION_MEMORY_STATS.md → validation/FIX_VERIFICATION_MEMORY_STATS.md} +0 -0
  133. /package/docs/{TOOL_VALIDATION_REPORT.md → validation/TOOL_VALIDATION_REPORT.md} +0 -0
  134. /package/docs/{VALIDATION_REPORT_v2.7.1.md → validation/VALIDATION_REPORT_v2.7.1.md} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/swarm/coordinator.ts"],"sourcesContent":["import { EventEmitter } from 'events';\nimport { promises as fs } from 'node:fs';\nimport { Logger } from '../core/logger.js';\nimport { generateId } from '../utils/helpers.js';\nimport {\n SwarmId,\n AgentId,\n TaskId,\n AgentState,\n TaskDefinition,\n SwarmObjective,\n SwarmConfig,\n SwarmStatus,\n SwarmProgress,\n SwarmResults,\n SwarmMetrics,\n SwarmMode,\n SwarmStrategy,\n AgentType,\n TaskType,\n TaskStatus,\n TaskPriority,\n SwarmEvent,\n EventType,\n SwarmEventEmitter,\n ValidationResult,\n SWARM_CONSTANTS,\n} from './types.js';\nimport { AutoStrategy } from './strategies/auto.js';\nimport { getClaudeFlowRoot, getClaudeFlowBin } from '../utils/paths.js';\nimport { SwarmJsonOutputAggregator } from './json-output-aggregator.js';\n\nexport class SwarmCoordinator extends EventEmitter implements SwarmEventEmitter {\n private logger: Logger;\n private config: SwarmConfig;\n private swarmId: SwarmId;\n\n // Core state management\n private agents: Map<string, AgentState> = new Map();\n private tasks: Map<string, TaskDefinition> = new Map();\n private objectives: Map<string, SwarmObjective> = new Map();\n\n // Execution state\n private _isRunning: boolean = false;\n private status: SwarmStatus = 'planning';\n private startTime?: Date;\n private endTime?: Date;\n\n // Performance tracking\n private metrics: SwarmMetrics;\n private events: SwarmEvent[] = [];\n private lastHeartbeat: Date = new Date();\n\n // JSON output aggregation (optional)\n private jsonOutputAggregator?: SwarmJsonOutputAggregator;\n\n // Background processes\n private heartbeatTimer?: NodeJS.Timeout;\n private monitoringTimer?: NodeJS.Timeout;\n private cleanupTimer?: NodeJS.Timeout;\n private executionIntervals?: Map<string, NodeJS.Timeout>;\n\n // Strategy instances\n private autoStrategy: AutoStrategy;\n\n constructor(config: Partial<SwarmConfig> = {}) {\n super();\n\n // Configure logger based on config or default to quiet mode\n const logLevel = (config as any).logging?.level || 'error';\n const logFormat = (config as any).logging?.format || 'text';\n const logDestination = (config as any).logging?.destination || 'console';\n\n this.logger = new Logger(\n { level: logLevel, format: logFormat, destination: logDestination },\n { component: 'SwarmCoordinator' },\n );\n this.swarmId = this.generateSwarmId();\n\n // Initialize configuration with defaults\n this.config = this.mergeWithDefaults(config);\n\n // Initialize metrics\n this.metrics = this.initializeMetrics();\n\n // Initialize strategy instances\n this.autoStrategy = new AutoStrategy(config);\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.logger.info('SwarmCoordinator initialized', {\n swarmId: this.swarmId.id,\n mode: this.config.mode,\n strategy: this.config.strategy,\n });\n }\n\n // ===== LIFECYCLE MANAGEMENT =====\n\n async initialize(): Promise<void> {\n if (this._isRunning) {\n throw new Error('Swarm coordinator already running');\n }\n\n this.logger.info('Initializing swarm coordinator...');\n this.status = 'initializing';\n\n try {\n // Validate configuration\n const validation = await this.validateConfiguration();\n if (!validation.valid) {\n throw new Error(\n `Configuration validation failed: ${validation.errors.map((e) => e.message).join(', ')}`,\n );\n }\n\n // Initialize subsystems\n await this.initializeSubsystems();\n\n // Start background processes\n this.startBackgroundProcesses();\n\n this._isRunning = true;\n this.startTime = new Date();\n this.status = 'executing';\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.started',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n\n this.logger.info('Swarm coordinator initialized successfully');\n } catch (error) {\n this.status = 'failed';\n this.logger.error('Failed to initialize swarm coordinator', { error });\n throw error;\n }\n }\n\n async shutdown(): Promise<void> {\n if (!this._isRunning) {\n return;\n }\n\n this.logger.info('Shutting down swarm coordinator...');\n this.status = 'paused';\n\n try {\n // Stop background processes\n this.stopBackgroundProcesses();\n\n // Gracefully stop all agents\n await this.stopAllAgents();\n\n // Complete any running tasks\n await this.completeRunningTasks();\n\n // Save final state\n await this.saveState();\n\n this._isRunning = false;\n this.endTime = new Date();\n this.status = 'completed';\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.completed',\n source: this.swarmId.id,\n data: {\n swarmId: this.swarmId,\n metrics: this.metrics,\n duration: this.endTime.getTime() - (this.startTime?.getTime() || 0),\n },\n broadcast: true,\n processed: false,\n });\n\n this.logger.info('Swarm coordinator shut down successfully');\n } catch (error) {\n this.logger.error('Error during swarm coordinator shutdown', { error });\n throw error;\n }\n }\n\n async pause(): Promise<void> {\n if (!this._isRunning || this.status === 'paused') {\n return;\n }\n\n this.logger.info('Pausing swarm coordinator...');\n this.status = 'paused';\n\n // Pause all agents\n for (const agent of this.agents.values()) {\n if (agent.status === 'busy') {\n await this.pauseAgent(agent.id);\n }\n }\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.paused',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n }\n\n async resume(): Promise<void> {\n if (!this._isRunning || this.status !== 'paused') {\n return;\n }\n\n this.logger.info('Resuming swarm coordinator...');\n this.status = 'executing';\n\n // Resume all paused agents\n for (const agent of this.agents.values()) {\n if (agent.status === 'paused') {\n await this.resumeAgent(agent.id);\n }\n }\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.resumed',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n }\n\n // ===== OBJECTIVE MANAGEMENT =====\n\n async createObjective(\n name: string,\n description: string,\n strategy: SwarmStrategy = 'auto',\n requirements: Partial<SwarmObjective['requirements']> = {},\n ): Promise<string> {\n const objectiveId = generateId('objective');\n\n const objective: SwarmObjective = {\n id: objectiveId,\n name,\n description,\n strategy,\n mode: this.config.mode,\n requirements: {\n minAgents: 1,\n maxAgents: this.config.maxAgents,\n agentTypes: this.determineRequiredAgentTypes(strategy),\n estimatedDuration: 60 * 60 * 1000, // 1 hour default\n maxDuration: 4 * 60 * 60 * 1000, // 4 hours default\n qualityThreshold: this.config.qualityThreshold,\n reviewCoverage: 0.8,\n testCoverage: 0.7,\n reliabilityTarget: 0.95,\n ...requirements,\n },\n constraints: {\n minQuality: this.config.qualityThreshold,\n requiredApprovals: [],\n allowedFailures: Math.floor(this.config.maxAgents * 0.1),\n recoveryTime: 5 * 60 * 1000, // 5 minutes\n milestones: [],\n },\n tasks: [],\n dependencies: [],\n status: 'planning',\n progress: this.initializeProgress(),\n createdAt: new Date(),\n metrics: this.initializeMetrics(),\n };\n\n // Decompose objective into tasks using optimized AUTO strategy\n if (objective.strategy === 'auto') {\n const decompositionResult = await this.autoStrategy.decomposeObjective(objective);\n objective.tasks = decompositionResult.tasks;\n objective.dependencies = this.convertDependenciesToTaskDependencies(\n decompositionResult.dependencies,\n );\n } else {\n objective.tasks = await this.decomposeObjective(objective);\n objective.dependencies = this.analyzeDependencies(objective.tasks);\n }\n\n this.objectives.set(objectiveId, objective);\n\n this.logger.info('Created objective', {\n objectiveId,\n name,\n strategy,\n taskCount: objective.tasks.length,\n });\n\n return objectiveId;\n }\n\n async executeObjective(objectiveId: string): Promise<void> {\n const objective = this.objectives.get(objectiveId);\n if (!objective) {\n throw new Error(`Objective not found: ${objectiveId}`);\n }\n\n if (objective.status !== 'planning') {\n throw new Error(`Objective already ${objective.status}`);\n }\n\n this.logger.info('Executing objective', { objectiveId, name: objective.name });\n objective.status = 'executing';\n objective.startedAt = new Date();\n\n try {\n // Ensure we have required agents\n await this.ensureRequiredAgents(objective);\n\n // Schedule initial tasks\n await this.scheduleInitialTasks(objective);\n\n // Start task execution loop\n this.startTaskExecutionLoop(objective);\n } catch (error) {\n objective.status = 'failed';\n this.logger.error('Failed to execute objective', { objectiveId, error });\n throw error;\n }\n }\n\n // ===== AGENT MANAGEMENT =====\n\n async registerAgent(\n name: string,\n type: AgentType,\n capabilities: Partial<AgentState['capabilities']> = {},\n ): Promise<string> {\n const agentId: AgentId = {\n id: generateId('agent'),\n swarmId: this.swarmId.id,\n type,\n instance: this.getNextInstanceNumber(type),\n };\n\n const agentState: AgentState = {\n id: agentId,\n name,\n type,\n status: 'initializing',\n capabilities: {\n // Default capabilities\n codeGeneration: false,\n codeReview: false,\n testing: false,\n documentation: false,\n research: false,\n analysis: false,\n webSearch: false,\n apiIntegration: false,\n fileSystem: true,\n terminalAccess: true,\n languages: [],\n frameworks: [],\n domains: [],\n tools: [],\n maxConcurrentTasks: 3,\n maxMemoryUsage: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,\n maxExecutionTime: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n reliability: 0.8,\n speed: 1.0,\n quality: 0.8,\n ...capabilities,\n },\n metrics: {\n tasksCompleted: 0,\n tasksFailed: 0,\n averageExecutionTime: 0,\n successRate: 0,\n cpuUsage: 0,\n memoryUsage: 0,\n diskUsage: 0,\n networkUsage: 0,\n codeQuality: 0,\n testCoverage: 0,\n bugRate: 0,\n userSatisfaction: 0,\n totalUptime: 0,\n lastActivity: new Date(),\n responseTime: 0,\n },\n workload: 0,\n health: 1.0,\n config: {\n autonomyLevel: 0.7,\n learningEnabled: true,\n adaptationEnabled: true,\n maxTasksPerHour: 10,\n maxConcurrentTasks: capabilities.maxConcurrentTasks || 3,\n timeoutThreshold: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n reportingInterval: 30000,\n heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,\n permissions: this.getDefaultPermissions(type),\n trustedAgents: [],\n expertise: {},\n preferences: {},\n },\n environment: {\n runtime: 'deno',\n version: '1.0.0',\n workingDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}`,\n tempDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/temp`,\n logDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/logs`,\n apiEndpoints: {},\n credentials: {},\n availableTools: [],\n toolConfigs: {},\n },\n endpoints: [],\n lastHeartbeat: new Date(),\n taskHistory: [],\n errorHistory: [],\n childAgents: [],\n collaborators: [],\n };\n\n this.agents.set(agentId.id, agentState);\n\n // Track agent in JSON output if enabled\n this.trackAgentInJsonOutput(agentState);\n\n // Initialize agent capabilities based on type\n await this.initializeAgentCapabilities(agentState);\n\n // Start agent\n await this.startAgent(agentId.id);\n\n this.logger.info('Registered agent', {\n agentId: agentId.id,\n name,\n type,\n capabilities: Object.keys(capabilities),\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.created',\n source: agentId.id,\n data: { agent: agentState },\n broadcast: false,\n processed: false,\n });\n\n return agentId.id;\n }\n\n async unregisterAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return;\n }\n\n this.logger.info('Unregistering agent', { agentId, name: agent.name });\n\n // Stop agent gracefully\n await this.stopAgent(agentId);\n\n // Reassign any active tasks\n if (agent.currentTask) {\n await this.reassignTask(agent.currentTask.id);\n }\n\n // Remove from agents map\n this.agents.delete(agentId);\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.stopped',\n source: agentId,\n data: { agentId },\n broadcast: false,\n processed: false,\n });\n }\n\n async startAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n throw new Error(`Agent not found: ${agentId}`);\n }\n\n if (agent.status !== 'initializing' && agent.status !== 'offline') {\n return;\n }\n\n this.logger.info('Starting agent', { agentId, name: agent.name });\n\n try {\n // Initialize agent environment\n await this.initializeAgentEnvironment(agent);\n\n // Start agent heartbeat\n this.startAgentHeartbeat(agent);\n\n agent.status = 'idle';\n agent.lastHeartbeat = new Date();\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.started',\n source: agentId,\n data: { agent },\n broadcast: false,\n processed: false,\n });\n } catch (error) {\n agent.status = 'error';\n agent.errorHistory.push({\n timestamp: new Date(),\n type: 'startup_error',\n message: error instanceof Error ? error.message : String(error),\n stack: error.stack,\n context: { agentId },\n severity: 'high',\n resolved: false,\n });\n\n this.logger.error('Failed to start agent', { agentId, error });\n throw error;\n }\n }\n\n async stopAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return;\n }\n\n if (agent.status === 'offline' || agent.status === 'terminated') {\n return;\n }\n\n this.logger.info('Stopping agent', { agentId, name: agent.name });\n\n agent.status = 'terminating';\n\n try {\n // Cancel current task if any\n if (agent.currentTask) {\n await this.cancelTask(agent.currentTask.id, 'Agent stopping');\n }\n\n // Stop heartbeat\n this.stopAgentHeartbeat(agent);\n\n // Cleanup agent environment\n await this.cleanupAgentEnvironment(agent);\n\n agent.status = 'terminated';\n } catch (error) {\n agent.status = 'error';\n this.logger.error('Error stopping agent', { agentId, error });\n }\n }\n\n async pauseAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent || agent.status !== 'busy') {\n return;\n }\n\n agent.status = 'paused';\n this.logger.info('Paused agent', { agentId });\n }\n\n async resumeAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent || agent.status !== 'paused') {\n return;\n }\n\n agent.status = 'busy';\n this.logger.info('Resumed agent', { agentId });\n }\n\n // ===== TASK MANAGEMENT =====\n\n async createTask(\n type: TaskType,\n name: string,\n description: string,\n instructions: string,\n options: Partial<TaskDefinition> = {},\n ): Promise<string> {\n const taskId: TaskId = {\n id: generateId('task'),\n swarmId: this.swarmId.id,\n sequence: this.tasks.size + 1,\n priority: 1,\n };\n\n const task: TaskDefinition = {\n id: taskId,\n type,\n name,\n description,\n instructions,\n requirements: {\n capabilities: this.getRequiredCapabilities(type),\n tools: this.getRequiredTools(type),\n permissions: this.getRequiredPermissions(type),\n ...options.requirements,\n },\n constraints: {\n dependencies: [],\n dependents: [],\n conflicts: [],\n maxRetries: SWARM_CONSTANTS.MAX_RETRIES,\n timeoutAfter: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n ...options.constraints,\n },\n priority: 'normal',\n input: options.input || {},\n context: options.context || {},\n examples: options.examples || [],\n status: 'created',\n createdAt: new Date(),\n updatedAt: new Date(),\n attempts: [],\n statusHistory: [\n {\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'created' as TaskStatus,\n reason: 'Task created',\n triggeredBy: 'system',\n },\n ],\n ...options,\n };\n\n this.tasks.set(taskId.id, task);\n\n // Track task in JSON output if enabled\n this.trackTaskInJsonOutput(task);\n\n this.logger.info('Created task', {\n taskId: taskId.id,\n type,\n name,\n priority: task.priority,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.created',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n\n return taskId.id;\n }\n\n async assignTask(taskId: string, agentId?: string): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n if (task.status !== 'created' && task.status !== 'queued') {\n throw new Error(`Task cannot be assigned, current status: ${task.status}`);\n }\n\n // Select agent if not specified\n if (!agentId) {\n agentId = await this.selectAgentForTask(task);\n if (!agentId) {\n throw new Error('No suitable agent available for task');\n }\n }\n\n const agent = this.agents.get(agentId);\n if (!agent) {\n throw new Error(`Agent not found: ${agentId}`);\n }\n\n if (agent.status !== 'idle') {\n throw new Error(`Agent not available: ${agent.status}`);\n }\n\n // Assign task\n task.assignedTo = agent.id;\n task.assignedAt = new Date();\n task.status = 'assigned';\n\n agent.currentTask = task.id;\n agent.status = 'busy';\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: task.statusHistory[task.statusHistory.length - 1].to,\n to: 'assigned',\n reason: `Assigned to agent ${agent.name}`,\n triggeredBy: 'system',\n });\n\n this.logger.info('Assigned task', {\n taskId,\n agentId,\n agentName: agent.name,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.assigned',\n source: agentId,\n data: { task, agent },\n broadcast: false,\n processed: false,\n });\n\n // Start task execution\n await this.startTaskExecution(task);\n }\n\n async startTaskExecution(task: TaskDefinition): Promise<void> {\n if (!task.assignedTo) {\n throw new Error('Task not assigned to any agent');\n }\n\n const agent = this.agents.get(task.assignedTo.id);\n if (!agent) {\n throw new Error(`Agent not found: ${task.assignedTo.id}`);\n }\n\n this.logger.info('Starting task execution', {\n taskId: task.id.id,\n agentId: agent.id.id,\n });\n\n task.status = 'running';\n task.startedAt = new Date();\n\n // Create attempt record\n const attempt = {\n attemptNumber: task.attempts.length + 1,\n agent: agent.id,\n startedAt: new Date(),\n status: 'running' as TaskStatus,\n resourcesUsed: {},\n };\n task.attempts.push(attempt);\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'assigned',\n to: 'running',\n reason: 'Task execution started',\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.started',\n source: agent.id.id,\n data: { task, agent, attempt },\n broadcast: false,\n processed: false,\n });\n\n try {\n // Execute task (this would spawn actual Claude process)\n const result = await this.executeTaskWithAgent(task, agent);\n await this.completeTask(task.id.id, result);\n } catch (error) {\n await this.failTask(task.id.id, error);\n }\n }\n\n async completeTask(taskId: string, result: any): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n if (!agent) {\n throw new Error('Task not assigned to any agent');\n }\n\n this.logger.info('Completing task', { taskId, agentId: agent.id.id });\n\n task.status = 'completed';\n task.completedAt = new Date();\n task.result = {\n output: result,\n artifacts: {},\n metadata: {},\n quality: this.assessTaskQuality(task, result),\n completeness: 1.0,\n accuracy: 1.0,\n executionTime: task.completedAt.getTime() - (task.startedAt?.getTime() || 0),\n resourcesUsed: {},\n validated: false,\n };\n\n // Update attempt\n const currentAttempt = task.attempts[task.attempts.length - 1];\n if (currentAttempt) {\n currentAttempt.completedAt = new Date();\n currentAttempt.status = 'completed';\n currentAttempt.result = task.result;\n }\n\n // Update agent state\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksCompleted++;\n agent.metrics.lastActivity = new Date();\n agent.taskHistory.push(task.id);\n\n // Update agent metrics\n this.updateAgentMetrics(agent, task);\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'completed',\n reason: 'Task completed successfully',\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.completed',\n source: agent.id.id,\n data: { task, agent, result: task.result },\n broadcast: false,\n processed: false,\n });\n\n // Check for dependent tasks\n await this.processDependentTasks(task);\n }\n\n async failTask(taskId: string, error: any): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n if (!agent) {\n throw new Error('Task not assigned to any agent');\n }\n\n this.logger.warn('Task failed', {\n taskId,\n agentId: agent.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n\n task.error = {\n type: error.constructor.name,\n message: error instanceof Error ? error.message : String(error),\n code: error.code,\n stack: error.stack,\n context: { taskId, agentId: agent.id.id },\n recoverable: this.isRecoverableError(error),\n retryable: this.isRetryableError(error),\n };\n\n // Update attempt\n const currentAttempt = task.attempts[task.attempts.length - 1];\n if (currentAttempt) {\n currentAttempt.completedAt = new Date();\n currentAttempt.status = 'failed';\n currentAttempt.error = task.error;\n }\n\n // Update agent state\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksFailed++;\n agent.metrics.lastActivity = new Date();\n\n // Add to error history\n agent.errorHistory.push({\n timestamp: new Date(),\n type: 'task_failure',\n message: error instanceof Error ? error.message : String(error),\n stack: error.stack,\n context: { taskId },\n severity: 'medium',\n resolved: false,\n });\n\n // Determine if we should retry\n const shouldRetry =\n task.error.retryable &&\n task.attempts.length < (task.constraints.maxRetries || SWARM_CONSTANTS.MAX_RETRIES);\n\n if (shouldRetry) {\n task.status = 'retrying';\n task.assignedTo = undefined;\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'retrying',\n reason: `Task failed, will retry: ${error instanceof Error ? error.message : String(error)}`,\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.retried',\n source: agent.id.id,\n data: { task, error: task.error, attempt: task.attempts.length },\n broadcast: false,\n processed: false,\n });\n\n // Schedule retry with exponential backoff\n const retryDelay = Math.pow(2, task.attempts.length) * 1000;\n setTimeout(() => {\n this.assignTask(taskId).catch((retryError) => {\n this.logger.error('Failed to retry task', { taskId, retryError });\n });\n }, retryDelay);\n } else {\n task.status = 'failed';\n task.completedAt = new Date();\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'failed',\n reason: `Task failed permanently: ${error instanceof Error ? error.message : String(error)}`,\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.failed',\n source: agent.id.id,\n data: { task, error: task.error },\n broadcast: false,\n processed: false,\n });\n\n // Handle failure cascade\n await this.handleTaskFailureCascade(task);\n }\n }\n\n async cancelTask(taskId: string, reason: string): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n\n this.logger.info('Cancelling task', { taskId, reason });\n\n task.status = 'cancelled';\n task.completedAt = new Date();\n\n if (agent) {\n agent.status = 'idle';\n agent.currentTask = undefined;\n }\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: task.statusHistory[task.statusHistory.length - 1].to,\n to: 'cancelled',\n reason: `Task cancelled: ${reason}`,\n triggeredBy: 'system',\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.cancelled',\n source: this.swarmId.id,\n data: { task, reason },\n broadcast: false,\n processed: false,\n });\n }\n\n // ===== ADVANCED FEATURES =====\n\n async selectAgentForTask(task: TaskDefinition): Promise<string | null> {\n const availableAgents = Array.from(this.agents.values()).filter(\n (agent) => agent.status === 'idle' && this.agentCanHandleTask(agent, task),\n );\n\n if (availableAgents.length === 0) {\n return null;\n }\n\n // Score agents based on multiple criteria\n const scoredAgents = availableAgents.map((agent) => ({\n agent,\n score: this.calculateAgentScore(agent, task),\n }));\n\n // Sort by score (highest first)\n scoredAgents.sort((a, b) => b.score - a.score);\n\n return scoredAgents[0].agent.id.id;\n }\n\n private calculateAgentScore(agent: AgentState, task: TaskDefinition): number {\n let score = 0;\n\n // Capability match (40% weight)\n const capabilityMatch = this.calculateCapabilityMatch(agent, task);\n score += capabilityMatch * 0.4;\n\n // Performance history (30% weight)\n const performanceScore = agent.metrics.successRate * agent.capabilities.reliability;\n score += performanceScore * 0.3;\n\n // Current workload (20% weight)\n const workloadScore = 1 - agent.workload;\n score += workloadScore * 0.2;\n\n // Quality rating (10% weight)\n score += agent.capabilities.quality * 0.1;\n\n return score;\n }\n\n private calculateCapabilityMatch(agent: AgentState, task: TaskDefinition): number {\n const requiredCapabilities = task.requirements.capabilities;\n let matches = 0;\n let total = requiredCapabilities.length;\n\n for (const capability of requiredCapabilities) {\n if (this.agentHasCapability(agent, capability)) {\n matches++;\n }\n }\n\n return total > 0 ? matches / total : 1.0;\n }\n\n private agentHasCapability(agent: AgentState, capability: string): boolean {\n const caps = agent.capabilities;\n\n switch (capability) {\n case 'code-generation':\n return caps.codeGeneration;\n case 'code-review':\n return caps.codeReview;\n case 'testing':\n return caps.testing;\n case 'documentation':\n return caps.documentation;\n case 'research':\n return caps.research;\n case 'analysis':\n return caps.analysis;\n case 'web-search':\n return caps.webSearch;\n case 'api-integration':\n return caps.apiIntegration;\n case 'file-system':\n return caps.fileSystem;\n case 'terminal-access':\n return caps.terminalAccess;\n case 'validation':\n return caps.testing; // Validation is part of testing capability\n default:\n return (\n caps.domains.includes(capability) ||\n caps.languages.includes(capability) ||\n caps.frameworks.includes(capability) ||\n caps.tools.includes(capability)\n );\n }\n }\n\n private agentCanHandleTask(agent: AgentState, task: TaskDefinition): boolean {\n // Check if agent type is suitable\n if (task.requirements.agentType && agent.type !== task.requirements.agentType) {\n return false;\n }\n\n // Check if agent has required capabilities\n for (const capability of task.requirements.capabilities) {\n if (!this.agentHasCapability(agent, capability)) {\n return false;\n }\n }\n\n // Check reliability requirement\n if (\n task.requirements.minReliability &&\n agent.capabilities.reliability < task.requirements.minReliability\n ) {\n return false;\n }\n\n // Check if agent has capacity\n if (agent.workload >= 1.0) {\n return false;\n }\n\n return true;\n }\n\n // ===== HELPER METHODS =====\n\n private generateSwarmId(): SwarmId {\n return {\n id: generateId('swarm'),\n timestamp: Date.now(),\n namespace: 'default',\n };\n }\n\n private mergeWithDefaults(config: Partial<SwarmConfig>): SwarmConfig {\n return {\n name: 'Unnamed Swarm',\n description: 'Auto-generated swarm',\n version: '1.0.0',\n mode: 'centralized',\n strategy: 'auto',\n coordinationStrategy: {\n name: 'default',\n description: 'Default coordination strategy',\n agentSelection: 'capability-based',\n taskScheduling: 'priority',\n loadBalancing: 'work-stealing',\n faultTolerance: 'retry',\n communication: 'event-driven',\n },\n maxAgents: 10,\n maxTasks: 100,\n maxDuration: 4 * 60 * 60 * 1000, // 4 hours\n resourceLimits: {\n memory: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,\n cpu: SWARM_CONSTANTS.DEFAULT_CPU_LIMIT,\n disk: SWARM_CONSTANTS.DEFAULT_DISK_LIMIT,\n },\n qualityThreshold: SWARM_CONSTANTS.DEFAULT_QUALITY_THRESHOLD,\n reviewRequired: true,\n testingRequired: true,\n monitoring: {\n metricsEnabled: true,\n loggingEnabled: true,\n tracingEnabled: false,\n metricsInterval: 10000,\n heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,\n healthCheckInterval: 30000,\n retentionPeriod: 24 * 60 * 60 * 1000, // 24 hours\n maxLogSize: 100 * 1024 * 1024, // 100MB\n maxMetricPoints: 10000,\n alertingEnabled: true,\n alertThresholds: {\n errorRate: 0.1,\n responseTime: 5000,\n memoryUsage: 0.8,\n cpuUsage: 0.8,\n },\n exportEnabled: false,\n exportFormat: 'json',\n exportDestination: '/tmp/swarm-metrics',\n },\n memory: {\n namespace: 'default',\n partitions: [],\n permissions: {\n read: 'swarm',\n write: 'team',\n delete: 'private',\n share: 'team',\n },\n persistent: true,\n backupEnabled: true,\n distributed: false,\n consistency: 'eventual',\n cacheEnabled: true,\n compressionEnabled: false,\n },\n security: {\n authenticationRequired: false,\n authorizationRequired: false,\n encryptionEnabled: false,\n defaultPermissions: ['read', 'write'],\n adminRoles: ['admin', 'coordinator'],\n auditEnabled: true,\n auditLevel: 'info',\n inputValidation: true,\n outputSanitization: true,\n },\n performance: {\n maxConcurrency: 10,\n defaultTimeout: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n cacheEnabled: true,\n cacheSize: 100,\n cacheTtl: 3600000, // 1 hour\n optimizationEnabled: true,\n adaptiveScheduling: true,\n predictiveLoading: false,\n resourcePooling: true,\n connectionPooling: true,\n memoryPooling: false,\n },\n ...config,\n };\n }\n\n private initializeMetrics(): SwarmMetrics {\n return {\n throughput: 0,\n latency: 0,\n efficiency: 0,\n reliability: 0,\n averageQuality: 0,\n defectRate: 0,\n reworkRate: 0,\n resourceUtilization: {},\n costEfficiency: 0,\n agentUtilization: 0,\n agentSatisfaction: 0,\n collaborationEffectiveness: 0,\n scheduleVariance: 0,\n deadlineAdherence: 0,\n };\n }\n\n private initializeProgress(): SwarmProgress {\n return {\n totalTasks: 0,\n completedTasks: 0,\n failedTasks: 0,\n runningTasks: 0,\n estimatedCompletion: new Date(),\n timeRemaining: 0,\n percentComplete: 0,\n averageQuality: 0,\n passedReviews: 0,\n passedTests: 0,\n resourceUtilization: {},\n costSpent: 0,\n activeAgents: 0,\n idleAgents: 0,\n busyAgents: 0,\n };\n }\n\n // ===== EVENT HANDLING =====\n\n private setupEventHandlers(): void {\n // Handle agent heartbeats\n this.on('agent.heartbeat', (data: any) => {\n const agent = this.agents.get(data.agentId);\n if (agent) {\n agent.lastHeartbeat = new Date();\n agent.health = data.health || 1.0;\n agent.metrics = { ...agent.metrics, ...data.metrics };\n }\n });\n\n // Handle task completion events\n this.on('task.completed', (data: any) => {\n this.updateSwarmMetrics();\n this.checkObjectiveCompletion();\n });\n\n // Handle task failure events\n this.on('task.failed', (data: any) => {\n this.updateSwarmMetrics();\n this.checkObjectiveFailure(data.task);\n });\n\n // Handle agent errors\n this.on('agent.error', (data: any) => {\n this.handleAgentError(data.agentId, data.error);\n });\n }\n\n // ===== SWARM EVENT EMITTER IMPLEMENTATION =====\n\n emitSwarmEvent(event: SwarmEvent): boolean {\n this.events.push(event);\n\n // Limit event history\n if (this.events.length > 1000) {\n this.events = this.events.slice(-500);\n }\n\n return this.emit(event.type, event);\n }\n\n emitSwarmEvents(events: SwarmEvent[]): boolean {\n let success = true;\n for (const event of events) {\n if (!this.emitSwarmEvent(event)) {\n success = false;\n }\n }\n return success;\n }\n\n onSwarmEvent(type: EventType, handler: (event: SwarmEvent) => void): this {\n return this.on(type, handler);\n }\n\n offSwarmEvent(type: EventType, handler: (event: SwarmEvent) => void): this {\n return this.off(type, handler);\n }\n\n filterEvents(predicate: (event: SwarmEvent) => boolean): SwarmEvent[] {\n return this.events.filter(predicate);\n }\n\n correlateEvents(correlationId: string): SwarmEvent[] {\n return this.events.filter((event) => event.correlationId === correlationId);\n }\n\n // ===== PUBLIC API METHODS =====\n\n getSwarmId(): SwarmId {\n return this.swarmId;\n }\n\n getStatus(): SwarmStatus {\n return this.status;\n }\n\n getAgents(): AgentState[] {\n return Array.from(this.agents.values());\n }\n\n getAgent(agentId: string): AgentState | undefined {\n return this.agents.get(agentId);\n }\n\n getTasks(): TaskDefinition[] {\n return Array.from(this.tasks.values());\n }\n\n getTask(taskId: string): TaskDefinition | undefined {\n return this.tasks.get(taskId);\n }\n\n getObjectives(): SwarmObjective[] {\n return Array.from(this.objectives.values());\n }\n\n getObjective(objectiveId: string): SwarmObjective | undefined {\n return this.objectives.get(objectiveId);\n }\n\n getMetrics(): SwarmMetrics {\n return { ...this.metrics };\n }\n\n getEvents(): SwarmEvent[] {\n return [...this.events];\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n getUptime(): number {\n if (!this.startTime) return 0;\n const endTime = this.endTime || new Date();\n return endTime.getTime() - this.startTime.getTime();\n }\n\n getSwarmStatus(): {\n status: SwarmStatus;\n objectives: number;\n tasks: { completed: number; failed: number; total: number };\n agents: { total: number };\n } {\n const tasks = Array.from(this.tasks.values());\n const completedTasks = tasks.filter((t) => t.status === 'completed').length;\n const failedTasks = tasks.filter((t) => t.status === 'failed').length;\n\n return {\n status: this.status,\n objectives: this.objectives.size,\n tasks: {\n completed: completedTasks,\n failed: failedTasks,\n total: tasks.length,\n },\n agents: {\n total: this.agents.size,\n },\n };\n }\n\n // ===== STUB METHODS (TO BE IMPLEMENTED) =====\n\n private async validateConfiguration(): Promise<ValidationResult> {\n // Implementation needed\n return {\n valid: true,\n errors: [],\n warnings: [],\n validatedAt: new Date(),\n validator: 'SwarmCoordinator',\n context: {},\n };\n }\n\n private async initializeSubsystems(): Promise<void> {\n // Implementation needed\n }\n\n private startBackgroundProcesses(): void {\n // Start heartbeat monitoring\n this.heartbeatTimer = setInterval(() => {\n this.processHeartbeats();\n }, this.config.monitoring.heartbeatInterval);\n\n // Start performance monitoring\n this.monitoringTimer = setInterval(() => {\n this.updateSwarmMetrics();\n }, this.config.monitoring.metricsInterval);\n\n // Start cleanup process\n this.cleanupTimer = setInterval(() => {\n this.performCleanup();\n }, 60000); // Every minute\n }\n\n private stopBackgroundProcesses(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n }\n if (this.monitoringTimer) {\n clearInterval(this.monitoringTimer);\n this.monitoringTimer = undefined;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n // Stop all execution intervals\n if (this.executionIntervals) {\n for (const [objectiveId, interval] of this.executionIntervals) {\n clearInterval(interval);\n }\n this.executionIntervals.clear();\n }\n }\n\n private async stopAllAgents(): Promise<void> {\n const stopPromises = Array.from(this.agents.keys()).map((agentId) => this.stopAgent(agentId));\n await Promise.allSettled(stopPromises);\n }\n\n private async completeRunningTasks(): Promise<void> {\n const runningTasks = Array.from(this.tasks.values()).filter(\n (task) => task.status === 'running',\n );\n\n // Wait for tasks to complete or timeout\n const timeout = 30000; // 30 seconds\n const deadline = Date.now() + timeout;\n\n while (runningTasks.some((task) => task.status === 'running') && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n\n // Cancel any remaining running tasks\n for (const task of runningTasks) {\n if (task.status === 'running') {\n await this.cancelTask(task.id.id, 'Swarm shutdown');\n }\n }\n }\n\n private async saveState(): Promise<void> {\n // Implementation needed - save swarm state to persistence layer\n }\n\n private determineRequiredAgentTypes(strategy: SwarmStrategy): AgentType[] {\n switch (strategy) {\n case 'research':\n return ['researcher', 'analyst'];\n case 'development':\n return ['coder', 'tester', 'reviewer'];\n case 'analysis':\n return ['analyst', 'researcher'];\n case 'testing':\n return ['tester', 'coder'];\n case 'optimization':\n return ['analyst', 'coder'];\n case 'maintenance':\n return ['coder', 'monitor'];\n default:\n return ['coordinator', 'coder', 'analyst'];\n }\n }\n\n private getAgentTypeInstructions(agentType: string): string {\n switch (agentType) {\n case 'coder':\n return '- Focus on implementation, code quality, and best practices\\n- Create clean, maintainable code\\n- Consider architecture and design patterns';\n case 'tester':\n return '- Focus on testing, edge cases, and quality assurance\\n- Create comprehensive test suites\\n- Identify potential bugs and issues';\n case 'analyst':\n return '- Focus on analysis, research, and understanding\\n- Break down complex problems\\n- Provide insights and recommendations';\n case 'researcher':\n return '- Focus on gathering information and best practices\\n- Research existing solutions and patterns\\n- Document findings and recommendations';\n case 'reviewer':\n return '- Focus on code review and quality checks\\n- Identify improvements and optimizations\\n- Ensure standards compliance';\n case 'coordinator':\n return '- Focus on coordination and integration\\n- Ensure all parts work together\\n- Manage dependencies and interfaces';\n case 'monitor':\n return '- Focus on monitoring and observability\\n- Set up logging and metrics\\n- Ensure system health tracking';\n default:\n return '- Execute the task to the best of your ability\\n- Follow best practices for your domain';\n }\n }\n\n private getAgentCapabilities(agentType: string): string[] {\n switch (agentType) {\n case 'coder':\n return ['code-generation', 'file-system', 'debugging'];\n case 'tester':\n return ['testing', 'code-generation', 'analysis'];\n case 'analyst':\n return ['analysis', 'documentation', 'research'];\n case 'researcher':\n return ['research', 'documentation', 'analysis'];\n case 'reviewer':\n return ['code-review', 'analysis', 'documentation'];\n case 'coordinator':\n return ['coordination', 'analysis', 'documentation'];\n case 'monitor':\n return ['monitoring', 'analysis', 'documentation'];\n default:\n return ['analysis', 'documentation'];\n }\n }\n\n private async decomposeObjective(objective: SwarmObjective): Promise<TaskDefinition[]> {\n // Decompose objective into tasks with clear instructions for Claude\n this.logger.info('Decomposing objective', {\n objectiveId: objective.id,\n description: objective.description,\n });\n\n const tasks: TaskDefinition[] = [];\n\n // Extract target directory from objective\n const targetDirMatch = objective.description.match(\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)|([^\\s]+\\/[^\\s]+)$/,\n );\n const targetDir = targetDirMatch ? targetDirMatch[1] || targetDirMatch[2] : null;\n const targetPath = targetDir\n ? targetDir.startsWith('/')\n ? targetDir\n : `${getClaudeFlowRoot()}/${targetDir}`\n : null;\n\n // Check if objective requests \"each agent\" or \"each agent type\" for parallel execution\n const eachAgentPattern = /\\beach\\s+agent(?:\\s+type)?\\b/i;\n const requestsParallelAgents = eachAgentPattern.test(objective.description);\n\n // Create tasks with specific prompts for Claude\n if (requestsParallelAgents && this.config.mode === 'parallel') {\n // Create parallel tasks for each agent type\n const agentTypes = this.determineRequiredAgentTypes(objective.strategy);\n this.logger.info('Creating parallel tasks for each agent type', {\n agentTypes,\n mode: this.config.mode,\n });\n\n for (const agentType of agentTypes) {\n const taskId = this.createTaskForObjective(`${agentType}-task`, agentType as TaskType, {\n title: `${agentType.charAt(0).toUpperCase() + agentType.slice(1)} Agent Task`,\n description: `${agentType} agent executing: ${objective.description}`,\n instructions: `You are a ${agentType} agent. Please execute the following task from your perspective:\n\n${objective.description}\n\n${targetPath ? `Target Directory: ${targetPath}` : ''}\n\nAs a ${agentType} agent, focus on aspects relevant to your role:\n${this.getAgentTypeInstructions(agentType)}\n\nWork independently but be aware that other agents are working on this same objective from their perspectives.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 10 * 60 * 1000,\n requiredCapabilities: this.getAgentCapabilities(agentType),\n });\n tasks.push(taskId);\n }\n } else if (objective.strategy === 'development') {\n // Task 1: Analyze and Plan\n const task1 = this.createTaskForObjective('analyze-requirements', 'analysis', {\n title: 'Analyze Requirements and Plan Implementation',\n description: `Analyze the requirements and create a plan for: ${objective.description}`,\n instructions: `Please analyze the following request and create a detailed implementation plan:\n\nRequest: ${objective.description}\n\nTarget Directory: ${targetPath || 'Not specified - determine appropriate location'}\n\nYour analysis should include:\n1. Understanding of what needs to be built\n2. Technology choices and rationale\n3. Project structure and file organization\n4. Key components and their responsibilities\n5. Any external dependencies needed\n\nPlease provide a clear, structured plan that the next tasks can follow.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['analysis', 'documentation'],\n });\n tasks.push(task1);\n\n // Task 2: Implementation\n const task2 = this.createTaskForObjective('create-implementation', 'coding', {\n title: 'Implement the Solution',\n description: `Create the implementation for: ${objective.description}`,\n instructions: `Please implement the following request:\n\nRequest: ${objective.description}\n\nTarget Directory: ${targetPath || 'Create in an appropriate location'}\n\nBased on the analysis from the previous task, please:\n1. Create all necessary files and directories\n2. Implement the core functionality as requested\n3. Ensure the code is well-structured and follows best practices\n4. Include appropriate error handling\n5. Add any necessary configuration files (package.json, requirements.txt, etc.)\n\nFocus on creating a working implementation that matches the user's request exactly.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 10 * 60 * 1000,\n requiredCapabilities: ['code-generation', 'file-system'],\n dependencies: [task1.id.id],\n });\n tasks.push(task2);\n\n // Task 3: Testing\n const task3 = this.createTaskForObjective('write-tests', 'testing', {\n title: 'Create Tests',\n description: `Write tests for the implementation`,\n instructions: `Please create comprehensive tests for the implementation created in the previous task.\n\nTarget Directory: ${targetPath || 'Use the same directory as the implementation'}\n\nCreate appropriate test files that:\n1. Test the main functionality\n2. Cover edge cases\n3. Ensure the implementation works as expected\n4. Use appropriate testing frameworks for the technology stack\n5. Include both unit tests and integration tests where applicable`,\n priority: 'medium' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['testing', 'code-generation'],\n dependencies: [task2.id.id],\n });\n tasks.push(task3);\n\n // Task 4: Documentation\n const task4 = this.createTaskForObjective('create-documentation', 'documentation', {\n title: 'Create Documentation',\n description: `Document the implementation`,\n instructions: `Please create comprehensive documentation for the implemented solution.\n\nTarget Directory: ${targetPath || 'Use the same directory as the implementation'}\n\nCreate documentation that includes:\n1. README.md with project overview, setup instructions, and usage examples\n2. API documentation (if applicable)\n3. Configuration options\n4. Architecture overview\n5. Deployment instructions (if applicable)\n6. Any other relevant documentation\n\nMake sure the documentation is clear, complete, and helps users understand and use the implementation.`,\n priority: 'medium' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['documentation'],\n dependencies: [task2.id.id],\n });\n tasks.push(task4);\n } else {\n // For other strategies, create a comprehensive single task\n tasks.push(\n this.createTaskForObjective('execute-objective', 'generic', {\n title: 'Execute Objective',\n description: objective.description,\n instructions: `Please complete the following request:\n\n${objective.description}\n\n${targetPath ? `Target Directory: ${targetPath}` : ''}\n\nPlease analyze what is being requested and implement it appropriately. This may involve:\n- Creating files and directories\n- Writing code\n- Setting up configurations\n- Creating documentation\n- Any other tasks necessary to fulfill the request\n\nEnsure your implementation is complete, well-structured, and follows best practices.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 15 * 60 * 1000,\n requiredCapabilities: ['code-generation', 'file-system', 'documentation'],\n }),\n );\n }\n\n this.logger.info('Objective decomposed', {\n objectiveId: objective.id,\n taskCount: tasks.length,\n });\n\n return tasks;\n }\n\n private createTaskForObjective(id: string, type: TaskType, params: any): TaskDefinition {\n const taskId: TaskId = {\n id: generateId('task'),\n swarmId: this.swarmId.id,\n sequence: this.tasks.size + 1,\n priority: 1,\n };\n\n return {\n id: taskId,\n type,\n name: params.title,\n description: params.description,\n instructions: params.description,\n requirements: {\n capabilities: params.requiredCapabilities || [],\n tools: this.getRequiredTools(type),\n permissions: this.getRequiredPermissions(type),\n },\n constraints: {\n dependencies: params.dependencies || [],\n dependents: [],\n conflicts: [],\n maxRetries: SWARM_CONSTANTS.MAX_RETRIES,\n timeoutAfter: params.estimatedDuration || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n },\n priority: params.priority || 'medium',\n input: {\n description: params.description,\n objective: params.description,\n },\n context: {\n objectiveId: id,\n targetDir: params.targetDir,\n },\n examples: [],\n status: 'created',\n createdAt: new Date(),\n updatedAt: new Date(),\n attempts: [],\n statusHistory: [\n {\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'created' as TaskStatus,\n reason: 'Task created',\n triggeredBy: 'system',\n },\n ],\n };\n }\n\n private analyzeDependencies(tasks: TaskDefinition[]): any[] {\n // Implementation needed - analyze task dependencies\n return [];\n }\n\n private convertDependenciesToTaskDependencies(dependencies: Map<string, string[]>): any[] {\n // Convert decomposition dependencies to task dependencies format\n const result: any[] = [];\n dependencies.forEach((deps, taskId) => {\n deps.forEach((dependsOn) => {\n result.push({\n taskId,\n dependsOn,\n type: 'sequential',\n });\n });\n });\n return result;\n }\n\n private async ensureRequiredAgents(objective: SwarmObjective): Promise<void> {\n // Implementation needed - ensure required agents are available\n }\n\n private async scheduleInitialTasks(objective: SwarmObjective): Promise<void> {\n this.logger.info('Scheduling initial tasks for objective', {\n objectiveId: objective.id,\n taskCount: objective.tasks.length,\n });\n\n // Extract target directory from objective description\n const targetDirPatterns = [\n /in\\s+([^\\s]+\\/?)$/i,\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i,\n /([^\\s]+\\/[^\\s]+)$/,\n /examples\\/[^\\s]+/i,\n ];\n\n let objectiveTargetDir = null;\n for (const pattern of targetDirPatterns) {\n const match = objective.description.match(pattern);\n if (match) {\n objectiveTargetDir = match[1] || match[0];\n break;\n }\n }\n\n // Add all tasks to the tasks map\n for (const task of objective.tasks) {\n task.context.objectiveId = objective.id;\n // Propagate target directory to all tasks\n if (objectiveTargetDir && !task.context.targetDir) {\n task.context.targetDir = objectiveTargetDir;\n }\n this.tasks.set(task.id.id, task);\n\n // Track task in JSON output if enabled\n this.trackTaskInJsonOutput(task);\n }\n\n // Find tasks with no dependencies and queue them\n const initialTasks = objective.tasks.filter(\n (task) => !task.constraints.dependencies || task.constraints.dependencies.length === 0,\n );\n\n this.logger.info('Found initial tasks without dependencies', {\n count: initialTasks.length,\n tasks: initialTasks.map((t) => ({ id: t.id.id, name: t.name })),\n });\n\n // Queue initial tasks for execution\n for (const task of initialTasks) {\n task.status = 'queued';\n task.updatedAt = new Date();\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'queued' as TaskStatus,\n reason: 'Task queued for execution',\n triggeredBy: 'system',\n });\n\n // Emit task queued event\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.queued',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n }\n\n // Update objective progress\n objective.progress.totalTasks = objective.tasks.length;\n objective.progress.runningTasks = 0;\n objective.progress.completedTasks = 0;\n objective.progress.failedTasks = 0;\n }\n\n private startTaskExecutionLoop(objective: SwarmObjective): void {\n this.logger.info('Starting task execution loop for objective', {\n objectiveId: objective.id,\n });\n\n // Create an interval to process queued tasks\n const executionInterval = setInterval(async () => {\n try {\n // Check if objective is still executing\n if (objective.status !== 'executing') {\n clearInterval(executionInterval);\n return;\n }\n\n // Find queued tasks\n const queuedTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'queued',\n );\n\n // Find idle agents\n const idleAgents = Array.from(this.agents.values()).filter(\n (agent) => agent.status === 'idle',\n );\n\n if (queuedTasks.length > 0 && idleAgents.length > 0) {\n this.logger.debug('Processing queued tasks', {\n queuedTasks: queuedTasks.length,\n idleAgents: idleAgents.length,\n });\n }\n\n // Assign tasks to idle agents\n for (const task of queuedTasks) {\n if (idleAgents.length === 0) break;\n\n // Find suitable agent\n const suitableAgents = idleAgents.filter((agent) => this.agentCanHandleTask(agent, task));\n\n if (suitableAgents.length > 0) {\n // Assign to first suitable agent\n await this.assignTask(task.id.id, suitableAgents[0].id.id);\n\n // Remove agent from idle list\n const agentIndex = idleAgents.findIndex((a) => a.id.id === suitableAgents[0].id.id);\n if (agentIndex >= 0) {\n idleAgents.splice(agentIndex, 1);\n }\n }\n }\n\n // Check for completed tasks and process dependencies\n const completedTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'completed',\n );\n\n // Find tasks that can now be queued (dependencies met)\n const pendingTasks = Array.from(this.tasks.values()).filter(\n (task) =>\n task.context?.objectiveId === objective.id &&\n task.status === 'created' &&\n this.taskDependenciesMet(task, completedTasks),\n );\n\n // Queue tasks with met dependencies\n for (const task of pendingTasks) {\n task.status = 'queued';\n task.updatedAt = new Date();\n\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'queued' as TaskStatus,\n reason: 'Dependencies met, task queued',\n triggeredBy: 'system',\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.queued',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n }\n\n // Check for stuck/timed out tasks\n const runningTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'running',\n );\n\n const now = Date.now();\n for (const task of runningTasks) {\n if (task.startedAt) {\n const runtime = now - task.startedAt.getTime();\n const timeout = task.constraints?.timeoutAfter || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT;\n\n if (runtime > timeout) {\n this.logger.warn('Task timed out', {\n taskId: task.id.id,\n runtime: Math.round(runtime / 1000),\n timeout: Math.round(timeout / 1000),\n });\n\n // Mark task as failed due to timeout\n task.status = 'failed';\n task.completedAt = new Date();\n task.error = {\n type: 'TimeoutError',\n message: `Task exceeded timeout of ${timeout}ms`,\n code: 'TASK_TIMEOUT',\n context: { taskId: task.id.id, runtime },\n recoverable: true,\n retryable: true,\n };\n\n // Update agent state if assigned\n if (task.assignedTo) {\n const agent = this.agents.get(task.assignedTo.id);\n if (agent) {\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksFailed++;\n }\n }\n\n // Emit timeout event\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.failed',\n source: this.swarmId.id,\n data: { task, reason: 'timeout' },\n broadcast: false,\n processed: false,\n });\n }\n }\n }\n\n // Update objective progress\n const allTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id,\n );\n\n objective.progress.totalTasks = allTasks.length;\n objective.progress.completedTasks = allTasks.filter((t) => t.status === 'completed').length;\n objective.progress.failedTasks = allTasks.filter((t) => t.status === 'failed').length;\n objective.progress.runningTasks = allTasks.filter((t) => t.status === 'running').length;\n objective.progress.percentComplete =\n objective.progress.totalTasks > 0\n ? (objective.progress.completedTasks / objective.progress.totalTasks) * 100\n : 0;\n\n // Check if objective is complete\n if (\n objective.progress.completedTasks + objective.progress.failedTasks ===\n objective.progress.totalTasks\n ) {\n objective.status = objective.progress.failedTasks === 0 ? 'completed' : 'failed';\n objective.completedAt = new Date();\n clearInterval(executionInterval);\n\n this.logger.info('Objective completed', {\n objectiveId: objective.id,\n status: objective.status,\n completedTasks: objective.progress.completedTasks,\n failedTasks: objective.progress.failedTasks,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: objective.status === 'completed' ? 'objective.completed' : 'objective.failed',\n source: this.swarmId.id,\n data: { objective },\n broadcast: true,\n processed: false,\n });\n }\n } catch (error) {\n this.logger.error('Error in task execution loop', { error });\n }\n }, 2000); // Check every 2 seconds\n\n // Store interval reference for cleanup\n if (!this.executionIntervals) {\n this.executionIntervals = new Map();\n }\n this.executionIntervals.set(objective.id, executionInterval);\n }\n\n private taskDependenciesMet(task: TaskDefinition, completedTasks: TaskDefinition[]): boolean {\n if (!task.constraints.dependencies || task.constraints.dependencies.length === 0) {\n return true;\n }\n\n const completedTaskIds = completedTasks.map((t) => t.id.id);\n return task.constraints.dependencies.every((dep) => {\n // Handle both string and TaskId object dependencies\n const depId = typeof dep === 'string' ? dep : dep.id;\n return completedTaskIds.includes(depId);\n });\n }\n\n private getNextInstanceNumber(type: AgentType): number {\n const agentsOfType = Array.from(this.agents.values()).filter((agent) => agent.type === type);\n return agentsOfType.length + 1;\n }\n\n private getDefaultPermissions(type: AgentType): string[] {\n switch (type) {\n case 'coordinator':\n return ['read', 'write', 'execute', 'admin'];\n case 'coder':\n return ['read', 'write', 'execute'];\n case 'tester':\n return ['read', 'execute'];\n case 'reviewer':\n return ['read', 'write'];\n default:\n return ['read'];\n }\n }\n\n private async initializeAgentCapabilities(agent: AgentState): Promise<void> {\n // Set capabilities based on agent type\n switch (agent.type) {\n case 'coordinator':\n agent.capabilities.codeGeneration = false;\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = false;\n agent.capabilities.documentation = true;\n agent.capabilities.research = true;\n agent.capabilities.analysis = true;\n break;\n case 'coder':\n agent.capabilities.codeGeneration = true;\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = true;\n agent.capabilities.documentation = true;\n break;\n case 'researcher':\n agent.capabilities.research = true;\n agent.capabilities.analysis = true;\n agent.capabilities.webSearch = true;\n agent.capabilities.documentation = true;\n break;\n case 'analyst':\n agent.capabilities.analysis = true;\n agent.capabilities.research = true;\n agent.capabilities.documentation = true;\n break;\n case 'reviewer':\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = true;\n agent.capabilities.documentation = true;\n break;\n case 'tester':\n agent.capabilities.testing = true;\n agent.capabilities.codeReview = true;\n break;\n }\n }\n\n private async initializeAgentEnvironment(agent: AgentState): Promise<void> {\n // Implementation needed - setup agent environment\n }\n\n private startAgentHeartbeat(agent: AgentState): void {\n // Implementation needed - start agent heartbeat\n }\n\n private stopAgentHeartbeat(agent: AgentState): void {\n // Implementation needed - stop agent heartbeat\n }\n\n private async cleanupAgentEnvironment(agent: AgentState): Promise<void> {\n // Implementation needed - cleanup agent environment\n }\n\n private getRequiredCapabilities(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['code-generation', 'file-system'];\n case 'testing':\n return ['testing', 'code-review'];\n case 'research':\n return ['research', 'web-search'];\n case 'analysis':\n return ['analysis', 'documentation'];\n case 'review':\n return ['code-review', 'documentation'];\n case 'documentation':\n return ['documentation'];\n default:\n return [];\n }\n }\n\n private getRequiredTools(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['editor', 'compiler', 'debugger'];\n case 'testing':\n return ['test-runner', 'coverage-tool'];\n case 'research':\n return ['web-browser', 'search-engine'];\n case 'analysis':\n return ['data-tools', 'visualization'];\n default:\n return [];\n }\n }\n\n private getRequiredPermissions(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['read', 'write', 'execute'];\n case 'testing':\n return ['read', 'execute'];\n case 'research':\n return ['read', 'network'];\n default:\n return ['read'];\n }\n }\n\n private async executeTaskWithAgent(task: TaskDefinition, agent: AgentState): Promise<any> {\n this.logger.info('Executing task with agent', {\n taskId: task.id.id,\n taskName: task.name,\n agentId: agent.id.id,\n agentName: agent.name,\n });\n\n // Extract target directory from task\n const targetDir = this.extractTargetDirectory(task);\n\n try {\n // Use Claude Flow executor for full SPARC system in non-interactive mode\n const { ClaudeFlowExecutor } = await import('./claude-flow-executor.ts');\n const executor = new ClaudeFlowExecutor({\n logger: this.logger,\n claudeFlowPath: getClaudeFlowBin(),\n enableSparc: true,\n verbose: this.config.logging?.level === 'debug',\n timeoutMinutes: this.config.taskTimeoutMinutes,\n });\n\n const result = await executor.executeTask(task, agent, targetDir);\n\n this.logger.info('Task execution completed', {\n taskId: task.id.id,\n success: true,\n outputLength: JSON.stringify(result).length,\n });\n\n return result;\n } catch (error) {\n this.logger.error('Task execution failed', {\n taskId: task.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private createExecutionPrompt(task: TaskDefinition): string {\n // Create a prompt that Claude will understand\n let prompt = `# Swarm Task Execution\\n\\n`;\n prompt += `## Task: ${task.name}\\n\\n`;\n prompt += `${task.instructions || task.description}\\n\\n`;\n\n // Add working directory information if available\n const targetDir = this.extractTargetDirectory(task);\n if (targetDir) {\n prompt += `## Working Directory\\n`;\n prompt += `Please create all files in: ${targetDir}\\n\\n`;\n }\n\n if (task.input && Object.keys(task.input).length > 0) {\n prompt += `## Additional Input\\n`;\n prompt += `${JSON.stringify(task.input, null, 2)}\\n\\n`;\n }\n\n if (task.context && Object.keys(task.context).length > 0) {\n prompt += `## Context\\n`;\n prompt += `${JSON.stringify(task.context, null, 2)}\\n\\n`;\n }\n\n // Add execution guidelines\n prompt += `## Guidelines\\n`;\n prompt += `- Focus on completing this specific task\\n`;\n prompt += `- Create all necessary files and directories\\n`;\n prompt += `- Follow best practices for the technology being used\\n`;\n prompt += `- Ensure the implementation is complete and functional\\n`;\n\n return prompt;\n }\n\n private extractTargetDirectory(task: TaskDefinition): string | null {\n // Try multiple patterns to find the target directory\n const patterns = [\n /in\\s+([^\\s]+\\/?)$/i, // \"in examples/dir\" at end\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i, // \"in examples/gradio\" anywhere\n /([^\\s]+\\/[^\\s]+)$/, // \"examples/gradio\" at end\n /examples\\/[^\\s]+/i, // specifically match examples/ paths\n ];\n\n let targetDir = null;\n\n // First check task description and input\n for (const pattern of patterns) {\n const descMatch = task.description.match(pattern);\n const inputMatch = task.input?.objective?.match(pattern);\n if (descMatch || inputMatch) {\n targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];\n break;\n }\n }\n\n // If not found and task has context with targetDir, use that\n if (!targetDir && task.context?.targetDir) {\n targetDir = task.context.targetDir;\n }\n\n // If still not found, check objective description from context\n if (!targetDir && task.context?.objectiveId) {\n const objective = this.objectives.get(task.context.objectiveId);\n if (objective) {\n for (const pattern of patterns) {\n const match = objective.description.match(pattern);\n if (match) {\n targetDir = match[1] || match[0];\n break;\n }\n }\n }\n }\n\n if (targetDir) {\n // Clean up the target directory\n targetDir = targetDir.replace(/\\s+.*$/, '');\n // Resolve relative to current directory\n if (!targetDir.startsWith('/')) {\n targetDir = `${getClaudeFlowRoot()}/${targetDir}`;\n }\n }\n\n return targetDir;\n }\n\n private async executeClaudeTask(\n task: TaskDefinition,\n agent: AgentState,\n prompt: string,\n targetDir: string | null,\n ): Promise<any> {\n // Create unique instance ID for this execution\n const instanceId = `swarm-${this.swarmId.id}-${task.id.id}-${Date.now()}`;\n\n // Build Claude arguments for non-interactive execution\n const claudeArgs = [prompt];\n\n // Always skip permissions for swarm automation\n claudeArgs.push('--dangerously-skip-permissions');\n\n // Add non-interactive flags for automation\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json');\n claudeArgs.push('--verbose'); // Required when using stream-json with -p\n\n // Set working directory if specified\n if (targetDir) {\n // Ensure directory exists\n await Deno.mkdir(targetDir, { recursive: true });\n\n // Add directory context to prompt\n const enhancedPrompt = `${prompt}\\n\\n## Important: Working Directory\\nPlease ensure all files are created in: ${targetDir}`;\n claudeArgs[0] = enhancedPrompt;\n }\n\n try {\n // Check if claude command exists\n const checkCommand = new Deno.Command('which', {\n args: ['claude'],\n stdout: 'piped',\n stderr: 'piped',\n });\n const checkResult = await checkCommand.output();\n if (!checkResult.success) {\n throw new Error('Claude CLI not found. Please ensure claude is installed and in PATH.');\n }\n\n // Execute Claude with the prompt\n const command = new Deno.Command('claude', {\n args: claudeArgs,\n cwd: targetDir || process.cwd(),\n env: {\n ...Deno.env.toObject(),\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_SWARM_MODE: 'true',\n CLAUDE_SWARM_ID: this.swarmId.id,\n CLAUDE_TASK_ID: task.id.id,\n CLAUDE_AGENT_ID: agent.id.id,\n CLAUDE_WORKING_DIRECTORY: targetDir || process.cwd(),\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: `swarm-${this.swarmId.id}`,\n },\n stdin: 'null',\n stdout: 'piped',\n stderr: 'piped',\n });\n\n this.logger.info('Spawning Claude agent for task', {\n taskId: task.id.id,\n agentId: agent.id.id,\n instanceId,\n targetDir,\n });\n\n const child = command.spawn();\n const { code, stdout, stderr } = await child.output();\n\n if (code === 0) {\n const output = new TextDecoder().decode(stdout);\n this.logger.info('Claude agent completed task successfully', {\n taskId: task.id.id,\n outputLength: output.length,\n });\n\n return {\n success: true,\n output,\n instanceId,\n targetDir,\n };\n } else {\n const errorOutput = new TextDecoder().decode(stderr);\n this.logger.error(`Claude agent failed with code ${code}`, {\n taskId: task.id.id,\n error: errorOutput,\n });\n throw new Error(`Claude execution failed: ${errorOutput}`);\n }\n } catch (error) {\n this.logger.error('Failed to execute Claude agent', {\n taskId: task.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private determineToolsForTask(task: TaskDefinition, agent: AgentState): string[] {\n const tools = new Set<string>();\n\n // Basic tools for all tasks\n tools.add('View');\n tools.add('Edit');\n tools.add('Bash');\n\n // Add tools based on task type\n switch (task.type) {\n case 'coding':\n tools.add('Create');\n tools.add('Write');\n tools.add('MultiEdit');\n tools.add('Test');\n break;\n case 'testing':\n tools.add('Test');\n tools.add('View');\n break;\n case 'documentation':\n tools.add('Write');\n tools.add('Create');\n break;\n case 'analysis':\n tools.add('Analyze');\n tools.add('Search');\n break;\n case 'research':\n tools.add('WebSearch');\n tools.add('Search');\n break;\n }\n\n // Add tools based on agent capabilities\n if (agent.capabilities.fileSystem) {\n tools.add('FileSystem');\n }\n if (agent.capabilities.terminalAccess) {\n tools.add('Terminal');\n }\n if (agent.capabilities.webSearch) {\n tools.add('WebSearch');\n }\n if (agent.capabilities.apiIntegration) {\n tools.add('API');\n }\n\n return Array.from(tools);\n }\n\n private async simulateTaskExecution(\n task: TaskDefinition,\n agent: AgentState,\n prompt: string,\n ): Promise<any> {\n // Simulate different task types with actual file operations\n // Check if task has a target directory in the description or context\n let workDir = `/tmp/swarm/${this.swarmId.id}/work`;\n\n // Extract target directory from task description or input\n // Try multiple patterns to find the target directory\n const patterns = [\n /in\\s+([^\\s]+\\/?)$/i, // \"in examples/dir\" at end\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i, // \"in examples/gradio\" anywhere\n /([^\\s]+\\/[^\\s]+)$/, // \"examples/gradio\" at end\n /examples\\/[^\\s]+/i, // specifically match examples/ paths\n ];\n\n let targetDir = null;\n for (const pattern of patterns) {\n const descMatch = task.description.match(pattern);\n const inputMatch = task.input?.objective?.match(pattern);\n if (descMatch || inputMatch) {\n targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];\n break;\n }\n }\n\n if (targetDir) {\n // Clean up the target directory (remove trailing words if needed)\n targetDir = targetDir.replace(/\\s+.*$/, '');\n // Use absolute path or resolve relative to current directory\n workDir = targetDir.startsWith('/') ? targetDir : `${getClaudeFlowRoot()}/${targetDir}`;\n\n this.logger.debug('Extracted target directory', {\n original: task.description,\n targetDir,\n workDir,\n });\n }\n\n try {\n // Ensure work directory exists\n await Deno.mkdir(workDir, { recursive: true });\n\n switch (task.type) {\n case 'coding':\n return await this.executeCodeGenerationTask(task, workDir, agent);\n\n case 'analysis':\n return await this.executeAnalysisTask(task, workDir, agent);\n\n case 'documentation':\n return await this.executeDocumentationTask(task, workDir, agent);\n\n case 'testing':\n return await this.executeTestingTask(task, workDir, agent);\n\n default:\n return await this.executeGenericTask(task, workDir, agent);\n }\n } catch (error) {\n throw new Error(\n `Task execution failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n private async executeCodeGenerationTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing code generation task', { taskId: task.id.id });\n\n // Detect technology from description\n const description = task.description.toLowerCase();\n const isGradio = description.includes('gradio');\n const isPython =\n isGradio ||\n description.includes('python') ||\n description.includes('fastapi') ||\n description.includes('django');\n const isHelloWorld = description.includes('hello') && description.includes('world');\n const isRestAPI = description.includes('rest api') || description.includes('api');\n\n if (isGradio) {\n // Create a Gradio application\n return await this.createGradioApp(task, workDir);\n } else if (isPython && isRestAPI) {\n // Create a Python REST API (FastAPI)\n return await this.createPythonRestAPI(task, workDir);\n } else if (isRestAPI) {\n // Create a REST API application\n const projectName = 'rest-api';\n const projectDir = `${workDir}/${projectName}`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n // Create main API file\n const apiCode = `const express = require('express');\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Health check endpoint\napp.get('/health', (req, res) => {\n res.json({ \n status: 'healthy',\n service: 'REST API',\n swarmId: '${this.swarmId.id}',\n created: '${new Date().toISOString()}'\n });\n});\n\n// Sample endpoints\napp.get('/api/v1/items', (req, res) => {\n res.json({\n items: [\n { id: 1, name: 'Item 1', description: 'First item' },\n { id: 2, name: 'Item 2', description: 'Second item' }\n ],\n total: 2\n });\n});\n\napp.get('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({\n id,\n name: \\`Item \\${id}\\`,\n description: \\`Description for item \\${id}\\`\n });\n});\n\napp.post('/api/v1/items', (req, res) => {\n const newItem = {\n id: Date.now(),\n ...req.body,\n createdAt: new Date().toISOString()\n };\n res.status(201).json(newItem);\n});\n\napp.put('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n const updatedItem = {\n id,\n ...req.body,\n updatedAt: new Date().toISOString()\n };\n res.json(updatedItem);\n});\n\napp.delete('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({ message: \\`Item \\${id} deleted successfully\\` });\n});\n\n// Error handling middleware\napp.use((err, req, res, next) => {\n console.error(err.stack);\n res.status(500).json({ error: 'Internal server error' });\n});\n\n// Start server\napp.listen(port, () => {\n console.log(\\`REST API server running on port \\${port}\\`);\n console.log('Created by Claude Flow Swarm');\n});\n\nmodule.exports = app;\n`;\n\n await fs.writeFile(`${projectDir}/server.js`, apiCode);\n\n // Create package.json\n const packageJson = {\n name: projectName,\n version: '1.0.0',\n description: 'REST API created by Claude Flow Swarm',\n main: 'server.js',\n scripts: {\n start: 'node server.js',\n dev: 'nodemon server.js',\n test: 'jest',\n },\n keywords: ['rest', 'api', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n dependencies: {\n express: '^4.18.2',\n },\n devDependencies: {\n nodemon: '^3.0.1',\n jest: '^29.7.0',\n supertest: '^6.3.3',\n },\n swarmMetadata: {\n swarmId: this.swarmId.id,\n taskId: task.id.id,\n agentId: agent.id.id,\n created: new Date().toISOString(),\n },\n };\n\n await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));\n\n // Create README\n const readme = `# REST API\n\nThis REST API was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${this.swarmId.id}\n- Task: ${task.name}\n- Agent: ${agent.name}\n- Generated: ${new Date().toISOString()}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Usage\n\nStart the server:\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\nDevelopment mode with auto-reload:\n\\`\\`\\`bash\nnpm run dev\n\\`\\`\\`\n\n## API Endpoints\n\n- \\`GET /health\\` - Health check\n- \\`GET /api/v1/items\\` - Get all items\n- \\`GET /api/v1/items/:id\\` - Get item by ID\n- \\`POST /api/v1/items\\` - Create new item\n- \\`PUT /api/v1/items/:id\\` - Update item\n- \\`DELETE /api/v1/items/:id\\` - Delete item\n\n## Description\n${task.description}\n\n---\nCreated by Claude Flow Swarm\n`;\n\n await fs.writeFile(`${projectDir}/README.md`, readme);\n\n // Create .gitignore\n const gitignore = `node_modules/\n.env\n*.log\n.DS_Store\ncoverage/\n`;\n\n await fs.writeFile(`${projectDir}/.gitignore`, gitignore);\n\n return {\n success: true,\n output: {\n message: 'REST API created successfully',\n location: projectDir,\n files: ['server.js', 'package.json', 'README.md', '.gitignore'],\n },\n artifacts: {\n mainFile: `${projectDir}/server.js`,\n packageFile: `${projectDir}/package.json`,\n readmeFile: `${projectDir}/README.md`,\n },\n };\n } else if (isHelloWorld) {\n // Create a simple hello world application\n const projectDir = `${workDir}/hello-world`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n // Create main application file\n const mainCode = `#!/usr/bin/env node\n\n// Hello World Application\n// Generated by Claude Flow Swarm\n\nconsole.log('Hello, World!');\nconsole.log('This application was created by the Claude Flow Swarm system.');\nconsole.log('Swarm ID: ${this.swarmId.id}');\nconsole.log('Task: ${task.name}');\nconsole.log('Generated at: ${new Date().toISOString()}');\n\n// Export for testing\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = { message: 'Hello, World!' };\n}\n`;\n\n await fs.writeFile(`${projectDir}/index.js`, mainCode);\n\n // Create package.json\n const packageJson = {\n name: 'hello-world',\n version: '1.0.0',\n description: 'Hello World application created by Claude Flow Swarm',\n main: 'index.js',\n scripts: {\n start: 'node index.js',\n test: 'node test.js',\n },\n keywords: ['hello-world', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n };\n\n await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));\n\n // Create README\n const readme = `# Hello World\n\nThis application was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${this.swarmId.id}\n- Task: ${task.name}\n- Generated: ${new Date().toISOString()}\n\n## Usage\n\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\n## Description\n${task.description}\n`;\n\n await fs.writeFile(`${projectDir}/README.md`, readme);\n\n return {\n success: true,\n output: {\n message: 'Hello World application created successfully',\n location: projectDir,\n files: ['index.js', 'package.json', 'README.md'],\n },\n artifacts: {\n mainFile: `${projectDir}/index.js`,\n packageFile: `${projectDir}/package.json`,\n readmeFile: `${projectDir}/README.md`,\n },\n };\n }\n\n // For other code generation tasks, create a basic structure\n const projectDir = `${workDir}/generated-code`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n const code = `// Generated code for: ${task.name}\n// ${task.description}\n\nfunction main() {\n console.log('Executing task: ${task.name}');\n // Implementation would go here\n}\n\nmain();\n`;\n\n await fs.writeFile(`${projectDir}/main.js`, code);\n\n return {\n success: true,\n output: {\n message: 'Code generated successfully',\n location: projectDir,\n files: ['main.js'],\n },\n };\n }\n\n private async executeAnalysisTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing analysis task', { taskId: task.id.id });\n\n const analysisDir = `${workDir}/analysis`;\n await Deno.mkdir(analysisDir, { recursive: true });\n\n const analysis = {\n task: task.name,\n description: task.description,\n timestamp: new Date().toISOString(),\n findings: [\n 'Analysis point 1: Task objectives are clear',\n 'Analysis point 2: Resources are allocated',\n 'Analysis point 3: Implementation path is defined',\n ],\n recommendations: [\n 'Proceed with implementation',\n 'Monitor progress regularly',\n 'Adjust resources as needed',\n ],\n };\n\n await fs.writeFile(`${analysisDir}/analysis-report.json`, JSON.stringify(analysis, null, 2));\n\n return {\n success: true,\n output: analysis,\n artifacts: {\n report: `${analysisDir}/analysis-report.json`,\n },\n };\n }\n\n private async executeDocumentationTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing documentation task', { taskId: task.id.id });\n\n const docsDir = `${workDir}/docs`;\n await Deno.mkdir(docsDir, { recursive: true });\n\n const documentation = `# ${task.name}\n\n${task.description}\n\n## Overview\nThis documentation was generated by the Claude Flow Swarm system.\n\n## Details\n- Task ID: ${task.id.id}\n- Generated: ${new Date().toISOString()}\n- Swarm ID: ${this.swarmId.id}\n\n## Instructions\n${task.instructions}\n\n## Implementation Notes\n- This is an automated documentation generated by the swarm\n- Further details would be added based on actual implementation\n`;\n\n await fs.writeFile(`${docsDir}/documentation.md`, documentation);\n\n return {\n success: true,\n output: {\n message: 'Documentation created successfully',\n location: docsDir,\n files: ['documentation.md'],\n },\n artifacts: {\n documentation: `${docsDir}/documentation.md`,\n },\n };\n }\n\n private async executeTestingTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing testing task', { taskId: task.id.id });\n\n const testDir = `${workDir}/tests`;\n await Deno.mkdir(testDir, { recursive: true });\n\n const testCode = `// Test suite for: ${task.name}\n// ${task.description}\n\nconst assert = require('assert');\n\ndescribe('${task.name}', () => {\n it('should pass basic test', () => {\n assert.strictEqual(1 + 1, 2);\n });\n \n it('should validate implementation', () => {\n // Test implementation would go here\n assert.ok(true, 'Implementation validated');\n });\n});\n\nconsole.log('Tests completed for: ${task.name}');\n`;\n\n await fs.writeFile(`${testDir}/test.js`, testCode);\n\n return {\n success: true,\n output: {\n message: 'Test suite created successfully',\n location: testDir,\n files: ['test.js'],\n testsPassed: 2,\n testsFailed: 0,\n },\n artifacts: {\n testFile: `${testDir}/test.js`,\n },\n };\n }\n\n private async executeGenericTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing generic task', { taskId: task.id.id });\n\n const outputDir = `${workDir}/output`;\n await Deno.mkdir(outputDir, { recursive: true });\n\n const output = {\n task: task.name,\n type: task.type,\n description: task.description,\n status: 'completed',\n timestamp: new Date().toISOString(),\n result: 'Task executed successfully',\n };\n\n await fs.writeFile(`${outputDir}/result.json`, JSON.stringify(output, null, 2));\n\n return {\n success: true,\n output,\n artifacts: {\n result: `${outputDir}/result.json`,\n },\n };\n }\n\n private assessTaskQuality(task: TaskDefinition, result: any): number {\n // Implementation needed - assess task quality\n return 0.8;\n }\n\n private updateAgentMetrics(agent: AgentState, task: TaskDefinition): void {\n // Update agent performance metrics\n const executionTime = task.completedAt!.getTime() - (task.startedAt?.getTime() || 0);\n\n agent.metrics.averageExecutionTime =\n (agent.metrics.averageExecutionTime * agent.metrics.tasksCompleted + executionTime) /\n (agent.metrics.tasksCompleted + 1);\n\n agent.metrics.successRate =\n agent.metrics.tasksCompleted / (agent.metrics.tasksCompleted + agent.metrics.tasksFailed);\n }\n\n private async processDependentTasks(task: TaskDefinition): Promise<void> {\n // Implementation needed - process tasks that depend on this one\n }\n\n private isRecoverableError(error: any): boolean {\n // Implementation needed - determine if error is recoverable\n return true;\n }\n\n private isRetryableError(error: any): boolean {\n // Implementation needed - determine if error is retryable\n return true;\n }\n\n private async handleTaskFailureCascade(task: TaskDefinition): Promise<void> {\n // Implementation needed - handle failure cascade\n }\n\n private async reassignTask(taskId: string): Promise<void> {\n // Implementation needed - reassign task to different agent\n }\n\n private processHeartbeats(): void {\n const now = new Date();\n const timeout = this.config.monitoring.heartbeatInterval * 10; // Increased multiplier for long-running Claude tasks\n\n for (const agent of this.agents.values()) {\n if (agent.status === 'offline' || agent.status === 'terminated') {\n continue;\n }\n\n const timeSinceHeartbeat = now.getTime() - agent.lastHeartbeat.getTime();\n if (timeSinceHeartbeat > timeout) {\n this.logger.warn('Agent heartbeat timeout', {\n agentId: agent.id.id,\n timeSinceHeartbeat,\n });\n agent.status = 'error';\n agent.health = 0;\n }\n }\n }\n\n private updateSwarmMetrics(): void {\n // Implementation needed - update swarm-level metrics\n }\n\n private performCleanup(): void {\n // Implementation needed - perform periodic cleanup\n }\n\n private checkObjectiveCompletion(): void {\n // Implementation needed - check if objectives are complete\n }\n\n private checkObjectiveFailure(task: TaskDefinition): void {\n // Implementation needed - check if objective has failed\n }\n\n private handleAgentError(agentId: string, error: any): void {\n const agent = this.agents.get(agentId);\n if (agent) {\n agent.status = 'error';\n agent.health = 0;\n this.logger.error('Agent error', { agentId, error });\n\n // Track error in JSON output if enabled\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgentError(\n agentId,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n }\n\n // ===== JSON OUTPUT METHODS =====\n\n /**\n * Enable JSON output collection for non-interactive mode\n */\n enableJsonOutput(objective: string): void {\n if (!this.jsonOutputAggregator) {\n this.jsonOutputAggregator = new SwarmJsonOutputAggregator(\n this.swarmId.id,\n objective,\n this.config,\n );\n this.logger.info('JSON output aggregation enabled', { swarmId: this.swarmId.id });\n }\n }\n\n /**\n * Get the final JSON output for the swarm\n */\n getJsonOutput(\n status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed',\n ): string | null {\n if (!this.jsonOutputAggregator) {\n return null;\n }\n return this.jsonOutputAggregator.getJsonOutput(status);\n }\n\n /**\n * Save JSON output to file\n */\n async saveJsonOutput(\n filePath: string,\n status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed',\n ): Promise<void> {\n if (!this.jsonOutputAggregator) {\n throw new Error('JSON output aggregation not enabled');\n }\n await this.jsonOutputAggregator.saveToFile(filePath, status);\n }\n\n /**\n * Track agent activity in JSON output\n */\n private trackAgentInJsonOutput(agent: AgentState): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgent(agent);\n }\n }\n\n /**\n * Track task activity in JSON output\n */\n private trackTaskInJsonOutput(task: TaskDefinition): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addTask(task);\n }\n }\n\n /**\n * Add output to JSON aggregator\n */\n private addOutputToJsonAggregator(agentId: string, output: string): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgentOutput(agentId, output);\n }\n }\n\n /**\n * Add insight to JSON aggregator\n */\n addInsight(insight: string): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addInsight(insight);\n }\n }\n\n /**\n * Add artifact to JSON aggregator\n */\n addArtifact(key: string, artifact: any): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addArtifact(key, artifact);\n }\n }\n}\n"],"names":["EventEmitter","promises","fs","Logger","generateId","SWARM_CONSTANTS","AutoStrategy","getClaudeFlowRoot","getClaudeFlowBin","SwarmJsonOutputAggregator","SwarmCoordinator","logger","config","swarmId","agents","Map","tasks","objectives","_isRunning","status","startTime","endTime","metrics","events","lastHeartbeat","Date","jsonOutputAggregator","heartbeatTimer","monitoringTimer","cleanupTimer","executionIntervals","autoStrategy","logLevel","logging","level","logFormat","format","logDestination","destination","component","generateSwarmId","mergeWithDefaults","initializeMetrics","setupEventHandlers","info","id","mode","strategy","initialize","Error","validation","validateConfiguration","valid","errors","map","e","message","join","initializeSubsystems","startBackgroundProcesses","emitSwarmEvent","timestamp","type","source","data","broadcast","processed","error","shutdown","stopBackgroundProcesses","stopAllAgents","completeRunningTasks","saveState","duration","getTime","pause","agent","values","pauseAgent","resume","resumeAgent","createObjective","name","description","requirements","objectiveId","objective","minAgents","maxAgents","agentTypes","determineRequiredAgentTypes","estimatedDuration","maxDuration","qualityThreshold","reviewCoverage","testCoverage","reliabilityTarget","constraints","minQuality","requiredApprovals","allowedFailures","Math","floor","recoveryTime","milestones","dependencies","progress","initializeProgress","createdAt","decompositionResult","decomposeObjective","convertDependenciesToTaskDependencies","analyzeDependencies","set","taskCount","length","executeObjective","get","startedAt","ensureRequiredAgents","scheduleInitialTasks","startTaskExecutionLoop","registerAgent","capabilities","agentId","instance","getNextInstanceNumber","agentState","codeGeneration","codeReview","testing","documentation","research","analysis","webSearch","apiIntegration","fileSystem","terminalAccess","languages","frameworks","domains","tools","maxConcurrentTasks","maxMemoryUsage","DEFAULT_MEMORY_LIMIT","maxExecutionTime","DEFAULT_TASK_TIMEOUT","reliability","speed","quality","tasksCompleted","tasksFailed","averageExecutionTime","successRate","cpuUsage","memoryUsage","diskUsage","networkUsage","codeQuality","bugRate","userSatisfaction","totalUptime","lastActivity","responseTime","workload","health","autonomyLevel","learningEnabled","adaptationEnabled","maxTasksPerHour","timeoutThreshold","reportingInterval","heartbeatInterval","DEFAULT_HEARTBEAT_INTERVAL","permissions","getDefaultPermissions","trustedAgents","expertise","preferences","environment","runtime","version","workingDirectory","tempDirectory","logDirectory","apiEndpoints","credentials","availableTools","toolConfigs","endpoints","taskHistory","errorHistory","childAgents","collaborators","trackAgentInJsonOutput","initializeAgentCapabilities","startAgent","Object","keys","unregisterAgent","stopAgent","currentTask","reassignTask","delete","initializeAgentEnvironment","startAgentHeartbeat","push","String","stack","context","severity","resolved","cancelTask","stopAgentHeartbeat","cleanupAgentEnvironment","createTask","instructions","options","taskId","sequence","size","priority","task","getRequiredCapabilities","getRequiredTools","getRequiredPermissions","dependents","conflicts","maxRetries","MAX_RETRIES","timeoutAfter","input","examples","updatedAt","attempts","statusHistory","from","to","reason","triggeredBy","trackTaskInJsonOutput","assignTask","selectAgentForTask","assignedTo","assignedAt","agentName","startTaskExecution","attempt","attemptNumber","resourcesUsed","result","executeTaskWithAgent","completeTask","failTask","completedAt","output","artifacts","metadata","assessTaskQuality","completeness","accuracy","executionTime","validated","currentAttempt","undefined","updateAgentMetrics","processDependentTasks","warn","code","recoverable","isRecoverableError","retryable","isRetryableError","shouldRetry","retryDelay","pow","setTimeout","catch","retryError","handleTaskFailureCascade","availableAgents","Array","filter","agentCanHandleTask","scoredAgents","score","calculateAgentScore","sort","a","b","capabilityMatch","calculateCapabilityMatch","performanceScore","workloadScore","requiredCapabilities","matches","total","capability","agentHasCapability","caps","includes","agentType","minReliability","now","namespace","coordinationStrategy","agentSelection","taskScheduling","loadBalancing","faultTolerance","communication","maxTasks","resourceLimits","memory","cpu","DEFAULT_CPU_LIMIT","disk","DEFAULT_DISK_LIMIT","DEFAULT_QUALITY_THRESHOLD","reviewRequired","testingRequired","monitoring","metricsEnabled","loggingEnabled","tracingEnabled","metricsInterval","healthCheckInterval","retentionPeriod","maxLogSize","maxMetricPoints","alertingEnabled","alertThresholds","errorRate","exportEnabled","exportFormat","exportDestination","partitions","read","write","share","persistent","backupEnabled","distributed","consistency","cacheEnabled","compressionEnabled","security","authenticationRequired","authorizationRequired","encryptionEnabled","defaultPermissions","adminRoles","auditEnabled","auditLevel","inputValidation","outputSanitization","performance","maxConcurrency","defaultTimeout","cacheSize","cacheTtl","optimizationEnabled","adaptiveScheduling","predictiveLoading","resourcePooling","connectionPooling","memoryPooling","throughput","latency","efficiency","averageQuality","defectRate","reworkRate","resourceUtilization","costEfficiency","agentUtilization","agentSatisfaction","collaborationEffectiveness","scheduleVariance","deadlineAdherence","totalTasks","completedTasks","failedTasks","runningTasks","estimatedCompletion","timeRemaining","percentComplete","passedReviews","passedTests","costSpent","activeAgents","idleAgents","busyAgents","on","updateSwarmMetrics","checkObjectiveCompletion","checkObjectiveFailure","handleAgentError","event","slice","emit","emitSwarmEvents","success","onSwarmEvent","handler","offSwarmEvent","off","filterEvents","predicate","correlateEvents","correlationId","getSwarmId","getStatus","getAgents","getAgent","getTasks","getTask","getObjectives","getObjective","getMetrics","getEvents","isRunning","getUptime","getSwarmStatus","t","completed","failed","warnings","validatedAt","validator","setInterval","processHeartbeats","performCleanup","clearInterval","interval","clear","stopPromises","Promise","allSettled","timeout","deadline","some","resolve","getAgentTypeInstructions","getAgentCapabilities","targetDirMatch","match","targetDir","targetPath","startsWith","eachAgentPattern","requestsParallelAgents","test","createTaskForObjective","title","charAt","toUpperCase","task1","task2","task3","task4","params","forEach","deps","dependsOn","targetDirPatterns","objectiveTargetDir","pattern","initialTasks","count","executionInterval","queuedTasks","debug","suitableAgents","agentIndex","findIndex","splice","pendingTasks","taskDependenciesMet","round","allTasks","completedTaskIds","every","dep","depId","agentsOfType","taskName","extractTargetDirectory","ClaudeFlowExecutor","executor","claudeFlowPath","enableSparc","verbose","timeoutMinutes","taskTimeoutMinutes","executeTask","outputLength","JSON","stringify","createExecutionPrompt","prompt","patterns","descMatch","inputMatch","replace","executeClaudeTask","instanceId","claudeArgs","Deno","mkdir","recursive","enhancedPrompt","checkCommand","Command","args","stdout","stderr","checkResult","command","cwd","process","env","toObject","CLAUDE_INSTANCE_ID","CLAUDE_SWARM_MODE","CLAUDE_SWARM_ID","CLAUDE_TASK_ID","CLAUDE_AGENT_ID","CLAUDE_WORKING_DIRECTORY","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","stdin","child","spawn","TextDecoder","decode","errorOutput","determineToolsForTask","Set","add","simulateTaskExecution","workDir","original","executeCodeGenerationTask","executeAnalysisTask","executeDocumentationTask","executeTestingTask","executeGenericTask","toLowerCase","isGradio","isPython","isHelloWorld","isRestAPI","createGradioApp","createPythonRestAPI","projectName","projectDir","apiCode","toISOString","writeFile","packageJson","main","scripts","start","dev","keywords","author","license","express","devDependencies","nodemon","jest","supertest","swarmMetadata","created","readme","gitignore","location","files","mainFile","packageFile","readmeFile","mainCode","analysisDir","findings","recommendations","report","docsDir","testDir","testCode","testsPassed","testsFailed","testFile","outputDir","timeSinceHeartbeat","addAgentError","enableJsonOutput","getJsonOutput","saveJsonOutput","filePath","saveToFile","addAgent","addTask","addOutputToJsonAggregator","addAgentOutput","addInsight","insight","addArtifact","key","artifact"],"mappings":"AAAA,SAASA,YAAY,QAAQ,SAAS;AACtC,SAASC,YAAYC,EAAE,QAAQ,UAAU;AACzC,SAASC,MAAM,QAAQ,oBAAoB;AAC3C,SAASC,UAAU,QAAQ,sBAAsB;AACjD,SAsBEC,eAAe,QACV,aAAa;AACpB,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,oBAAoB;AACxE,SAASC,yBAAyB,QAAQ,8BAA8B;AAExE,OAAO,MAAMC,yBAAyBV;IAC5BW,OAAe;IACfC,OAAoB;IACpBC,QAAiB;IAGjBC,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C,YAAYC,GAAW,EAAEC,QAAa,EAAQ;QAC5C,IAAI,IAAI,CAACvkB,oBAAoB,EAAE;YAC7B,IAAI,CAACA,oBAAoB,CAACqkB,WAAW,CAACC,KAAKC;QAC7C;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/swarm/coordinator.ts"],"sourcesContent":["import { EventEmitter } from 'events';\nimport { promises as fs } from 'node:fs';\nimport { Logger } from '../core/logger.js';\nimport { generateId } from '../utils/helpers.js';\nimport {\n SwarmId,\n AgentId,\n TaskId,\n AgentState,\n TaskDefinition,\n SwarmObjective,\n SwarmConfig,\n SwarmStatus,\n SwarmProgress,\n SwarmResults,\n SwarmMetrics,\n SwarmMode,\n SwarmStrategy,\n AgentType,\n TaskType,\n TaskStatus,\n TaskPriority,\n SwarmEvent,\n EventType,\n SwarmEventEmitter,\n ValidationResult,\n SWARM_CONSTANTS,\n} from './types.js';\nimport { AutoStrategy } from './strategies/auto.js';\nimport { getClaudeFlowRoot, getClaudeFlowBin } from '../utils/paths.js';\nimport { SwarmJsonOutputAggregator } from './json-output-aggregator.js';\n\nexport class SwarmCoordinator extends EventEmitter implements SwarmEventEmitter {\n private logger: Logger;\n private config: SwarmConfig;\n private swarmId: SwarmId;\n\n // Core state management\n private agents: Map<string, AgentState> = new Map();\n private tasks: Map<string, TaskDefinition> = new Map();\n private objectives: Map<string, SwarmObjective> = new Map();\n\n // Execution state\n private _isRunning: boolean = false;\n private status: SwarmStatus = 'planning';\n private startTime?: Date;\n private endTime?: Date;\n\n // Performance tracking\n private metrics: SwarmMetrics;\n private events: SwarmEvent[] = [];\n private lastHeartbeat: Date = new Date();\n\n // JSON output aggregation (optional)\n private jsonOutputAggregator?: SwarmJsonOutputAggregator;\n\n // Background processes\n private heartbeatTimer?: NodeJS.Timeout;\n private monitoringTimer?: NodeJS.Timeout;\n private cleanupTimer?: NodeJS.Timeout;\n private executionIntervals?: Map<string, NodeJS.Timeout>;\n\n // Strategy instances\n private autoStrategy: AutoStrategy;\n\n constructor(config: Partial<SwarmConfig> = {}) {\n super();\n\n // Configure logger based on config or default to quiet mode\n const logLevel = (config as any).logging?.level || 'error';\n const logFormat = (config as any).logging?.format || 'text';\n const logDestination = (config as any).logging?.destination || 'console';\n\n this.logger = new Logger(\n { level: logLevel, format: logFormat, destination: logDestination },\n { component: 'SwarmCoordinator' },\n );\n this.swarmId = this.generateSwarmId();\n\n // Initialize configuration with defaults\n this.config = this.mergeWithDefaults(config);\n\n // Initialize metrics\n this.metrics = this.initializeMetrics();\n\n // Initialize strategy instances\n this.autoStrategy = new AutoStrategy(config);\n\n // Setup event handlers\n this.setupEventHandlers();\n\n this.logger.info('SwarmCoordinator initialized', {\n swarmId: this.swarmId.id,\n mode: this.config.mode,\n strategy: this.config.strategy,\n });\n }\n\n // ===== LIFECYCLE MANAGEMENT =====\n\n async initialize(): Promise<void> {\n if (this._isRunning) {\n throw new Error('Swarm coordinator already running');\n }\n\n this.logger.info('Initializing swarm coordinator...');\n this.status = 'initializing';\n\n try {\n // Validate configuration\n const validation = await this.validateConfiguration();\n if (!validation.valid) {\n throw new Error(\n `Configuration validation failed: ${validation.errors.map((e) => e.message).join(', ')}`,\n );\n }\n\n // Initialize subsystems\n await this.initializeSubsystems();\n\n // Start background processes\n this.startBackgroundProcesses();\n\n this._isRunning = true;\n this.startTime = new Date();\n this.status = 'executing';\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.started',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n\n this.logger.info('Swarm coordinator initialized successfully');\n } catch (error) {\n this.status = 'failed';\n this.logger.error('Failed to initialize swarm coordinator', { error });\n throw error;\n }\n }\n\n async shutdown(): Promise<void> {\n if (!this._isRunning) {\n return;\n }\n\n this.logger.info('Shutting down swarm coordinator...');\n this.status = 'paused';\n\n try {\n // Stop background processes\n this.stopBackgroundProcesses();\n\n // Gracefully stop all agents\n await this.stopAllAgents();\n\n // Complete any running tasks\n await this.completeRunningTasks();\n\n // Save final state\n await this.saveState();\n\n this._isRunning = false;\n this.endTime = new Date();\n this.status = 'completed';\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.completed',\n source: this.swarmId.id,\n data: {\n swarmId: this.swarmId,\n metrics: this.metrics,\n duration: this.endTime.getTime() - (this.startTime?.getTime() || 0),\n },\n broadcast: true,\n processed: false,\n });\n\n this.logger.info('Swarm coordinator shut down successfully');\n } catch (error) {\n this.logger.error('Error during swarm coordinator shutdown', { error });\n throw error;\n }\n }\n\n async pause(): Promise<void> {\n if (!this._isRunning || this.status === 'paused') {\n return;\n }\n\n this.logger.info('Pausing swarm coordinator...');\n this.status = 'paused';\n\n // Pause all agents\n for (const agent of this.agents.values()) {\n if (agent.status === 'busy') {\n await this.pauseAgent(agent.id);\n }\n }\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.paused',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n }\n\n async resume(): Promise<void> {\n if (!this._isRunning || this.status !== 'paused') {\n return;\n }\n\n this.logger.info('Resuming swarm coordinator...');\n this.status = 'executing';\n\n // Resume all paused agents\n for (const agent of this.agents.values()) {\n if (agent.status === 'paused') {\n await this.resumeAgent(agent.id);\n }\n }\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'swarm.resumed',\n source: this.swarmId.id,\n data: { swarmId: this.swarmId },\n broadcast: true,\n processed: false,\n });\n }\n\n // ===== OBJECTIVE MANAGEMENT =====\n\n async createObjective(\n name: string,\n description: string,\n strategy: SwarmStrategy = 'auto',\n requirements: Partial<SwarmObjective['requirements']> = {},\n ): Promise<string> {\n const objectiveId = generateId('objective');\n\n const objective: SwarmObjective = {\n id: objectiveId,\n name,\n description,\n strategy,\n mode: this.config.mode,\n requirements: {\n minAgents: 1,\n maxAgents: this.config.maxAgents,\n agentTypes: this.determineRequiredAgentTypes(strategy),\n estimatedDuration: 60 * 60 * 1000, // 1 hour default\n maxDuration: 4 * 60 * 60 * 1000, // 4 hours default\n qualityThreshold: this.config.qualityThreshold,\n reviewCoverage: 0.8,\n testCoverage: 0.7,\n reliabilityTarget: 0.95,\n ...requirements,\n },\n constraints: {\n minQuality: this.config.qualityThreshold,\n requiredApprovals: [],\n allowedFailures: Math.floor(this.config.maxAgents * 0.1),\n recoveryTime: 5 * 60 * 1000, // 5 minutes\n milestones: [],\n },\n tasks: [],\n dependencies: [],\n status: 'planning',\n progress: this.initializeProgress(),\n createdAt: new Date(),\n metrics: this.initializeMetrics(),\n };\n\n // Decompose objective into tasks using optimized AUTO strategy\n if (objective.strategy === 'auto') {\n const decompositionResult = await this.autoStrategy.decomposeObjective(objective);\n objective.tasks = decompositionResult.tasks;\n objective.dependencies = this.convertDependenciesToTaskDependencies(\n decompositionResult.dependencies,\n );\n } else {\n objective.tasks = await this.decomposeObjective(objective);\n objective.dependencies = this.analyzeDependencies(objective.tasks);\n }\n\n this.objectives.set(objectiveId, objective);\n\n this.logger.info('Created objective', {\n objectiveId,\n name,\n strategy,\n taskCount: objective.tasks.length,\n });\n\n return objectiveId;\n }\n\n async executeObjective(objectiveId: string): Promise<void> {\n const objective = this.objectives.get(objectiveId);\n if (!objective) {\n throw new Error(`Objective not found: ${objectiveId}`);\n }\n\n if (objective.status !== 'planning') {\n throw new Error(`Objective already ${objective.status}`);\n }\n\n this.logger.info('Executing objective', { objectiveId, name: objective.name });\n objective.status = 'executing';\n objective.startedAt = new Date();\n\n try {\n // Ensure we have required agents\n await this.ensureRequiredAgents(objective);\n\n // Schedule initial tasks\n await this.scheduleInitialTasks(objective);\n\n // Start task execution loop\n this.startTaskExecutionLoop(objective);\n } catch (error) {\n objective.status = 'failed';\n this.logger.error('Failed to execute objective', { objectiveId, error });\n throw error;\n }\n }\n\n // ===== AGENT MANAGEMENT =====\n\n async registerAgent(\n name: string,\n type: AgentType,\n capabilities: Partial<AgentState['capabilities']> = {},\n ): Promise<string> {\n const agentId: AgentId = {\n id: generateId('agent'),\n swarmId: this.swarmId.id,\n type,\n instance: this.getNextInstanceNumber(type),\n };\n\n const agentState: AgentState = {\n id: agentId,\n name,\n type,\n status: 'initializing',\n capabilities: {\n // Default capabilities\n codeGeneration: false,\n codeReview: false,\n testing: false,\n documentation: false,\n research: false,\n analysis: false,\n webSearch: false,\n apiIntegration: false,\n fileSystem: true,\n terminalAccess: true,\n languages: [],\n frameworks: [],\n domains: [],\n tools: [],\n maxConcurrentTasks: 3,\n maxMemoryUsage: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,\n maxExecutionTime: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n reliability: 0.8,\n speed: 1.0,\n quality: 0.8,\n ...capabilities,\n },\n metrics: {\n tasksCompleted: 0,\n tasksFailed: 0,\n averageExecutionTime: 0,\n successRate: 0,\n cpuUsage: 0,\n memoryUsage: 0,\n diskUsage: 0,\n networkUsage: 0,\n codeQuality: 0,\n testCoverage: 0,\n bugRate: 0,\n userSatisfaction: 0,\n totalUptime: 0,\n lastActivity: new Date(),\n responseTime: 0,\n },\n workload: 0,\n health: 1.0,\n config: {\n autonomyLevel: 0.7,\n learningEnabled: true,\n adaptationEnabled: true,\n maxTasksPerHour: 10,\n maxConcurrentTasks: capabilities.maxConcurrentTasks || 3,\n timeoutThreshold: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n reportingInterval: 30000,\n heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,\n permissions: this.getDefaultPermissions(type),\n trustedAgents: [],\n expertise: {},\n preferences: {},\n },\n environment: {\n runtime: 'deno',\n version: '1.0.0',\n workingDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}`,\n tempDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/temp`,\n logDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/logs`,\n apiEndpoints: {},\n credentials: {},\n availableTools: [],\n toolConfigs: {},\n },\n endpoints: [],\n lastHeartbeat: new Date(),\n taskHistory: [],\n errorHistory: [],\n childAgents: [],\n collaborators: [],\n };\n\n this.agents.set(agentId.id, agentState);\n\n // Track agent in JSON output if enabled\n this.trackAgentInJsonOutput(agentState);\n\n // Initialize agent capabilities based on type\n await this.initializeAgentCapabilities(agentState);\n\n // Start agent\n await this.startAgent(agentId.id);\n\n this.logger.info('Registered agent', {\n agentId: agentId.id,\n name,\n type,\n capabilities: Object.keys(capabilities),\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.created',\n source: agentId.id,\n data: { agent: agentState },\n broadcast: false,\n processed: false,\n });\n\n return agentId.id;\n }\n\n async unregisterAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return;\n }\n\n this.logger.info('Unregistering agent', { agentId, name: agent.name });\n\n // Stop agent gracefully\n await this.stopAgent(agentId);\n\n // Reassign any active tasks\n if (agent.currentTask) {\n await this.reassignTask(agent.currentTask.id);\n }\n\n // Remove from agents map\n this.agents.delete(agentId);\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.stopped',\n source: agentId,\n data: { agentId },\n broadcast: false,\n processed: false,\n });\n }\n\n async startAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n throw new Error(`Agent not found: ${agentId}`);\n }\n\n if (agent.status !== 'initializing' && agent.status !== 'offline') {\n return;\n }\n\n this.logger.info('Starting agent', { agentId, name: agent.name });\n\n try {\n // Initialize agent environment\n await this.initializeAgentEnvironment(agent);\n\n // Start agent heartbeat\n this.startAgentHeartbeat(agent);\n\n agent.status = 'idle';\n agent.lastHeartbeat = new Date();\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'agent.started',\n source: agentId,\n data: { agent },\n broadcast: false,\n processed: false,\n });\n } catch (error) {\n agent.status = 'error';\n agent.errorHistory.push({\n timestamp: new Date(),\n type: 'startup_error',\n message: error instanceof Error ? error.message : String(error),\n stack: error.stack,\n context: { agentId },\n severity: 'high',\n resolved: false,\n });\n\n this.logger.error('Failed to start agent', { agentId, error });\n throw error;\n }\n }\n\n async stopAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return;\n }\n\n if (agent.status === 'offline' || agent.status === 'terminated') {\n return;\n }\n\n this.logger.info('Stopping agent', { agentId, name: agent.name });\n\n agent.status = 'terminating';\n\n try {\n // Cancel current task if any\n if (agent.currentTask) {\n await this.cancelTask(agent.currentTask.id, 'Agent stopping');\n }\n\n // Stop heartbeat\n this.stopAgentHeartbeat(agent);\n\n // Cleanup agent environment\n await this.cleanupAgentEnvironment(agent);\n\n agent.status = 'terminated';\n } catch (error) {\n agent.status = 'error';\n this.logger.error('Error stopping agent', { agentId, error });\n }\n }\n\n async pauseAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent || agent.status !== 'busy') {\n return;\n }\n\n agent.status = 'paused';\n this.logger.info('Paused agent', { agentId });\n }\n\n async resumeAgent(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent || agent.status !== 'paused') {\n return;\n }\n\n agent.status = 'busy';\n this.logger.info('Resumed agent', { agentId });\n }\n\n // ===== TASK MANAGEMENT =====\n\n async createTask(\n type: TaskType,\n name: string,\n description: string,\n instructions: string,\n options: Partial<TaskDefinition> = {},\n ): Promise<string> {\n const taskId: TaskId = {\n id: generateId('task'),\n swarmId: this.swarmId.id,\n sequence: this.tasks.size + 1,\n priority: 1,\n };\n\n const task: TaskDefinition = {\n id: taskId,\n type,\n name,\n description,\n instructions,\n requirements: {\n capabilities: this.getRequiredCapabilities(type),\n tools: this.getRequiredTools(type),\n permissions: this.getRequiredPermissions(type),\n ...options.requirements,\n },\n constraints: {\n dependencies: [],\n dependents: [],\n conflicts: [],\n maxRetries: SWARM_CONSTANTS.MAX_RETRIES,\n timeoutAfter: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n ...options.constraints,\n },\n priority: 'normal',\n input: options.input || {},\n context: options.context || {},\n examples: options.examples || [],\n status: 'created',\n createdAt: new Date(),\n updatedAt: new Date(),\n attempts: [],\n statusHistory: [\n {\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'created' as TaskStatus,\n reason: 'Task created',\n triggeredBy: 'system',\n },\n ],\n ...options,\n };\n\n this.tasks.set(taskId.id, task);\n\n // Track task in JSON output if enabled\n this.trackTaskInJsonOutput(task);\n\n this.logger.info('Created task', {\n taskId: taskId.id,\n type,\n name,\n priority: task.priority,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.created',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n\n return taskId.id;\n }\n\n async assignTask(taskId: string, agentId?: string): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n if (task.status !== 'created' && task.status !== 'queued') {\n throw new Error(`Task cannot be assigned, current status: ${task.status}`);\n }\n\n // Select agent if not specified\n if (!agentId) {\n agentId = await this.selectAgentForTask(task);\n if (!agentId) {\n throw new Error('No suitable agent available for task');\n }\n }\n\n const agent = this.agents.get(agentId);\n if (!agent) {\n throw new Error(`Agent not found: ${agentId}`);\n }\n\n if (agent.status !== 'idle') {\n throw new Error(`Agent not available: ${agent.status}`);\n }\n\n // Assign task\n task.assignedTo = agent.id;\n task.assignedAt = new Date();\n task.status = 'assigned';\n\n agent.currentTask = task.id;\n agent.status = 'busy';\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: task.statusHistory[task.statusHistory.length - 1].to,\n to: 'assigned',\n reason: `Assigned to agent ${agent.name}`,\n triggeredBy: 'system',\n });\n\n this.logger.info('Assigned task', {\n taskId,\n agentId,\n agentName: agent.name,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.assigned',\n source: agentId,\n data: { task, agent },\n broadcast: false,\n processed: false,\n });\n\n // Start task execution\n await this.startTaskExecution(task);\n }\n\n async startTaskExecution(task: TaskDefinition): Promise<void> {\n if (!task.assignedTo) {\n throw new Error('Task not assigned to any agent');\n }\n\n const agent = this.agents.get(task.assignedTo.id);\n if (!agent) {\n throw new Error(`Agent not found: ${task.assignedTo.id}`);\n }\n\n this.logger.info('Starting task execution', {\n taskId: task.id.id,\n agentId: agent.id.id,\n });\n\n task.status = 'running';\n task.startedAt = new Date();\n\n // Create attempt record\n const attempt = {\n attemptNumber: task.attempts.length + 1,\n agent: agent.id,\n startedAt: new Date(),\n status: 'running' as TaskStatus,\n resourcesUsed: {},\n };\n task.attempts.push(attempt);\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'assigned',\n to: 'running',\n reason: 'Task execution started',\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.started',\n source: agent.id.id,\n data: { task, agent, attempt },\n broadcast: false,\n processed: false,\n });\n\n try {\n // Execute task (this would spawn actual Claude process)\n const result = await this.executeTaskWithAgent(task, agent);\n await this.completeTask(task.id.id, result);\n } catch (error) {\n await this.failTask(task.id.id, error);\n }\n }\n\n async completeTask(taskId: string, result: any): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n if (!agent) {\n throw new Error('Task not assigned to any agent');\n }\n\n this.logger.info('Completing task', { taskId, agentId: agent.id.id });\n\n task.status = 'completed';\n task.completedAt = new Date();\n task.result = {\n output: result,\n artifacts: {},\n metadata: {},\n quality: this.assessTaskQuality(task, result),\n completeness: 1.0,\n accuracy: 1.0,\n executionTime: task.completedAt.getTime() - (task.startedAt?.getTime() || 0),\n resourcesUsed: {},\n validated: false,\n };\n\n // Update attempt\n const currentAttempt = task.attempts[task.attempts.length - 1];\n if (currentAttempt) {\n currentAttempt.completedAt = new Date();\n currentAttempt.status = 'completed';\n currentAttempt.result = task.result;\n }\n\n // Update agent state\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksCompleted++;\n agent.metrics.lastActivity = new Date();\n agent.taskHistory.push(task.id);\n\n // Update agent metrics\n this.updateAgentMetrics(agent, task);\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'completed',\n reason: 'Task completed successfully',\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.completed',\n source: agent.id.id,\n data: { task, agent, result: task.result },\n broadcast: false,\n processed: false,\n });\n\n // Check for dependent tasks\n await this.processDependentTasks(task);\n }\n\n async failTask(taskId: string, error: any): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n if (!agent) {\n throw new Error('Task not assigned to any agent');\n }\n\n this.logger.warn('Task failed', {\n taskId,\n agentId: agent.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n\n task.error = {\n type: error.constructor.name,\n message: error instanceof Error ? error.message : String(error),\n code: error.code,\n stack: error.stack,\n context: { taskId, agentId: agent.id.id },\n recoverable: this.isRecoverableError(error),\n retryable: this.isRetryableError(error),\n };\n\n // Update attempt\n const currentAttempt = task.attempts[task.attempts.length - 1];\n if (currentAttempt) {\n currentAttempt.completedAt = new Date();\n currentAttempt.status = 'failed';\n currentAttempt.error = task.error;\n }\n\n // Update agent state\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksFailed++;\n agent.metrics.lastActivity = new Date();\n\n // Add to error history\n agent.errorHistory.push({\n timestamp: new Date(),\n type: 'task_failure',\n message: error instanceof Error ? error.message : String(error),\n stack: error.stack,\n context: { taskId },\n severity: 'medium',\n resolved: false,\n });\n\n // Determine if we should retry\n const shouldRetry =\n task.error.retryable &&\n task.attempts.length < (task.constraints.maxRetries || SWARM_CONSTANTS.MAX_RETRIES);\n\n if (shouldRetry) {\n task.status = 'retrying';\n task.assignedTo = undefined;\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'retrying',\n reason: `Task failed, will retry: ${error instanceof Error ? error.message : String(error)}`,\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.retried',\n source: agent.id.id,\n data: { task, error: task.error, attempt: task.attempts.length },\n broadcast: false,\n processed: false,\n });\n\n // Schedule retry with exponential backoff\n const retryDelay = Math.pow(2, task.attempts.length) * 1000;\n setTimeout(() => {\n this.assignTask(taskId).catch((retryError) => {\n this.logger.error('Failed to retry task', { taskId, retryError });\n });\n }, retryDelay);\n } else {\n task.status = 'failed';\n task.completedAt = new Date();\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'running',\n to: 'failed',\n reason: `Task failed permanently: ${error instanceof Error ? error.message : String(error)}`,\n triggeredBy: agent.id,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.failed',\n source: agent.id.id,\n data: { task, error: task.error },\n broadcast: false,\n processed: false,\n });\n\n // Handle failure cascade\n await this.handleTaskFailureCascade(task);\n }\n }\n\n async cancelTask(taskId: string, reason: string): Promise<void> {\n const task = this.tasks.get(taskId);\n if (!task) {\n throw new Error(`Task not found: ${taskId}`);\n }\n\n const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;\n\n this.logger.info('Cancelling task', { taskId, reason });\n\n task.status = 'cancelled';\n task.completedAt = new Date();\n\n if (agent) {\n agent.status = 'idle';\n agent.currentTask = undefined;\n }\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: task.statusHistory[task.statusHistory.length - 1].to,\n to: 'cancelled',\n reason: `Task cancelled: ${reason}`,\n triggeredBy: 'system',\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.cancelled',\n source: this.swarmId.id,\n data: { task, reason },\n broadcast: false,\n processed: false,\n });\n }\n\n // ===== ADVANCED FEATURES =====\n\n async selectAgentForTask(task: TaskDefinition): Promise<string | null> {\n const availableAgents = Array.from(this.agents.values()).filter(\n (agent) => agent.status === 'idle' && this.agentCanHandleTask(agent, task),\n );\n\n if (availableAgents.length === 0) {\n return null;\n }\n\n // Score agents based on multiple criteria\n const scoredAgents = availableAgents.map((agent) => ({\n agent,\n score: this.calculateAgentScore(agent, task),\n }));\n\n // Sort by score (highest first)\n scoredAgents.sort((a, b) => b.score - a.score);\n\n return scoredAgents[0].agent.id.id;\n }\n\n private calculateAgentScore(agent: AgentState, task: TaskDefinition): number {\n let score = 0;\n\n // Capability match (40% weight)\n const capabilityMatch = this.calculateCapabilityMatch(agent, task);\n score += capabilityMatch * 0.4;\n\n // Performance history (30% weight)\n const performanceScore = agent.metrics.successRate * agent.capabilities.reliability;\n score += performanceScore * 0.3;\n\n // Current workload (20% weight)\n const workloadScore = 1 - agent.workload;\n score += workloadScore * 0.2;\n\n // Quality rating (10% weight)\n score += agent.capabilities.quality * 0.1;\n\n return score;\n }\n\n private calculateCapabilityMatch(agent: AgentState, task: TaskDefinition): number {\n const requiredCapabilities = task.requirements.capabilities;\n let matches = 0;\n const total = requiredCapabilities.length;\n\n for (const capability of requiredCapabilities) {\n if (this.agentHasCapability(agent, capability)) {\n matches++;\n }\n }\n\n return total > 0 ? matches / total : 1.0;\n }\n\n private agentHasCapability(agent: AgentState, capability: string): boolean {\n const caps = agent.capabilities;\n\n switch (capability) {\n case 'code-generation':\n return caps.codeGeneration;\n case 'code-review':\n return caps.codeReview;\n case 'testing':\n return caps.testing;\n case 'documentation':\n return caps.documentation;\n case 'research':\n return caps.research;\n case 'analysis':\n return caps.analysis;\n case 'web-search':\n return caps.webSearch;\n case 'api-integration':\n return caps.apiIntegration;\n case 'file-system':\n return caps.fileSystem;\n case 'terminal-access':\n return caps.terminalAccess;\n case 'validation':\n return caps.testing; // Validation is part of testing capability\n default:\n return (\n caps.domains.includes(capability) ||\n caps.languages.includes(capability) ||\n caps.frameworks.includes(capability) ||\n caps.tools.includes(capability)\n );\n }\n }\n\n private agentCanHandleTask(agent: AgentState, task: TaskDefinition): boolean {\n // Check if agent type is suitable\n if (task.requirements.agentType && agent.type !== task.requirements.agentType) {\n return false;\n }\n\n // Check if agent has required capabilities\n for (const capability of task.requirements.capabilities) {\n if (!this.agentHasCapability(agent, capability)) {\n return false;\n }\n }\n\n // Check reliability requirement\n if (\n task.requirements.minReliability &&\n agent.capabilities.reliability < task.requirements.minReliability\n ) {\n return false;\n }\n\n // Check if agent has capacity\n if (agent.workload >= 1.0) {\n return false;\n }\n\n return true;\n }\n\n // ===== HELPER METHODS =====\n\n private generateSwarmId(): SwarmId {\n return {\n id: generateId('swarm'),\n timestamp: Date.now(),\n namespace: 'default',\n };\n }\n\n private mergeWithDefaults(config: Partial<SwarmConfig>): SwarmConfig {\n return {\n name: 'Unnamed Swarm',\n description: 'Auto-generated swarm',\n version: '1.0.0',\n mode: 'centralized',\n strategy: 'auto',\n coordinationStrategy: {\n name: 'default',\n description: 'Default coordination strategy',\n agentSelection: 'capability-based',\n taskScheduling: 'priority',\n loadBalancing: 'work-stealing',\n faultTolerance: 'retry',\n communication: 'event-driven',\n },\n maxAgents: 10,\n maxTasks: 100,\n maxDuration: 4 * 60 * 60 * 1000, // 4 hours\n resourceLimits: {\n memory: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,\n cpu: SWARM_CONSTANTS.DEFAULT_CPU_LIMIT,\n disk: SWARM_CONSTANTS.DEFAULT_DISK_LIMIT,\n },\n qualityThreshold: SWARM_CONSTANTS.DEFAULT_QUALITY_THRESHOLD,\n reviewRequired: true,\n testingRequired: true,\n monitoring: {\n metricsEnabled: true,\n loggingEnabled: true,\n tracingEnabled: false,\n metricsInterval: 10000,\n heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,\n healthCheckInterval: 30000,\n retentionPeriod: 24 * 60 * 60 * 1000, // 24 hours\n maxLogSize: 100 * 1024 * 1024, // 100MB\n maxMetricPoints: 10000,\n alertingEnabled: true,\n alertThresholds: {\n errorRate: 0.1,\n responseTime: 5000,\n memoryUsage: 0.8,\n cpuUsage: 0.8,\n },\n exportEnabled: false,\n exportFormat: 'json',\n exportDestination: '/tmp/swarm-metrics',\n },\n memory: {\n namespace: 'default',\n partitions: [],\n permissions: {\n read: 'swarm',\n write: 'team',\n delete: 'private',\n share: 'team',\n },\n persistent: true,\n backupEnabled: true,\n distributed: false,\n consistency: 'eventual',\n cacheEnabled: true,\n compressionEnabled: false,\n },\n security: {\n authenticationRequired: false,\n authorizationRequired: false,\n encryptionEnabled: false,\n defaultPermissions: ['read', 'write'],\n adminRoles: ['admin', 'coordinator'],\n auditEnabled: true,\n auditLevel: 'info',\n inputValidation: true,\n outputSanitization: true,\n },\n performance: {\n maxConcurrency: 10,\n defaultTimeout: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n cacheEnabled: true,\n cacheSize: 100,\n cacheTtl: 3600000, // 1 hour\n optimizationEnabled: true,\n adaptiveScheduling: true,\n predictiveLoading: false,\n resourcePooling: true,\n connectionPooling: true,\n memoryPooling: false,\n },\n ...config,\n };\n }\n\n private initializeMetrics(): SwarmMetrics {\n return {\n throughput: 0,\n latency: 0,\n efficiency: 0,\n reliability: 0,\n averageQuality: 0,\n defectRate: 0,\n reworkRate: 0,\n resourceUtilization: {},\n costEfficiency: 0,\n agentUtilization: 0,\n agentSatisfaction: 0,\n collaborationEffectiveness: 0,\n scheduleVariance: 0,\n deadlineAdherence: 0,\n };\n }\n\n private initializeProgress(): SwarmProgress {\n return {\n totalTasks: 0,\n completedTasks: 0,\n failedTasks: 0,\n runningTasks: 0,\n estimatedCompletion: new Date(),\n timeRemaining: 0,\n percentComplete: 0,\n averageQuality: 0,\n passedReviews: 0,\n passedTests: 0,\n resourceUtilization: {},\n costSpent: 0,\n activeAgents: 0,\n idleAgents: 0,\n busyAgents: 0,\n };\n }\n\n // ===== EVENT HANDLING =====\n\n private setupEventHandlers(): void {\n // Handle agent heartbeats\n this.on('agent.heartbeat', (data: any) => {\n const agent = this.agents.get(data.agentId);\n if (agent) {\n agent.lastHeartbeat = new Date();\n agent.health = data.health || 1.0;\n agent.metrics = { ...agent.metrics, ...data.metrics };\n }\n });\n\n // Handle task completion events\n this.on('task.completed', (data: any) => {\n this.updateSwarmMetrics();\n this.checkObjectiveCompletion();\n });\n\n // Handle task failure events\n this.on('task.failed', (data: any) => {\n this.updateSwarmMetrics();\n this.checkObjectiveFailure(data.task);\n });\n\n // Handle agent errors\n this.on('agent.error', (data: any) => {\n this.handleAgentError(data.agentId, data.error);\n });\n }\n\n // ===== SWARM EVENT EMITTER IMPLEMENTATION =====\n\n emitSwarmEvent(event: SwarmEvent): boolean {\n this.events.push(event);\n\n // Limit event history\n if (this.events.length > 1000) {\n this.events = this.events.slice(-500);\n }\n\n return this.emit(event.type, event);\n }\n\n emitSwarmEvents(events: SwarmEvent[]): boolean {\n let success = true;\n for (const event of events) {\n if (!this.emitSwarmEvent(event)) {\n success = false;\n }\n }\n return success;\n }\n\n onSwarmEvent(type: EventType, handler: (event: SwarmEvent) => void): this {\n return this.on(type, handler);\n }\n\n offSwarmEvent(type: EventType, handler: (event: SwarmEvent) => void): this {\n return this.off(type, handler);\n }\n\n filterEvents(predicate: (event: SwarmEvent) => boolean): SwarmEvent[] {\n return this.events.filter(predicate);\n }\n\n correlateEvents(correlationId: string): SwarmEvent[] {\n return this.events.filter((event) => event.correlationId === correlationId);\n }\n\n // ===== PUBLIC API METHODS =====\n\n getSwarmId(): SwarmId {\n return this.swarmId;\n }\n\n getStatus(): SwarmStatus {\n return this.status;\n }\n\n getAgents(): AgentState[] {\n return Array.from(this.agents.values());\n }\n\n getAgent(agentId: string): AgentState | undefined {\n return this.agents.get(agentId);\n }\n\n getTasks(): TaskDefinition[] {\n return Array.from(this.tasks.values());\n }\n\n getTask(taskId: string): TaskDefinition | undefined {\n return this.tasks.get(taskId);\n }\n\n getObjectives(): SwarmObjective[] {\n return Array.from(this.objectives.values());\n }\n\n getObjective(objectiveId: string): SwarmObjective | undefined {\n return this.objectives.get(objectiveId);\n }\n\n getMetrics(): SwarmMetrics {\n return { ...this.metrics };\n }\n\n getEvents(): SwarmEvent[] {\n return [...this.events];\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n getUptime(): number {\n if (!this.startTime) return 0;\n const endTime = this.endTime || new Date();\n return endTime.getTime() - this.startTime.getTime();\n }\n\n getSwarmStatus(): {\n status: SwarmStatus;\n objectives: number;\n tasks: { completed: number; failed: number; total: number };\n agents: { total: number };\n } {\n const tasks = Array.from(this.tasks.values());\n const completedTasks = tasks.filter((t) => t.status === 'completed').length;\n const failedTasks = tasks.filter((t) => t.status === 'failed').length;\n\n return {\n status: this.status,\n objectives: this.objectives.size,\n tasks: {\n completed: completedTasks,\n failed: failedTasks,\n total: tasks.length,\n },\n agents: {\n total: this.agents.size,\n },\n };\n }\n\n // ===== STUB METHODS (TO BE IMPLEMENTED) =====\n\n private async validateConfiguration(): Promise<ValidationResult> {\n // Implementation needed\n return {\n valid: true,\n errors: [],\n warnings: [],\n validatedAt: new Date(),\n validator: 'SwarmCoordinator',\n context: {},\n };\n }\n\n private async initializeSubsystems(): Promise<void> {\n // Implementation needed\n }\n\n private startBackgroundProcesses(): void {\n // Start heartbeat monitoring\n this.heartbeatTimer = setInterval(() => {\n this.processHeartbeats();\n }, this.config.monitoring.heartbeatInterval);\n\n // Start performance monitoring\n this.monitoringTimer = setInterval(() => {\n this.updateSwarmMetrics();\n }, this.config.monitoring.metricsInterval);\n\n // Start cleanup process\n this.cleanupTimer = setInterval(() => {\n this.performCleanup();\n }, 60000); // Every minute\n }\n\n private stopBackgroundProcesses(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n }\n if (this.monitoringTimer) {\n clearInterval(this.monitoringTimer);\n this.monitoringTimer = undefined;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n // Stop all execution intervals\n if (this.executionIntervals) {\n for (const [objectiveId, interval] of this.executionIntervals) {\n clearInterval(interval);\n }\n this.executionIntervals.clear();\n }\n }\n\n private async stopAllAgents(): Promise<void> {\n const stopPromises = Array.from(this.agents.keys()).map((agentId) => this.stopAgent(agentId));\n await Promise.allSettled(stopPromises);\n }\n\n private async completeRunningTasks(): Promise<void> {\n const runningTasks = Array.from(this.tasks.values()).filter(\n (task) => task.status === 'running',\n );\n\n // Wait for tasks to complete or timeout\n const timeout = 30000; // 30 seconds\n const deadline = Date.now() + timeout;\n\n while (runningTasks.some((task) => task.status === 'running') && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n\n // Cancel any remaining running tasks\n for (const task of runningTasks) {\n if (task.status === 'running') {\n await this.cancelTask(task.id.id, 'Swarm shutdown');\n }\n }\n }\n\n private async saveState(): Promise<void> {\n // Implementation needed - save swarm state to persistence layer\n }\n\n private determineRequiredAgentTypes(strategy: SwarmStrategy): AgentType[] {\n switch (strategy) {\n case 'research':\n return ['researcher', 'analyst'];\n case 'development':\n return ['coder', 'tester', 'reviewer'];\n case 'analysis':\n return ['analyst', 'researcher'];\n case 'testing':\n return ['tester', 'coder'];\n case 'optimization':\n return ['analyst', 'coder'];\n case 'maintenance':\n return ['coder', 'monitor'];\n default:\n return ['coordinator', 'coder', 'analyst'];\n }\n }\n\n private getAgentTypeInstructions(agentType: string): string {\n switch (agentType) {\n case 'coder':\n return '- Focus on implementation, code quality, and best practices\\n- Create clean, maintainable code\\n- Consider architecture and design patterns';\n case 'tester':\n return '- Focus on testing, edge cases, and quality assurance\\n- Create comprehensive test suites\\n- Identify potential bugs and issues';\n case 'analyst':\n return '- Focus on analysis, research, and understanding\\n- Break down complex problems\\n- Provide insights and recommendations';\n case 'researcher':\n return '- Focus on gathering information and best practices\\n- Research existing solutions and patterns\\n- Document findings and recommendations';\n case 'reviewer':\n return '- Focus on code review and quality checks\\n- Identify improvements and optimizations\\n- Ensure standards compliance';\n case 'coordinator':\n return '- Focus on coordination and integration\\n- Ensure all parts work together\\n- Manage dependencies and interfaces';\n case 'monitor':\n return '- Focus on monitoring and observability\\n- Set up logging and metrics\\n- Ensure system health tracking';\n default:\n return '- Execute the task to the best of your ability\\n- Follow best practices for your domain';\n }\n }\n\n private getAgentCapabilities(agentType: string): string[] {\n switch (agentType) {\n case 'coder':\n return ['code-generation', 'file-system', 'debugging'];\n case 'tester':\n return ['testing', 'code-generation', 'analysis'];\n case 'analyst':\n return ['analysis', 'documentation', 'research'];\n case 'researcher':\n return ['research', 'documentation', 'analysis'];\n case 'reviewer':\n return ['code-review', 'analysis', 'documentation'];\n case 'coordinator':\n return ['coordination', 'analysis', 'documentation'];\n case 'monitor':\n return ['monitoring', 'analysis', 'documentation'];\n default:\n return ['analysis', 'documentation'];\n }\n }\n\n private async decomposeObjective(objective: SwarmObjective): Promise<TaskDefinition[]> {\n // Decompose objective into tasks with clear instructions for Claude\n this.logger.info('Decomposing objective', {\n objectiveId: objective.id,\n description: objective.description,\n });\n\n const tasks: TaskDefinition[] = [];\n\n // Extract target directory from objective\n const targetDirMatch = objective.description.match(\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)|([^\\s]+\\/[^\\s]+)$/,\n );\n const targetDir = targetDirMatch ? targetDirMatch[1] || targetDirMatch[2] : null;\n const targetPath = targetDir\n ? targetDir.startsWith('/')\n ? targetDir\n : `${getClaudeFlowRoot()}/${targetDir}`\n : null;\n\n // Check if objective requests \"each agent\" or \"each agent type\" for parallel execution\n const eachAgentPattern = /\\beach\\s+agent(?:\\s+type)?\\b/i;\n const requestsParallelAgents = eachAgentPattern.test(objective.description);\n\n // Create tasks with specific prompts for Claude\n if (requestsParallelAgents && this.config.mode === 'parallel') {\n // Create parallel tasks for each agent type\n const agentTypes = this.determineRequiredAgentTypes(objective.strategy);\n this.logger.info('Creating parallel tasks for each agent type', {\n agentTypes,\n mode: this.config.mode,\n });\n\n for (const agentType of agentTypes) {\n const taskId = this.createTaskForObjective(`${agentType}-task`, agentType as TaskType, {\n title: `${agentType.charAt(0).toUpperCase() + agentType.slice(1)} Agent Task`,\n description: `${agentType} agent executing: ${objective.description}`,\n instructions: `You are a ${agentType} agent. Please execute the following task from your perspective:\n\n${objective.description}\n\n${targetPath ? `Target Directory: ${targetPath}` : ''}\n\nAs a ${agentType} agent, focus on aspects relevant to your role:\n${this.getAgentTypeInstructions(agentType)}\n\nWork independently but be aware that other agents are working on this same objective from their perspectives.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 10 * 60 * 1000,\n requiredCapabilities: this.getAgentCapabilities(agentType),\n });\n tasks.push(taskId);\n }\n } else if (objective.strategy === 'development') {\n // Task 1: Analyze and Plan\n const task1 = this.createTaskForObjective('analyze-requirements', 'analysis', {\n title: 'Analyze Requirements and Plan Implementation',\n description: `Analyze the requirements and create a plan for: ${objective.description}`,\n instructions: `Please analyze the following request and create a detailed implementation plan:\n\nRequest: ${objective.description}\n\nTarget Directory: ${targetPath || 'Not specified - determine appropriate location'}\n\nYour analysis should include:\n1. Understanding of what needs to be built\n2. Technology choices and rationale\n3. Project structure and file organization\n4. Key components and their responsibilities\n5. Any external dependencies needed\n\nPlease provide a clear, structured plan that the next tasks can follow.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['analysis', 'documentation'],\n });\n tasks.push(task1);\n\n // Task 2: Implementation\n const task2 = this.createTaskForObjective('create-implementation', 'coding', {\n title: 'Implement the Solution',\n description: `Create the implementation for: ${objective.description}`,\n instructions: `Please implement the following request:\n\nRequest: ${objective.description}\n\nTarget Directory: ${targetPath || 'Create in an appropriate location'}\n\nBased on the analysis from the previous task, please:\n1. Create all necessary files and directories\n2. Implement the core functionality as requested\n3. Ensure the code is well-structured and follows best practices\n4. Include appropriate error handling\n5. Add any necessary configuration files (package.json, requirements.txt, etc.)\n\nFocus on creating a working implementation that matches the user's request exactly.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 10 * 60 * 1000,\n requiredCapabilities: ['code-generation', 'file-system'],\n dependencies: [task1.id.id],\n });\n tasks.push(task2);\n\n // Task 3: Testing\n const task3 = this.createTaskForObjective('write-tests', 'testing', {\n title: 'Create Tests',\n description: `Write tests for the implementation`,\n instructions: `Please create comprehensive tests for the implementation created in the previous task.\n\nTarget Directory: ${targetPath || 'Use the same directory as the implementation'}\n\nCreate appropriate test files that:\n1. Test the main functionality\n2. Cover edge cases\n3. Ensure the implementation works as expected\n4. Use appropriate testing frameworks for the technology stack\n5. Include both unit tests and integration tests where applicable`,\n priority: 'medium' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['testing', 'code-generation'],\n dependencies: [task2.id.id],\n });\n tasks.push(task3);\n\n // Task 4: Documentation\n const task4 = this.createTaskForObjective('create-documentation', 'documentation', {\n title: 'Create Documentation',\n description: `Document the implementation`,\n instructions: `Please create comprehensive documentation for the implemented solution.\n\nTarget Directory: ${targetPath || 'Use the same directory as the implementation'}\n\nCreate documentation that includes:\n1. README.md with project overview, setup instructions, and usage examples\n2. API documentation (if applicable)\n3. Configuration options\n4. Architecture overview\n5. Deployment instructions (if applicable)\n6. Any other relevant documentation\n\nMake sure the documentation is clear, complete, and helps users understand and use the implementation.`,\n priority: 'medium' as TaskPriority,\n estimatedDuration: 5 * 60 * 1000,\n requiredCapabilities: ['documentation'],\n dependencies: [task2.id.id],\n });\n tasks.push(task4);\n } else {\n // For other strategies, create a comprehensive single task\n tasks.push(\n this.createTaskForObjective('execute-objective', 'generic', {\n title: 'Execute Objective',\n description: objective.description,\n instructions: `Please complete the following request:\n\n${objective.description}\n\n${targetPath ? `Target Directory: ${targetPath}` : ''}\n\nPlease analyze what is being requested and implement it appropriately. This may involve:\n- Creating files and directories\n- Writing code\n- Setting up configurations\n- Creating documentation\n- Any other tasks necessary to fulfill the request\n\nEnsure your implementation is complete, well-structured, and follows best practices.`,\n priority: 'high' as TaskPriority,\n estimatedDuration: 15 * 60 * 1000,\n requiredCapabilities: ['code-generation', 'file-system', 'documentation'],\n }),\n );\n }\n\n this.logger.info('Objective decomposed', {\n objectiveId: objective.id,\n taskCount: tasks.length,\n });\n\n return tasks;\n }\n\n private createTaskForObjective(id: string, type: TaskType, params: any): TaskDefinition {\n const taskId: TaskId = {\n id: generateId('task'),\n swarmId: this.swarmId.id,\n sequence: this.tasks.size + 1,\n priority: 1,\n };\n\n return {\n id: taskId,\n type,\n name: params.title,\n description: params.description,\n instructions: params.description,\n requirements: {\n capabilities: params.requiredCapabilities || [],\n tools: this.getRequiredTools(type),\n permissions: this.getRequiredPermissions(type),\n },\n constraints: {\n dependencies: params.dependencies || [],\n dependents: [],\n conflicts: [],\n maxRetries: SWARM_CONSTANTS.MAX_RETRIES,\n timeoutAfter: params.estimatedDuration || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,\n },\n priority: params.priority || 'medium',\n input: {\n description: params.description,\n objective: params.description,\n },\n context: {\n objectiveId: id,\n targetDir: params.targetDir,\n },\n examples: [],\n status: 'created',\n createdAt: new Date(),\n updatedAt: new Date(),\n attempts: [],\n statusHistory: [\n {\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'created' as TaskStatus,\n reason: 'Task created',\n triggeredBy: 'system',\n },\n ],\n };\n }\n\n private analyzeDependencies(tasks: TaskDefinition[]): any[] {\n // Implementation needed - analyze task dependencies\n return [];\n }\n\n private convertDependenciesToTaskDependencies(dependencies: Map<string, string[]>): any[] {\n // Convert decomposition dependencies to task dependencies format\n const result: any[] = [];\n dependencies.forEach((deps, taskId) => {\n deps.forEach((dependsOn) => {\n result.push({\n taskId,\n dependsOn,\n type: 'sequential',\n });\n });\n });\n return result;\n }\n\n private async ensureRequiredAgents(objective: SwarmObjective): Promise<void> {\n // Implementation needed - ensure required agents are available\n }\n\n private async scheduleInitialTasks(objective: SwarmObjective): Promise<void> {\n this.logger.info('Scheduling initial tasks for objective', {\n objectiveId: objective.id,\n taskCount: objective.tasks.length,\n });\n\n // Extract target directory from objective description\n const targetDirPatterns = [\n /in\\s+([^\\s]+\\/?)$/i,\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i,\n /([^\\s]+\\/[^\\s]+)$/,\n /examples\\/[^\\s]+/i,\n ];\n\n let objectiveTargetDir = null;\n for (const pattern of targetDirPatterns) {\n const match = objective.description.match(pattern);\n if (match) {\n objectiveTargetDir = match[1] || match[0];\n break;\n }\n }\n\n // Add all tasks to the tasks map\n for (const task of objective.tasks) {\n task.context.objectiveId = objective.id;\n // Propagate target directory to all tasks\n if (objectiveTargetDir && !task.context.targetDir) {\n task.context.targetDir = objectiveTargetDir;\n }\n this.tasks.set(task.id.id, task);\n\n // Track task in JSON output if enabled\n this.trackTaskInJsonOutput(task);\n }\n\n // Find tasks with no dependencies and queue them\n const initialTasks = objective.tasks.filter(\n (task) => !task.constraints.dependencies || task.constraints.dependencies.length === 0,\n );\n\n this.logger.info('Found initial tasks without dependencies', {\n count: initialTasks.length,\n tasks: initialTasks.map((t) => ({ id: t.id.id, name: t.name })),\n });\n\n // Queue initial tasks for execution\n for (const task of initialTasks) {\n task.status = 'queued';\n task.updatedAt = new Date();\n\n // Update status history\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'queued' as TaskStatus,\n reason: 'Task queued for execution',\n triggeredBy: 'system',\n });\n\n // Emit task queued event\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.queued',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n }\n\n // Update objective progress\n objective.progress.totalTasks = objective.tasks.length;\n objective.progress.runningTasks = 0;\n objective.progress.completedTasks = 0;\n objective.progress.failedTasks = 0;\n }\n\n private startTaskExecutionLoop(objective: SwarmObjective): void {\n this.logger.info('Starting task execution loop for objective', {\n objectiveId: objective.id,\n });\n\n // Create an interval to process queued tasks\n const executionInterval = setInterval(async () => {\n try {\n // Check if objective is still executing\n if (objective.status !== 'executing') {\n clearInterval(executionInterval);\n return;\n }\n\n // Find queued tasks\n const queuedTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'queued',\n );\n\n // Find idle agents\n const idleAgents = Array.from(this.agents.values()).filter(\n (agent) => agent.status === 'idle',\n );\n\n if (queuedTasks.length > 0 && idleAgents.length > 0) {\n this.logger.debug('Processing queued tasks', {\n queuedTasks: queuedTasks.length,\n idleAgents: idleAgents.length,\n });\n }\n\n // Assign tasks to idle agents\n for (const task of queuedTasks) {\n if (idleAgents.length === 0) break;\n\n // Find suitable agent\n const suitableAgents = idleAgents.filter((agent) => this.agentCanHandleTask(agent, task));\n\n if (suitableAgents.length > 0) {\n // Assign to first suitable agent\n await this.assignTask(task.id.id, suitableAgents[0].id.id);\n\n // Remove agent from idle list\n const agentIndex = idleAgents.findIndex((a) => a.id.id === suitableAgents[0].id.id);\n if (agentIndex >= 0) {\n idleAgents.splice(agentIndex, 1);\n }\n }\n }\n\n // Check for completed tasks and process dependencies\n const completedTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'completed',\n );\n\n // Find tasks that can now be queued (dependencies met)\n const pendingTasks = Array.from(this.tasks.values()).filter(\n (task) =>\n task.context?.objectiveId === objective.id &&\n task.status === 'created' &&\n this.taskDependenciesMet(task, completedTasks),\n );\n\n // Queue tasks with met dependencies\n for (const task of pendingTasks) {\n task.status = 'queued';\n task.updatedAt = new Date();\n\n task.statusHistory.push({\n timestamp: new Date(),\n from: 'created' as TaskStatus,\n to: 'queued' as TaskStatus,\n reason: 'Dependencies met, task queued',\n triggeredBy: 'system',\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.queued',\n source: this.swarmId.id,\n data: { task },\n broadcast: false,\n processed: false,\n });\n }\n\n // Check for stuck/timed out tasks\n const runningTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id && task.status === 'running',\n );\n\n const now = Date.now();\n for (const task of runningTasks) {\n if (task.startedAt) {\n const runtime = now - task.startedAt.getTime();\n const timeout = task.constraints?.timeoutAfter || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT;\n\n if (runtime > timeout) {\n this.logger.warn('Task timed out', {\n taskId: task.id.id,\n runtime: Math.round(runtime / 1000),\n timeout: Math.round(timeout / 1000),\n });\n\n // Mark task as failed due to timeout\n task.status = 'failed';\n task.completedAt = new Date();\n task.error = {\n type: 'TimeoutError',\n message: `Task exceeded timeout of ${timeout}ms`,\n code: 'TASK_TIMEOUT',\n context: { taskId: task.id.id, runtime },\n recoverable: true,\n retryable: true,\n };\n\n // Update agent state if assigned\n if (task.assignedTo) {\n const agent = this.agents.get(task.assignedTo.id);\n if (agent) {\n agent.status = 'idle';\n agent.currentTask = undefined;\n agent.metrics.tasksFailed++;\n }\n }\n\n // Emit timeout event\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: 'task.failed',\n source: this.swarmId.id,\n data: { task, reason: 'timeout' },\n broadcast: false,\n processed: false,\n });\n }\n }\n }\n\n // Update objective progress\n const allTasks = Array.from(this.tasks.values()).filter(\n (task) => task.context?.objectiveId === objective.id,\n );\n\n objective.progress.totalTasks = allTasks.length;\n objective.progress.completedTasks = allTasks.filter((t) => t.status === 'completed').length;\n objective.progress.failedTasks = allTasks.filter((t) => t.status === 'failed').length;\n objective.progress.runningTasks = allTasks.filter((t) => t.status === 'running').length;\n objective.progress.percentComplete =\n objective.progress.totalTasks > 0\n ? (objective.progress.completedTasks / objective.progress.totalTasks) * 100\n : 0;\n\n // Check if objective is complete\n if (\n objective.progress.completedTasks + objective.progress.failedTasks ===\n objective.progress.totalTasks\n ) {\n objective.status = objective.progress.failedTasks === 0 ? 'completed' : 'failed';\n objective.completedAt = new Date();\n clearInterval(executionInterval);\n\n this.logger.info('Objective completed', {\n objectiveId: objective.id,\n status: objective.status,\n completedTasks: objective.progress.completedTasks,\n failedTasks: objective.progress.failedTasks,\n });\n\n this.emitSwarmEvent({\n id: generateId('event'),\n timestamp: new Date(),\n type: objective.status === 'completed' ? 'objective.completed' : 'objective.failed',\n source: this.swarmId.id,\n data: { objective },\n broadcast: true,\n processed: false,\n });\n }\n } catch (error) {\n this.logger.error('Error in task execution loop', { error });\n }\n }, 2000); // Check every 2 seconds\n\n // Store interval reference for cleanup\n if (!this.executionIntervals) {\n this.executionIntervals = new Map();\n }\n this.executionIntervals.set(objective.id, executionInterval);\n }\n\n private taskDependenciesMet(task: TaskDefinition, completedTasks: TaskDefinition[]): boolean {\n if (!task.constraints.dependencies || task.constraints.dependencies.length === 0) {\n return true;\n }\n\n const completedTaskIds = completedTasks.map((t) => t.id.id);\n return task.constraints.dependencies.every((dep) => {\n // Handle both string and TaskId object dependencies\n const depId = typeof dep === 'string' ? dep : dep.id;\n return completedTaskIds.includes(depId);\n });\n }\n\n private getNextInstanceNumber(type: AgentType): number {\n const agentsOfType = Array.from(this.agents.values()).filter((agent) => agent.type === type);\n return agentsOfType.length + 1;\n }\n\n private getDefaultPermissions(type: AgentType): string[] {\n switch (type) {\n case 'coordinator':\n return ['read', 'write', 'execute', 'admin'];\n case 'coder':\n return ['read', 'write', 'execute'];\n case 'tester':\n return ['read', 'execute'];\n case 'reviewer':\n return ['read', 'write'];\n default:\n return ['read'];\n }\n }\n\n private async initializeAgentCapabilities(agent: AgentState): Promise<void> {\n // Set capabilities based on agent type\n switch (agent.type) {\n case 'coordinator':\n agent.capabilities.codeGeneration = false;\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = false;\n agent.capabilities.documentation = true;\n agent.capabilities.research = true;\n agent.capabilities.analysis = true;\n break;\n case 'coder':\n agent.capabilities.codeGeneration = true;\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = true;\n agent.capabilities.documentation = true;\n break;\n case 'researcher':\n agent.capabilities.research = true;\n agent.capabilities.analysis = true;\n agent.capabilities.webSearch = true;\n agent.capabilities.documentation = true;\n break;\n case 'analyst':\n agent.capabilities.analysis = true;\n agent.capabilities.research = true;\n agent.capabilities.documentation = true;\n break;\n case 'reviewer':\n agent.capabilities.codeReview = true;\n agent.capabilities.testing = true;\n agent.capabilities.documentation = true;\n break;\n case 'tester':\n agent.capabilities.testing = true;\n agent.capabilities.codeReview = true;\n break;\n }\n }\n\n private async initializeAgentEnvironment(agent: AgentState): Promise<void> {\n // Implementation needed - setup agent environment\n }\n\n private startAgentHeartbeat(agent: AgentState): void {\n // Implementation needed - start agent heartbeat\n }\n\n private stopAgentHeartbeat(agent: AgentState): void {\n // Implementation needed - stop agent heartbeat\n }\n\n private async cleanupAgentEnvironment(agent: AgentState): Promise<void> {\n // Implementation needed - cleanup agent environment\n }\n\n private getRequiredCapabilities(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['code-generation', 'file-system'];\n case 'testing':\n return ['testing', 'code-review'];\n case 'research':\n return ['research', 'web-search'];\n case 'analysis':\n return ['analysis', 'documentation'];\n case 'review':\n return ['code-review', 'documentation'];\n case 'documentation':\n return ['documentation'];\n default:\n return [];\n }\n }\n\n private getRequiredTools(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['editor', 'compiler', 'debugger'];\n case 'testing':\n return ['test-runner', 'coverage-tool'];\n case 'research':\n return ['web-browser', 'search-engine'];\n case 'analysis':\n return ['data-tools', 'visualization'];\n default:\n return [];\n }\n }\n\n private getRequiredPermissions(type: TaskType): string[] {\n switch (type) {\n case 'coding':\n return ['read', 'write', 'execute'];\n case 'testing':\n return ['read', 'execute'];\n case 'research':\n return ['read', 'network'];\n default:\n return ['read'];\n }\n }\n\n private async executeTaskWithAgent(task: TaskDefinition, agent: AgentState): Promise<any> {\n this.logger.info('Executing task with agent', {\n taskId: task.id.id,\n taskName: task.name,\n agentId: agent.id.id,\n agentName: agent.name,\n });\n\n // Extract target directory from task\n const targetDir = this.extractTargetDirectory(task);\n\n try {\n // Use Claude Flow executor for full SPARC system in non-interactive mode\n const { ClaudeFlowExecutor } = await import('./claude-flow-executor.ts');\n const executor = new ClaudeFlowExecutor({\n logger: this.logger,\n claudeFlowPath: getClaudeFlowBin(),\n enableSparc: true,\n verbose: this.config.logging?.level === 'debug',\n timeoutMinutes: this.config.taskTimeoutMinutes,\n });\n\n const result = await executor.executeTask(task, agent, targetDir);\n\n this.logger.info('Task execution completed', {\n taskId: task.id.id,\n success: true,\n outputLength: JSON.stringify(result).length,\n });\n\n return result;\n } catch (error) {\n this.logger.error('Task execution failed', {\n taskId: task.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private createExecutionPrompt(task: TaskDefinition): string {\n // Create a prompt that Claude will understand\n let prompt = `# Swarm Task Execution\\n\\n`;\n prompt += `## Task: ${task.name}\\n\\n`;\n prompt += `${task.instructions || task.description}\\n\\n`;\n\n // Add working directory information if available\n const targetDir = this.extractTargetDirectory(task);\n if (targetDir) {\n prompt += `## Working Directory\\n`;\n prompt += `Please create all files in: ${targetDir}\\n\\n`;\n }\n\n if (task.input && Object.keys(task.input).length > 0) {\n prompt += `## Additional Input\\n`;\n prompt += `${JSON.stringify(task.input, null, 2)}\\n\\n`;\n }\n\n if (task.context && Object.keys(task.context).length > 0) {\n prompt += `## Context\\n`;\n prompt += `${JSON.stringify(task.context, null, 2)}\\n\\n`;\n }\n\n // Add execution guidelines\n prompt += `## Guidelines\\n`;\n prompt += `- Focus on completing this specific task\\n`;\n prompt += `- Create all necessary files and directories\\n`;\n prompt += `- Follow best practices for the technology being used\\n`;\n prompt += `- Ensure the implementation is complete and functional\\n`;\n\n return prompt;\n }\n\n private extractTargetDirectory(task: TaskDefinition): string | null {\n // Try multiple patterns to find the target directory\n const patterns = [\n /in\\s+([^\\s]+\\/?)$/i, // \"in examples/dir\" at end\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i, // \"in examples/gradio\" anywhere\n /([^\\s]+\\/[^\\s]+)$/, // \"examples/gradio\" at end\n /examples\\/[^\\s]+/i, // specifically match examples/ paths\n ];\n\n let targetDir = null;\n\n // First check task description and input\n for (const pattern of patterns) {\n const descMatch = task.description.match(pattern);\n const inputMatch = task.input?.objective?.match(pattern);\n if (descMatch || inputMatch) {\n targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];\n break;\n }\n }\n\n // If not found and task has context with targetDir, use that\n if (!targetDir && task.context?.targetDir) {\n targetDir = task.context.targetDir;\n }\n\n // If still not found, check objective description from context\n if (!targetDir && task.context?.objectiveId) {\n const objective = this.objectives.get(task.context.objectiveId);\n if (objective) {\n for (const pattern of patterns) {\n const match = objective.description.match(pattern);\n if (match) {\n targetDir = match[1] || match[0];\n break;\n }\n }\n }\n }\n\n if (targetDir) {\n // Clean up the target directory\n targetDir = targetDir.replace(/\\s+.*$/, '');\n // Resolve relative to current directory\n if (!targetDir.startsWith('/')) {\n targetDir = `${getClaudeFlowRoot()}/${targetDir}`;\n }\n }\n\n return targetDir;\n }\n\n private async executeClaudeTask(\n task: TaskDefinition,\n agent: AgentState,\n prompt: string,\n targetDir: string | null,\n ): Promise<any> {\n // Create unique instance ID for this execution\n const instanceId = `swarm-${this.swarmId.id}-${task.id.id}-${Date.now()}`;\n\n // Build Claude arguments for non-interactive execution\n const claudeArgs = [prompt];\n\n // Always skip permissions for swarm automation\n claudeArgs.push('--dangerously-skip-permissions');\n\n // Add non-interactive flags for automation\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json');\n claudeArgs.push('--verbose'); // Required when using stream-json with -p\n\n // Set working directory if specified\n if (targetDir) {\n // Ensure directory exists\n await Deno.mkdir(targetDir, { recursive: true });\n\n // Add directory context to prompt\n const enhancedPrompt = `${prompt}\\n\\n## Important: Working Directory\\nPlease ensure all files are created in: ${targetDir}`;\n claudeArgs[0] = enhancedPrompt;\n }\n\n try {\n // Check if claude command exists\n const checkCommand = new Deno.Command('which', {\n args: ['claude'],\n stdout: 'piped',\n stderr: 'piped',\n });\n const checkResult = await checkCommand.output();\n if (!checkResult.success) {\n throw new Error('Claude CLI not found. Please ensure claude is installed and in PATH.');\n }\n\n // Execute Claude with the prompt\n const command = new Deno.Command('claude', {\n args: claudeArgs,\n cwd: targetDir || process.cwd(),\n env: {\n ...Deno.env.toObject(),\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_SWARM_MODE: 'true',\n CLAUDE_SWARM_ID: this.swarmId.id,\n CLAUDE_TASK_ID: task.id.id,\n CLAUDE_AGENT_ID: agent.id.id,\n CLAUDE_WORKING_DIRECTORY: targetDir || process.cwd(),\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: `swarm-${this.swarmId.id}`,\n },\n stdin: 'null',\n stdout: 'piped',\n stderr: 'piped',\n });\n\n this.logger.info('Spawning Claude agent for task', {\n taskId: task.id.id,\n agentId: agent.id.id,\n instanceId,\n targetDir,\n });\n\n const child = command.spawn();\n const { code, stdout, stderr } = await child.output();\n\n if (code === 0) {\n const output = new TextDecoder().decode(stdout);\n this.logger.info('Claude agent completed task successfully', {\n taskId: task.id.id,\n outputLength: output.length,\n });\n\n return {\n success: true,\n output,\n instanceId,\n targetDir,\n };\n } else {\n const errorOutput = new TextDecoder().decode(stderr);\n this.logger.error(`Claude agent failed with code ${code}`, {\n taskId: task.id.id,\n error: errorOutput,\n });\n throw new Error(`Claude execution failed: ${errorOutput}`);\n }\n } catch (error) {\n this.logger.error('Failed to execute Claude agent', {\n taskId: task.id.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private determineToolsForTask(task: TaskDefinition, agent: AgentState): string[] {\n const tools = new Set<string>();\n\n // Basic tools for all tasks\n tools.add('View');\n tools.add('Edit');\n tools.add('Bash');\n\n // Add tools based on task type\n switch (task.type) {\n case 'coding':\n tools.add('Create');\n tools.add('Write');\n tools.add('MultiEdit');\n tools.add('Test');\n break;\n case 'testing':\n tools.add('Test');\n tools.add('View');\n break;\n case 'documentation':\n tools.add('Write');\n tools.add('Create');\n break;\n case 'analysis':\n tools.add('Analyze');\n tools.add('Search');\n break;\n case 'research':\n tools.add('WebSearch');\n tools.add('Search');\n break;\n }\n\n // Add tools based on agent capabilities\n if (agent.capabilities.fileSystem) {\n tools.add('FileSystem');\n }\n if (agent.capabilities.terminalAccess) {\n tools.add('Terminal');\n }\n if (agent.capabilities.webSearch) {\n tools.add('WebSearch');\n }\n if (agent.capabilities.apiIntegration) {\n tools.add('API');\n }\n\n return Array.from(tools);\n }\n\n private async simulateTaskExecution(\n task: TaskDefinition,\n agent: AgentState,\n prompt: string,\n ): Promise<any> {\n // Simulate different task types with actual file operations\n // Check if task has a target directory in the description or context\n let workDir = `/tmp/swarm/${this.swarmId.id}/work`;\n\n // Extract target directory from task description or input\n // Try multiple patterns to find the target directory\n const patterns = [\n /in\\s+([^\\s]+\\/?)$/i, // \"in examples/dir\" at end\n /(?:in|to|at)\\s+([^\\s]+\\/[^\\s]+)/i, // \"in examples/gradio\" anywhere\n /([^\\s]+\\/[^\\s]+)$/, // \"examples/gradio\" at end\n /examples\\/[^\\s]+/i, // specifically match examples/ paths\n ];\n\n let targetDir = null;\n for (const pattern of patterns) {\n const descMatch = task.description.match(pattern);\n const inputMatch = task.input?.objective?.match(pattern);\n if (descMatch || inputMatch) {\n targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];\n break;\n }\n }\n\n if (targetDir) {\n // Clean up the target directory (remove trailing words if needed)\n targetDir = targetDir.replace(/\\s+.*$/, '');\n // Use absolute path or resolve relative to current directory\n workDir = targetDir.startsWith('/') ? targetDir : `${getClaudeFlowRoot()}/${targetDir}`;\n\n this.logger.debug('Extracted target directory', {\n original: task.description,\n targetDir,\n workDir,\n });\n }\n\n try {\n // Ensure work directory exists\n await Deno.mkdir(workDir, { recursive: true });\n\n switch (task.type) {\n case 'coding':\n return await this.executeCodeGenerationTask(task, workDir, agent);\n\n case 'analysis':\n return await this.executeAnalysisTask(task, workDir, agent);\n\n case 'documentation':\n return await this.executeDocumentationTask(task, workDir, agent);\n\n case 'testing':\n return await this.executeTestingTask(task, workDir, agent);\n\n default:\n return await this.executeGenericTask(task, workDir, agent);\n }\n } catch (error) {\n throw new Error(\n `Task execution failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n private async executeCodeGenerationTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing code generation task', { taskId: task.id.id });\n\n // Detect technology from description\n const description = task.description.toLowerCase();\n const isGradio = description.includes('gradio');\n const isPython =\n isGradio ||\n description.includes('python') ||\n description.includes('fastapi') ||\n description.includes('django');\n const isHelloWorld = description.includes('hello') && description.includes('world');\n const isRestAPI = description.includes('rest api') || description.includes('api');\n\n if (isGradio) {\n // Create a Gradio application\n return await this.createGradioApp(task, workDir);\n } else if (isPython && isRestAPI) {\n // Create a Python REST API (FastAPI)\n return await this.createPythonRestAPI(task, workDir);\n } else if (isRestAPI) {\n // Create a REST API application\n const projectName = 'rest-api';\n const projectDir = `${workDir}/${projectName}`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n // Create main API file\n const apiCode = `const express = require('express');\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Health check endpoint\napp.get('/health', (req, res) => {\n res.json({ \n status: 'healthy',\n service: 'REST API',\n swarmId: '${this.swarmId.id}',\n created: '${new Date().toISOString()}'\n });\n});\n\n// Sample endpoints\napp.get('/api/v1/items', (req, res) => {\n res.json({\n items: [\n { id: 1, name: 'Item 1', description: 'First item' },\n { id: 2, name: 'Item 2', description: 'Second item' }\n ],\n total: 2\n });\n});\n\napp.get('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({\n id,\n name: \\`Item \\${id}\\`,\n description: \\`Description for item \\${id}\\`\n });\n});\n\napp.post('/api/v1/items', (req, res) => {\n const newItem = {\n id: Date.now(),\n ...req.body,\n createdAt: new Date().toISOString()\n };\n res.status(201).json(newItem);\n});\n\napp.put('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n const updatedItem = {\n id,\n ...req.body,\n updatedAt: new Date().toISOString()\n };\n res.json(updatedItem);\n});\n\napp.delete('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({ message: \\`Item \\${id} deleted successfully\\` });\n});\n\n// Error handling middleware\napp.use((err, req, res, next) => {\n console.error(err.stack);\n res.status(500).json({ error: 'Internal server error' });\n});\n\n// Start server\napp.listen(port, () => {\n console.log(\\`REST API server running on port \\${port}\\`);\n console.log('Created by Claude Flow Swarm');\n});\n\nmodule.exports = app;\n`;\n\n await fs.writeFile(`${projectDir}/server.js`, apiCode);\n\n // Create package.json\n const packageJson = {\n name: projectName,\n version: '1.0.0',\n description: 'REST API created by Claude Flow Swarm',\n main: 'server.js',\n scripts: {\n start: 'node server.js',\n dev: 'nodemon server.js',\n test: 'jest',\n },\n keywords: ['rest', 'api', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n dependencies: {\n express: '^4.18.2',\n },\n devDependencies: {\n nodemon: '^3.0.1',\n jest: '^29.7.0',\n supertest: '^6.3.3',\n },\n swarmMetadata: {\n swarmId: this.swarmId.id,\n taskId: task.id.id,\n agentId: agent.id.id,\n created: new Date().toISOString(),\n },\n };\n\n await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));\n\n // Create README\n const readme = `# REST API\n\nThis REST API was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${this.swarmId.id}\n- Task: ${task.name}\n- Agent: ${agent.name}\n- Generated: ${new Date().toISOString()}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Usage\n\nStart the server:\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\nDevelopment mode with auto-reload:\n\\`\\`\\`bash\nnpm run dev\n\\`\\`\\`\n\n## API Endpoints\n\n- \\`GET /health\\` - Health check\n- \\`GET /api/v1/items\\` - Get all items\n- \\`GET /api/v1/items/:id\\` - Get item by ID\n- \\`POST /api/v1/items\\` - Create new item\n- \\`PUT /api/v1/items/:id\\` - Update item\n- \\`DELETE /api/v1/items/:id\\` - Delete item\n\n## Description\n${task.description}\n\n---\nCreated by Claude Flow Swarm\n`;\n\n await fs.writeFile(`${projectDir}/README.md`, readme);\n\n // Create .gitignore\n const gitignore = `node_modules/\n.env\n*.log\n.DS_Store\ncoverage/\n`;\n\n await fs.writeFile(`${projectDir}/.gitignore`, gitignore);\n\n return {\n success: true,\n output: {\n message: 'REST API created successfully',\n location: projectDir,\n files: ['server.js', 'package.json', 'README.md', '.gitignore'],\n },\n artifacts: {\n mainFile: `${projectDir}/server.js`,\n packageFile: `${projectDir}/package.json`,\n readmeFile: `${projectDir}/README.md`,\n },\n };\n } else if (isHelloWorld) {\n // Create a simple hello world application\n const projectDir = `${workDir}/hello-world`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n // Create main application file\n const mainCode = `#!/usr/bin/env node\n\n// Hello World Application\n// Generated by Claude Flow Swarm\n\nconsole.log('Hello, World!');\nconsole.log('This application was created by the Claude Flow Swarm system.');\nconsole.log('Swarm ID: ${this.swarmId.id}');\nconsole.log('Task: ${task.name}');\nconsole.log('Generated at: ${new Date().toISOString()}');\n\n// Export for testing\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = { message: 'Hello, World!' };\n}\n`;\n\n await fs.writeFile(`${projectDir}/index.js`, mainCode);\n\n // Create package.json\n const packageJson = {\n name: 'hello-world',\n version: '1.0.0',\n description: 'Hello World application created by Claude Flow Swarm',\n main: 'index.js',\n scripts: {\n start: 'node index.js',\n test: 'node test.js',\n },\n keywords: ['hello-world', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n };\n\n await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));\n\n // Create README\n const readme = `# Hello World\n\nThis application was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${this.swarmId.id}\n- Task: ${task.name}\n- Generated: ${new Date().toISOString()}\n\n## Usage\n\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\n## Description\n${task.description}\n`;\n\n await fs.writeFile(`${projectDir}/README.md`, readme);\n\n return {\n success: true,\n output: {\n message: 'Hello World application created successfully',\n location: projectDir,\n files: ['index.js', 'package.json', 'README.md'],\n },\n artifacts: {\n mainFile: `${projectDir}/index.js`,\n packageFile: `${projectDir}/package.json`,\n readmeFile: `${projectDir}/README.md`,\n },\n };\n }\n\n // For other code generation tasks, create a basic structure\n const projectDir = `${workDir}/generated-code`;\n await Deno.mkdir(projectDir, { recursive: true });\n\n const code = `// Generated code for: ${task.name}\n// ${task.description}\n\nfunction main() {\n console.log('Executing task: ${task.name}');\n // Implementation would go here\n}\n\nmain();\n`;\n\n await fs.writeFile(`${projectDir}/main.js`, code);\n\n return {\n success: true,\n output: {\n message: 'Code generated successfully',\n location: projectDir,\n files: ['main.js'],\n },\n };\n }\n\n private async executeAnalysisTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing analysis task', { taskId: task.id.id });\n\n const analysisDir = `${workDir}/analysis`;\n await Deno.mkdir(analysisDir, { recursive: true });\n\n const analysis = {\n task: task.name,\n description: task.description,\n timestamp: new Date().toISOString(),\n findings: [\n 'Analysis point 1: Task objectives are clear',\n 'Analysis point 2: Resources are allocated',\n 'Analysis point 3: Implementation path is defined',\n ],\n recommendations: [\n 'Proceed with implementation',\n 'Monitor progress regularly',\n 'Adjust resources as needed',\n ],\n };\n\n await fs.writeFile(`${analysisDir}/analysis-report.json`, JSON.stringify(analysis, null, 2));\n\n return {\n success: true,\n output: analysis,\n artifacts: {\n report: `${analysisDir}/analysis-report.json`,\n },\n };\n }\n\n private async executeDocumentationTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing documentation task', { taskId: task.id.id });\n\n const docsDir = `${workDir}/docs`;\n await Deno.mkdir(docsDir, { recursive: true });\n\n const documentation = `# ${task.name}\n\n${task.description}\n\n## Overview\nThis documentation was generated by the Claude Flow Swarm system.\n\n## Details\n- Task ID: ${task.id.id}\n- Generated: ${new Date().toISOString()}\n- Swarm ID: ${this.swarmId.id}\n\n## Instructions\n${task.instructions}\n\n## Implementation Notes\n- This is an automated documentation generated by the swarm\n- Further details would be added based on actual implementation\n`;\n\n await fs.writeFile(`${docsDir}/documentation.md`, documentation);\n\n return {\n success: true,\n output: {\n message: 'Documentation created successfully',\n location: docsDir,\n files: ['documentation.md'],\n },\n artifacts: {\n documentation: `${docsDir}/documentation.md`,\n },\n };\n }\n\n private async executeTestingTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing testing task', { taskId: task.id.id });\n\n const testDir = `${workDir}/tests`;\n await Deno.mkdir(testDir, { recursive: true });\n\n const testCode = `// Test suite for: ${task.name}\n// ${task.description}\n\nconst assert = require('assert');\n\ndescribe('${task.name}', () => {\n it('should pass basic test', () => {\n assert.strictEqual(1 + 1, 2);\n });\n \n it('should validate implementation', () => {\n // Test implementation would go here\n assert.ok(true, 'Implementation validated');\n });\n});\n\nconsole.log('Tests completed for: ${task.name}');\n`;\n\n await fs.writeFile(`${testDir}/test.js`, testCode);\n\n return {\n success: true,\n output: {\n message: 'Test suite created successfully',\n location: testDir,\n files: ['test.js'],\n testsPassed: 2,\n testsFailed: 0,\n },\n artifacts: {\n testFile: `${testDir}/test.js`,\n },\n };\n }\n\n private async executeGenericTask(\n task: TaskDefinition,\n workDir: string,\n agent: AgentState,\n ): Promise<any> {\n this.logger.info('Executing generic task', { taskId: task.id.id });\n\n const outputDir = `${workDir}/output`;\n await Deno.mkdir(outputDir, { recursive: true });\n\n const output = {\n task: task.name,\n type: task.type,\n description: task.description,\n status: 'completed',\n timestamp: new Date().toISOString(),\n result: 'Task executed successfully',\n };\n\n await fs.writeFile(`${outputDir}/result.json`, JSON.stringify(output, null, 2));\n\n return {\n success: true,\n output,\n artifacts: {\n result: `${outputDir}/result.json`,\n },\n };\n }\n\n private assessTaskQuality(task: TaskDefinition, result: any): number {\n // Implementation needed - assess task quality\n return 0.8;\n }\n\n private updateAgentMetrics(agent: AgentState, task: TaskDefinition): void {\n // Update agent performance metrics\n const executionTime = task.completedAt!.getTime() - (task.startedAt?.getTime() || 0);\n\n agent.metrics.averageExecutionTime =\n (agent.metrics.averageExecutionTime * agent.metrics.tasksCompleted + executionTime) /\n (agent.metrics.tasksCompleted + 1);\n\n agent.metrics.successRate =\n agent.metrics.tasksCompleted / (agent.metrics.tasksCompleted + agent.metrics.tasksFailed);\n }\n\n private async processDependentTasks(task: TaskDefinition): Promise<void> {\n // Implementation needed - process tasks that depend on this one\n }\n\n private isRecoverableError(error: any): boolean {\n // Implementation needed - determine if error is recoverable\n return true;\n }\n\n private isRetryableError(error: any): boolean {\n // Implementation needed - determine if error is retryable\n return true;\n }\n\n private async handleTaskFailureCascade(task: TaskDefinition): Promise<void> {\n // Implementation needed - handle failure cascade\n }\n\n private async reassignTask(taskId: string): Promise<void> {\n // Implementation needed - reassign task to different agent\n }\n\n private processHeartbeats(): void {\n const now = new Date();\n const timeout = this.config.monitoring.heartbeatInterval * 10; // Increased multiplier for long-running Claude tasks\n\n for (const agent of this.agents.values()) {\n if (agent.status === 'offline' || agent.status === 'terminated') {\n continue;\n }\n\n const timeSinceHeartbeat = now.getTime() - agent.lastHeartbeat.getTime();\n if (timeSinceHeartbeat > timeout) {\n this.logger.warn('Agent heartbeat timeout', {\n agentId: agent.id.id,\n timeSinceHeartbeat,\n });\n agent.status = 'error';\n agent.health = 0;\n }\n }\n }\n\n private updateSwarmMetrics(): void {\n // Implementation needed - update swarm-level metrics\n }\n\n private performCleanup(): void {\n // Implementation needed - perform periodic cleanup\n }\n\n private checkObjectiveCompletion(): void {\n // Implementation needed - check if objectives are complete\n }\n\n private checkObjectiveFailure(task: TaskDefinition): void {\n // Implementation needed - check if objective has failed\n }\n\n private handleAgentError(agentId: string, error: any): void {\n const agent = this.agents.get(agentId);\n if (agent) {\n agent.status = 'error';\n agent.health = 0;\n this.logger.error('Agent error', { agentId, error });\n\n // Track error in JSON output if enabled\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgentError(\n agentId,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n }\n\n // ===== JSON OUTPUT METHODS =====\n\n /**\n * Enable JSON output collection for non-interactive mode\n */\n enableJsonOutput(objective: string): void {\n if (!this.jsonOutputAggregator) {\n this.jsonOutputAggregator = new SwarmJsonOutputAggregator(\n this.swarmId.id,\n objective,\n this.config,\n );\n this.logger.info('JSON output aggregation enabled', { swarmId: this.swarmId.id });\n }\n }\n\n /**\n * Get the final JSON output for the swarm\n */\n getJsonOutput(\n status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed',\n ): string | null {\n if (!this.jsonOutputAggregator) {\n return null;\n }\n return this.jsonOutputAggregator.getJsonOutput(status);\n }\n\n /**\n * Save JSON output to file\n */\n async saveJsonOutput(\n filePath: string,\n status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed',\n ): Promise<void> {\n if (!this.jsonOutputAggregator) {\n throw new Error('JSON output aggregation not enabled');\n }\n await this.jsonOutputAggregator.saveToFile(filePath, status);\n }\n\n /**\n * Track agent activity in JSON output\n */\n private trackAgentInJsonOutput(agent: AgentState): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgent(agent);\n }\n }\n\n /**\n * Track task activity in JSON output\n */\n private trackTaskInJsonOutput(task: TaskDefinition): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addTask(task);\n }\n }\n\n /**\n * Add output to JSON aggregator\n */\n private addOutputToJsonAggregator(agentId: string, output: string): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addAgentOutput(agentId, output);\n }\n }\n\n /**\n * Add insight to JSON aggregator\n */\n addInsight(insight: string): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addInsight(insight);\n }\n }\n\n /**\n * Add artifact to JSON aggregator\n */\n addArtifact(key: string, artifact: any): void {\n if (this.jsonOutputAggregator) {\n this.jsonOutputAggregator.addArtifact(key, artifact);\n }\n }\n}\n"],"names":["EventEmitter","promises","fs","Logger","generateId","SWARM_CONSTANTS","AutoStrategy","getClaudeFlowRoot","getClaudeFlowBin","SwarmJsonOutputAggregator","SwarmCoordinator","logger","config","swarmId","agents","Map","tasks","objectives","_isRunning","status","startTime","endTime","metrics","events","lastHeartbeat","Date","jsonOutputAggregator","heartbeatTimer","monitoringTimer","cleanupTimer","executionIntervals","autoStrategy","logLevel","logging","level","logFormat","format","logDestination","destination","component","generateSwarmId","mergeWithDefaults","initializeMetrics","setupEventHandlers","info","id","mode","strategy","initialize","Error","validation","validateConfiguration","valid","errors","map","e","message","join","initializeSubsystems","startBackgroundProcesses","emitSwarmEvent","timestamp","type","source","data","broadcast","processed","error","shutdown","stopBackgroundProcesses","stopAllAgents","completeRunningTasks","saveState","duration","getTime","pause","agent","values","pauseAgent","resume","resumeAgent","createObjective","name","description","requirements","objectiveId","objective","minAgents","maxAgents","agentTypes","determineRequiredAgentTypes","estimatedDuration","maxDuration","qualityThreshold","reviewCoverage","testCoverage","reliabilityTarget","constraints","minQuality","requiredApprovals","allowedFailures","Math","floor","recoveryTime","milestones","dependencies","progress","initializeProgress","createdAt","decompositionResult","decomposeObjective","convertDependenciesToTaskDependencies","analyzeDependencies","set","taskCount","length","executeObjective","get","startedAt","ensureRequiredAgents","scheduleInitialTasks","startTaskExecutionLoop","registerAgent","capabilities","agentId","instance","getNextInstanceNumber","agentState","codeGeneration","codeReview","testing","documentation","research","analysis","webSearch","apiIntegration","fileSystem","terminalAccess","languages","frameworks","domains","tools","maxConcurrentTasks","maxMemoryUsage","DEFAULT_MEMORY_LIMIT","maxExecutionTime","DEFAULT_TASK_TIMEOUT","reliability","speed","quality","tasksCompleted","tasksFailed","averageExecutionTime","successRate","cpuUsage","memoryUsage","diskUsage","networkUsage","codeQuality","bugRate","userSatisfaction","totalUptime","lastActivity","responseTime","workload","health","autonomyLevel","learningEnabled","adaptationEnabled","maxTasksPerHour","timeoutThreshold","reportingInterval","heartbeatInterval","DEFAULT_HEARTBEAT_INTERVAL","permissions","getDefaultPermissions","trustedAgents","expertise","preferences","environment","runtime","version","workingDirectory","tempDirectory","logDirectory","apiEndpoints","credentials","availableTools","toolConfigs","endpoints","taskHistory","errorHistory","childAgents","collaborators","trackAgentInJsonOutput","initializeAgentCapabilities","startAgent","Object","keys","unregisterAgent","stopAgent","currentTask","reassignTask","delete","initializeAgentEnvironment","startAgentHeartbeat","push","String","stack","context","severity","resolved","cancelTask","stopAgentHeartbeat","cleanupAgentEnvironment","createTask","instructions","options","taskId","sequence","size","priority","task","getRequiredCapabilities","getRequiredTools","getRequiredPermissions","dependents","conflicts","maxRetries","MAX_RETRIES","timeoutAfter","input","examples","updatedAt","attempts","statusHistory","from","to","reason","triggeredBy","trackTaskInJsonOutput","assignTask","selectAgentForTask","assignedTo","assignedAt","agentName","startTaskExecution","attempt","attemptNumber","resourcesUsed","result","executeTaskWithAgent","completeTask","failTask","completedAt","output","artifacts","metadata","assessTaskQuality","completeness","accuracy","executionTime","validated","currentAttempt","undefined","updateAgentMetrics","processDependentTasks","warn","code","recoverable","isRecoverableError","retryable","isRetryableError","shouldRetry","retryDelay","pow","setTimeout","catch","retryError","handleTaskFailureCascade","availableAgents","Array","filter","agentCanHandleTask","scoredAgents","score","calculateAgentScore","sort","a","b","capabilityMatch","calculateCapabilityMatch","performanceScore","workloadScore","requiredCapabilities","matches","total","capability","agentHasCapability","caps","includes","agentType","minReliability","now","namespace","coordinationStrategy","agentSelection","taskScheduling","loadBalancing","faultTolerance","communication","maxTasks","resourceLimits","memory","cpu","DEFAULT_CPU_LIMIT","disk","DEFAULT_DISK_LIMIT","DEFAULT_QUALITY_THRESHOLD","reviewRequired","testingRequired","monitoring","metricsEnabled","loggingEnabled","tracingEnabled","metricsInterval","healthCheckInterval","retentionPeriod","maxLogSize","maxMetricPoints","alertingEnabled","alertThresholds","errorRate","exportEnabled","exportFormat","exportDestination","partitions","read","write","share","persistent","backupEnabled","distributed","consistency","cacheEnabled","compressionEnabled","security","authenticationRequired","authorizationRequired","encryptionEnabled","defaultPermissions","adminRoles","auditEnabled","auditLevel","inputValidation","outputSanitization","performance","maxConcurrency","defaultTimeout","cacheSize","cacheTtl","optimizationEnabled","adaptiveScheduling","predictiveLoading","resourcePooling","connectionPooling","memoryPooling","throughput","latency","efficiency","averageQuality","defectRate","reworkRate","resourceUtilization","costEfficiency","agentUtilization","agentSatisfaction","collaborationEffectiveness","scheduleVariance","deadlineAdherence","totalTasks","completedTasks","failedTasks","runningTasks","estimatedCompletion","timeRemaining","percentComplete","passedReviews","passedTests","costSpent","activeAgents","idleAgents","busyAgents","on","updateSwarmMetrics","checkObjectiveCompletion","checkObjectiveFailure","handleAgentError","event","slice","emit","emitSwarmEvents","success","onSwarmEvent","handler","offSwarmEvent","off","filterEvents","predicate","correlateEvents","correlationId","getSwarmId","getStatus","getAgents","getAgent","getTasks","getTask","getObjectives","getObjective","getMetrics","getEvents","isRunning","getUptime","getSwarmStatus","t","completed","failed","warnings","validatedAt","validator","setInterval","processHeartbeats","performCleanup","clearInterval","interval","clear","stopPromises","Promise","allSettled","timeout","deadline","some","resolve","getAgentTypeInstructions","getAgentCapabilities","targetDirMatch","match","targetDir","targetPath","startsWith","eachAgentPattern","requestsParallelAgents","test","createTaskForObjective","title","charAt","toUpperCase","task1","task2","task3","task4","params","forEach","deps","dependsOn","targetDirPatterns","objectiveTargetDir","pattern","initialTasks","count","executionInterval","queuedTasks","debug","suitableAgents","agentIndex","findIndex","splice","pendingTasks","taskDependenciesMet","round","allTasks","completedTaskIds","every","dep","depId","agentsOfType","taskName","extractTargetDirectory","ClaudeFlowExecutor","executor","claudeFlowPath","enableSparc","verbose","timeoutMinutes","taskTimeoutMinutes","executeTask","outputLength","JSON","stringify","createExecutionPrompt","prompt","patterns","descMatch","inputMatch","replace","executeClaudeTask","instanceId","claudeArgs","Deno","mkdir","recursive","enhancedPrompt","checkCommand","Command","args","stdout","stderr","checkResult","command","cwd","process","env","toObject","CLAUDE_INSTANCE_ID","CLAUDE_SWARM_MODE","CLAUDE_SWARM_ID","CLAUDE_TASK_ID","CLAUDE_AGENT_ID","CLAUDE_WORKING_DIRECTORY","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","stdin","child","spawn","TextDecoder","decode","errorOutput","determineToolsForTask","Set","add","simulateTaskExecution","workDir","original","executeCodeGenerationTask","executeAnalysisTask","executeDocumentationTask","executeTestingTask","executeGenericTask","toLowerCase","isGradio","isPython","isHelloWorld","isRestAPI","createGradioApp","createPythonRestAPI","projectName","projectDir","apiCode","toISOString","writeFile","packageJson","main","scripts","start","dev","keywords","author","license","express","devDependencies","nodemon","jest","supertest","swarmMetadata","created","readme","gitignore","location","files","mainFile","packageFile","readmeFile","mainCode","analysisDir","findings","recommendations","report","docsDir","testDir","testCode","testsPassed","testsFailed","testFile","outputDir","timeSinceHeartbeat","addAgentError","enableJsonOutput","getJsonOutput","saveJsonOutput","filePath","saveToFile","addAgent","addTask","addOutputToJsonAggregator","addAgentOutput","addInsight","insight","addArtifact","key","artifact"],"mappings":"AAAA,SAASA,YAAY,QAAQ,SAAS;AACtC,SAASC,YAAYC,EAAE,QAAQ,UAAU;AACzC,SAASC,MAAM,QAAQ,oBAAoB;AAC3C,SAASC,UAAU,QAAQ,sBAAsB;AACjD,SAsBEC,eAAe,QACV,aAAa;AACpB,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,oBAAoB;AACxE,SAASC,yBAAyB,QAAQ,8BAA8B;AAExE,OAAO,MAAMC,yBAAyBV;IAC5BW,OAAe;IAC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