claude-flow 2.0.0-alpha.2 → 2.0.0-alpha.21

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 (1018) hide show
  1. package/.claude/settings.json +30 -110
  2. package/README.md +301 -605
  3. package/bin/claude-flow +26 -2
  4. package/cli.mjs +2 -19
  5. package/package.json +3 -2
  6. package/scripts/claude-flow-wrapper.sh +35 -0
  7. package/src/cli/cli-core.ts +1 -1
  8. package/src/cli/command-registry.js +1 -1
  9. package/src/cli/commands/hook-types.ts +126 -0
  10. package/src/cli/commands/hook-validator.ts +191 -0
  11. package/src/cli/commands/hook.ts +346 -0
  12. package/src/cli/commands/index.ts +37 -0
  13. package/src/cli/commands/start/start-command.ts +3 -3
  14. package/src/cli/commands/swarm-new.ts +763 -353
  15. package/src/cli/commands/swarm-spawn.ts +8 -13
  16. package/src/cli/commands/swarm.ts +1 -1
  17. package/src/cli/commands/task.ts +51 -7
  18. package/src/cli/commands/workflow.ts +746 -10
  19. package/src/cli/index-remote.ts +1 -1
  20. package/src/cli/index.ts +35 -29
  21. package/src/cli/node-compat.js +2 -71
  22. package/src/cli/node-repl.ts +3 -5
  23. package/src/cli/repl.ts +33 -57
  24. package/src/cli/simple-cli.ts +27 -85
  25. package/src/cli/simple-commands/hive-mind/core.js +3 -1
  26. package/src/cli/simple-commands/hive-mind/mcp-wrapper.js +4 -1
  27. package/src/cli/simple-commands/hive-mind/memory.js +19 -5
  28. package/src/cli/simple-commands/hive-mind.js +390 -636
  29. package/src/cli/simple-commands/init/executable-wrapper.js +8 -5
  30. package/src/cli/simple-commands/init/help.js +6 -2
  31. package/src/cli/simple-commands/init/index.js +201 -168
  32. package/src/cli/simple-commands/init/templates/claude-flow-universal +78 -0
  33. package/src/cli/simple-commands/init/templates/commands/hooks/notification.md +102 -0
  34. package/src/cli/simple-commands/init/templates/commands/hooks/post-command.md +105 -0
  35. package/src/cli/simple-commands/init/templates/commands/hooks/post-edit.md +106 -0
  36. package/src/cli/simple-commands/init/templates/commands/hooks/post-task.md +101 -0
  37. package/src/cli/simple-commands/init/templates/commands/hooks/pre-command.md +102 -0
  38. package/src/cli/simple-commands/init/templates/commands/hooks/pre-edit.md +102 -0
  39. package/src/cli/simple-commands/init/templates/commands/hooks/pre-search.md +105 -0
  40. package/src/cli/simple-commands/init/templates/commands/hooks/pre-task.md +8 -8
  41. package/src/cli/simple-commands/init/templates/commands/hooks/session-end.md +107 -0
  42. package/src/cli/simple-commands/init/templates/commands/hooks/session-restore.md +110 -0
  43. package/src/cli/simple-commands/init/templates/commands/hooks/session-start.md +106 -0
  44. package/src/cli/simple-commands/init/templates/enhanced-templates.js +170 -222
  45. package/src/cli/simple-commands/init/templates/settings.json +30 -110
  46. package/src/cli/simple-commands/swarm.js +9 -6
  47. package/src/cli/ui/compatible-ui.ts +1 -14
  48. package/src/cli/ui/fallback-handler.ts +2 -2
  49. package/src/cli/utils/environment-detector.ts +6 -6
  50. package/src/cli/utils/interactive-detector.js +126 -0
  51. package/src/communication/message-bus.ts +7 -3
  52. package/src/coordination/advanced-task-executor.ts +11 -8
  53. package/src/coordination/load-balancer.ts +19 -33
  54. package/src/coordination/work-stealing.ts +1 -1
  55. package/src/core/event-bus.ts +2 -2
  56. package/src/core/logger.ts +1 -1
  57. package/src/hive-mind/core/Agent.ts +2 -3
  58. package/src/hive-mind/core/Communication.ts +3 -16
  59. package/src/hive-mind/core/DatabaseManager.ts +3 -18
  60. package/src/hive-mind/core/HiveMind.ts +6 -8
  61. package/src/hive-mind/core/Memory.ts +35 -29
  62. package/src/hive-mind/integration/ConsensusEngine.ts +19 -4
  63. package/src/hive-mind/integration/MCPToolWrapper.ts +2 -1
  64. package/src/hive-mind/integration/SwarmOrchestrator.ts +4 -7
  65. package/src/integration/mock-components.ts +8 -8
  66. package/src/integration/system-integration.ts +20 -33
  67. package/src/mcp/index.ts +17 -20
  68. package/src/mcp/ruv-swarm-tools.ts +2 -12
  69. package/src/swarm/coordinator.ts +46 -97
  70. package/src/swarm/executor-v2.ts +18 -23
  71. package/src/swarm/executor.ts +9 -9
  72. package/src/swarm/optimizations/optimized-executor.ts +26 -79
  73. package/src/swarm/prompt-copier-enhanced.ts +9 -27
  74. package/src/swarm/prompt-copier.ts +12 -13
  75. package/src/swarm/types.ts +1 -7
  76. package/src/utils/error-handler.ts +6 -23
  77. package/src/utils/type-guards.ts +188 -0
  78. package/.claude/commands/analysis/README.md +0 -9
  79. package/.claude/commands/analysis/bottleneck-detect.md +0 -150
  80. package/.claude/commands/analysis/performance-report.md +0 -25
  81. package/.claude/commands/analysis/token-usage.md +0 -25
  82. package/.claude/commands/automation/README.md +0 -9
  83. package/.claude/commands/automation/auto-agent.md +0 -112
  84. package/.claude/commands/automation/smart-spawn.md +0 -25
  85. package/.claude/commands/automation/workflow-select.md +0 -25
  86. package/.claude/commands/coordination/README.md +0 -9
  87. package/.claude/commands/coordination/agent-spawn.md +0 -25
  88. package/.claude/commands/coordination/swarm-init.md +0 -76
  89. package/.claude/commands/coordination/task-orchestrate.md +0 -25
  90. package/.claude/commands/github/README.md +0 -11
  91. package/.claude/commands/github/code-review.md +0 -25
  92. package/.claude/commands/github/github-swarm.md +0 -108
  93. package/.claude/commands/github/issue-tracker-enhanced.md +0 -358
  94. package/.claude/commands/github/issue-triage.md +0 -25
  95. package/.claude/commands/github/pr-enhance.md +0 -26
  96. package/.claude/commands/github/repo-analyze.md +0 -25
  97. package/.claude/commands/hooks/README.md +0 -11
  98. package/.claude/commands/hooks/post-edit.md +0 -25
  99. package/.claude/commands/hooks/post-task.md +0 -25
  100. package/.claude/commands/hooks/pre-edit.md +0 -25
  101. package/.claude/commands/hooks/pre-task.md +0 -100
  102. package/.claude/commands/hooks/session-end.md +0 -25
  103. package/.claude/commands/hooks-overview.md +0 -245
  104. package/.claude/commands/memory/README.md +0 -9
  105. package/.claude/commands/memory/memory-persist.md +0 -25
  106. package/.claude/commands/memory/memory-search.md +0 -25
  107. package/.claude/commands/memory/memory-usage.md +0 -25
  108. package/.claude/commands/monitoring/README.md +0 -9
  109. package/.claude/commands/monitoring/agent-metrics.md +0 -25
  110. package/.claude/commands/monitoring/real-time-view.md +0 -25
  111. package/.claude/commands/monitoring/swarm-monitor.md +0 -25
  112. package/.claude/commands/optimization/README.md +0 -9
  113. package/.claude/commands/optimization/cache-manage.md +0 -25
  114. package/.claude/commands/optimization/parallel-execute.md +0 -25
  115. package/.claude/commands/optimization/topology-optimize.md +0 -25
  116. package/.claude/commands/training/README.md +0 -9
  117. package/.claude/commands/training/model-update.md +0 -25
  118. package/.claude/commands/training/neural-train.md +0 -25
  119. package/.claude/commands/training/pattern-learn.md +0 -25
  120. package/.claude/commands/workflows/README.md +0 -9
  121. package/.claude/commands/workflows/workflow-create.md +0 -25
  122. package/.claude/commands/workflows/workflow-execute.md +0 -25
  123. package/.claude/commands/workflows/workflow-export.md +0 -25
  124. package/.claude/helpers/github-setup.sh +0 -28
  125. package/.claude/helpers/quick-start.sh +0 -19
  126. package/.claude/helpers/setup-mcp.sh +0 -18
  127. package/dist/adapters/cliffy-node.d.ts +0 -45
  128. package/dist/adapters/cliffy-node.d.ts.map +0 -1
  129. package/dist/adapters/cliffy-node.js +0 -61
  130. package/dist/adapters/cliffy-node.js.map +0 -1
  131. package/dist/agents/agent-manager.d.ts +0 -191
  132. package/dist/agents/agent-manager.d.ts.map +0 -1
  133. package/dist/agents/agent-manager.js +0 -969
  134. package/dist/agents/agent-manager.js.map +0 -1
  135. package/dist/agents/agent-registry.d.ts +0 -112
  136. package/dist/agents/agent-registry.d.ts.map +0 -1
  137. package/dist/agents/agent-registry.js +0 -341
  138. package/dist/agents/agent-registry.js.map +0 -1
  139. package/dist/cli/agents/analyst.d.ts +0 -28
  140. package/dist/cli/agents/analyst.d.ts.map +0 -1
  141. package/dist/cli/agents/analyst.js +0 -718
  142. package/dist/cli/agents/analyst.js.map +0 -1
  143. package/dist/cli/agents/architect.d.ts +0 -27
  144. package/dist/cli/agents/architect.d.ts.map +0 -1
  145. package/dist/cli/agents/architect.js +0 -729
  146. package/dist/cli/agents/architect.js.map +0 -1
  147. package/dist/cli/agents/base-agent.d.ts +0 -80
  148. package/dist/cli/agents/base-agent.d.ts.map +0 -1
  149. package/dist/cli/agents/base-agent.js +0 -385
  150. package/dist/cli/agents/base-agent.js.map +0 -1
  151. package/dist/cli/agents/capabilities.d.ts +0 -106
  152. package/dist/cli/agents/capabilities.d.ts.map +0 -1
  153. package/dist/cli/agents/capabilities.js +0 -556
  154. package/dist/cli/agents/capabilities.js.map +0 -1
  155. package/dist/cli/agents/coder.d.ts +0 -34
  156. package/dist/cli/agents/coder.d.ts.map +0 -1
  157. package/dist/cli/agents/coder.js +0 -806
  158. package/dist/cli/agents/coder.js.map +0 -1
  159. package/dist/cli/agents/coordinator.d.ts +0 -25
  160. package/dist/cli/agents/coordinator.d.ts.map +0 -1
  161. package/dist/cli/agents/coordinator.js +0 -454
  162. package/dist/cli/agents/coordinator.js.map +0 -1
  163. package/dist/cli/agents/hive-agents.d.ts +0 -85
  164. package/dist/cli/agents/hive-agents.d.ts.map +0 -1
  165. package/dist/cli/agents/hive-agents.js +0 -549
  166. package/dist/cli/agents/hive-agents.js.map +0 -1
  167. package/dist/cli/agents/index.d.ts +0 -111
  168. package/dist/cli/agents/index.d.ts.map +0 -1
  169. package/dist/cli/agents/index.js +0 -276
  170. package/dist/cli/agents/index.js.map +0 -1
  171. package/dist/cli/agents/researcher.d.ts +0 -24
  172. package/dist/cli/agents/researcher.d.ts.map +0 -1
  173. package/dist/cli/agents/researcher.js +0 -356
  174. package/dist/cli/agents/researcher.js.map +0 -1
  175. package/dist/cli/agents/tester.d.ts +0 -27
  176. package/dist/cli/agents/tester.d.ts.map +0 -1
  177. package/dist/cli/agents/tester.js +0 -594
  178. package/dist/cli/agents/tester.js.map +0 -1
  179. package/dist/cli/cli-core.d.ts +0 -49
  180. package/dist/cli/cli-core.d.ts.map +0 -1
  181. package/dist/cli/cli-core.js +0 -263
  182. package/dist/cli/cli-core.js.map +0 -1
  183. package/dist/cli/commands/advanced-memory-commands.d.ts +0 -2
  184. package/dist/cli/commands/advanced-memory-commands.d.ts.map +0 -1
  185. package/dist/cli/commands/advanced-memory-commands.js +0 -849
  186. package/dist/cli/commands/advanced-memory-commands.js.map +0 -1
  187. package/dist/cli/commands/agent-simple.d.ts +0 -12
  188. package/dist/cli/commands/agent-simple.d.ts.map +0 -1
  189. package/dist/cli/commands/agent-simple.js +0 -353
  190. package/dist/cli/commands/agent-simple.js.map +0 -1
  191. package/dist/cli/commands/agent.d.ts +0 -7
  192. package/dist/cli/commands/agent.d.ts.map +0 -1
  193. package/dist/cli/commands/agent.js +0 -369
  194. package/dist/cli/commands/agent.js.map +0 -1
  195. package/dist/cli/commands/claude.d.ts +0 -3
  196. package/dist/cli/commands/claude.d.ts.map +0 -1
  197. package/dist/cli/commands/claude.js +0 -154
  198. package/dist/cli/commands/claude.js.map +0 -1
  199. package/dist/cli/commands/config-integration.d.ts +0 -10
  200. package/dist/cli/commands/config-integration.d.ts.map +0 -1
  201. package/dist/cli/commands/config-integration.js +0 -416
  202. package/dist/cli/commands/config-integration.js.map +0 -1
  203. package/dist/cli/commands/config.d.ts +0 -5
  204. package/dist/cli/commands/config.d.ts.map +0 -1
  205. package/dist/cli/commands/config.js +0 -89
  206. package/dist/cli/commands/config.js.map +0 -1
  207. package/dist/cli/commands/enterprise.d.ts +0 -3
  208. package/dist/cli/commands/enterprise.d.ts.map +0 -1
  209. package/dist/cli/commands/enterprise.js +0 -1486
  210. package/dist/cli/commands/enterprise.js.map +0 -1
  211. package/dist/cli/commands/help.d.ts +0 -6
  212. package/dist/cli/commands/help.d.ts.map +0 -1
  213. package/dist/cli/commands/help.js +0 -786
  214. package/dist/cli/commands/help.js.map +0 -1
  215. package/dist/cli/commands/hive-mind/index.d.ts +0 -15
  216. package/dist/cli/commands/hive-mind/index.d.ts.map +0 -1
  217. package/dist/cli/commands/hive-mind/index.js +0 -22
  218. package/dist/cli/commands/hive-mind/index.js.map +0 -1
  219. package/dist/cli/commands/hive-mind/init.d.ts +0 -10
  220. package/dist/cli/commands/hive-mind/init.d.ts.map +0 -1
  221. package/dist/cli/commands/hive-mind/init.js +0 -68
  222. package/dist/cli/commands/hive-mind/init.js.map +0 -1
  223. package/dist/cli/commands/hive-mind/optimize-memory.d.ts +0 -8
  224. package/dist/cli/commands/hive-mind/optimize-memory.d.ts.map +0 -1
  225. package/dist/cli/commands/hive-mind/optimize-memory.js +0 -391
  226. package/dist/cli/commands/hive-mind/optimize-memory.js.map +0 -1
  227. package/dist/cli/commands/hive-mind/spawn.d.ts +0 -10
  228. package/dist/cli/commands/hive-mind/spawn.d.ts.map +0 -1
  229. package/dist/cli/commands/hive-mind/spawn.js +0 -147
  230. package/dist/cli/commands/hive-mind/spawn.js.map +0 -1
  231. package/dist/cli/commands/hive-mind/status.d.ts +0 -10
  232. package/dist/cli/commands/hive-mind/status.d.ts.map +0 -1
  233. package/dist/cli/commands/hive-mind/status.js +0 -209
  234. package/dist/cli/commands/hive-mind/status.js.map +0 -1
  235. package/dist/cli/commands/hive-mind/task.d.ts +0 -10
  236. package/dist/cli/commands/hive-mind/task.d.ts.map +0 -1
  237. package/dist/cli/commands/hive-mind/task.js +0 -288
  238. package/dist/cli/commands/hive-mind/task.js.map +0 -1
  239. package/dist/cli/commands/hive-mind/wizard.d.ts +0 -10
  240. package/dist/cli/commands/hive-mind/wizard.d.ts.map +0 -1
  241. package/dist/cli/commands/hive-mind/wizard.js +0 -513
  242. package/dist/cli/commands/hive-mind/wizard.js.map +0 -1
  243. package/dist/cli/commands/hive.d.ts +0 -6
  244. package/dist/cli/commands/hive.d.ts.map +0 -1
  245. package/dist/cli/commands/hive.js +0 -374
  246. package/dist/cli/commands/hive.js.map +0 -1
  247. package/dist/cli/commands/index.d.ts +0 -3
  248. package/dist/cli/commands/index.d.ts.map +0 -1
  249. package/dist/cli/commands/index.js +0 -2416
  250. package/dist/cli/commands/index.js.map +0 -1
  251. package/dist/cli/commands/mcp.d.ts +0 -6
  252. package/dist/cli/commands/mcp.d.ts.map +0 -1
  253. package/dist/cli/commands/mcp.js +0 -177
  254. package/dist/cli/commands/mcp.js.map +0 -1
  255. package/dist/cli/commands/memory.d.ts +0 -30
  256. package/dist/cli/commands/memory.d.ts.map +0 -1
  257. package/dist/cli/commands/memory.js +0 -225
  258. package/dist/cli/commands/memory.js.map +0 -1
  259. package/dist/cli/commands/migrate.d.ts +0 -6
  260. package/dist/cli/commands/migrate.d.ts.map +0 -1
  261. package/dist/cli/commands/migrate.js +0 -139
  262. package/dist/cli/commands/migrate.js.map +0 -1
  263. package/dist/cli/commands/monitor.d.ts +0 -6
  264. package/dist/cli/commands/monitor.d.ts.map +0 -1
  265. package/dist/cli/commands/monitor.js +0 -477
  266. package/dist/cli/commands/monitor.js.map +0 -1
  267. package/dist/cli/commands/ruv-swarm.d.ts +0 -10
  268. package/dist/cli/commands/ruv-swarm.d.ts.map +0 -1
  269. package/dist/cli/commands/ruv-swarm.js +0 -563
  270. package/dist/cli/commands/ruv-swarm.js.map +0 -1
  271. package/dist/cli/commands/session.d.ts +0 -6
  272. package/dist/cli/commands/session.d.ts.map +0 -1
  273. package/dist/cli/commands/session.js +0 -543
  274. package/dist/cli/commands/session.js.map +0 -1
  275. package/dist/cli/commands/sparc.d.ts +0 -3
  276. package/dist/cli/commands/sparc.d.ts.map +0 -1
  277. package/dist/cli/commands/sparc.js +0 -452
  278. package/dist/cli/commands/sparc.js.map +0 -1
  279. package/dist/cli/commands/start/event-emitter.d.ts +0 -13
  280. package/dist/cli/commands/start/event-emitter.d.ts.map +0 -1
  281. package/dist/cli/commands/start/event-emitter.js +0 -35
  282. package/dist/cli/commands/start/event-emitter.js.map +0 -1
  283. package/dist/cli/commands/start/index.d.ts +0 -10
  284. package/dist/cli/commands/start/index.d.ts.map +0 -1
  285. package/dist/cli/commands/start/index.js +0 -9
  286. package/dist/cli/commands/start/index.js.map +0 -1
  287. package/dist/cli/commands/start/process-manager.d.ts +0 -31
  288. package/dist/cli/commands/start/process-manager.d.ts.map +0 -1
  289. package/dist/cli/commands/start/process-manager.js +0 -281
  290. package/dist/cli/commands/start/process-manager.js.map +0 -1
  291. package/dist/cli/commands/start/process-ui-simple.d.ts +0 -25
  292. package/dist/cli/commands/start/process-ui-simple.d.ts.map +0 -1
  293. package/dist/cli/commands/start/process-ui-simple.js +0 -334
  294. package/dist/cli/commands/start/process-ui-simple.js.map +0 -1
  295. package/dist/cli/commands/start/process-ui.d.ts +0 -5
  296. package/dist/cli/commands/start/process-ui.d.ts.map +0 -1
  297. package/dist/cli/commands/start/process-ui.js +0 -5
  298. package/dist/cli/commands/start/process-ui.js.map +0 -1
  299. package/dist/cli/commands/start/start-command.d.ts +0 -6
  300. package/dist/cli/commands/start/start-command.d.ts.map +0 -1
  301. package/dist/cli/commands/start/start-command.js +0 -450
  302. package/dist/cli/commands/start/start-command.js.map +0 -1
  303. package/dist/cli/commands/start/system-monitor.d.ts +0 -22
  304. package/dist/cli/commands/start/system-monitor.d.ts.map +0 -1
  305. package/dist/cli/commands/start/system-monitor.js +0 -267
  306. package/dist/cli/commands/start/system-monitor.js.map +0 -1
  307. package/dist/cli/commands/start/types.d.ts +0 -64
  308. package/dist/cli/commands/start/types.d.ts.map +0 -1
  309. package/dist/cli/commands/start/types.js +0 -22
  310. package/dist/cli/commands/start/types.js.map +0 -1
  311. package/dist/cli/commands/start.d.ts +0 -6
  312. package/dist/cli/commands/start.d.ts.map +0 -1
  313. package/dist/cli/commands/start.js +0 -6
  314. package/dist/cli/commands/start.js.map +0 -1
  315. package/dist/cli/commands/status.d.ts +0 -6
  316. package/dist/cli/commands/status.d.ts.map +0 -1
  317. package/dist/cli/commands/status.js +0 -312
  318. package/dist/cli/commands/status.js.map +0 -1
  319. package/dist/cli/commands/swarm-new.d.ts +0 -3
  320. package/dist/cli/commands/swarm-new.d.ts.map +0 -1
  321. package/dist/cli/commands/swarm-new.js +0 -989
  322. package/dist/cli/commands/swarm-new.js.map +0 -1
  323. package/dist/cli/commands/swarm-spawn.d.ts +0 -24
  324. package/dist/cli/commands/swarm-spawn.d.ts.map +0 -1
  325. package/dist/cli/commands/swarm-spawn.js +0 -61
  326. package/dist/cli/commands/swarm-spawn.js.map +0 -1
  327. package/dist/cli/commands/swarm.d.ts +0 -3
  328. package/dist/cli/commands/swarm.d.ts.map +0 -1
  329. package/dist/cli/commands/swarm.js +0 -460
  330. package/dist/cli/commands/swarm.js.map +0 -1
  331. package/dist/cli/commands/task.d.ts +0 -3
  332. package/dist/cli/commands/task.d.ts.map +0 -1
  333. package/dist/cli/commands/task.js +0 -29
  334. package/dist/cli/commands/task.js.map +0 -1
  335. package/dist/cli/commands/workflow.d.ts +0 -3
  336. package/dist/cli/commands/workflow.d.ts.map +0 -1
  337. package/dist/cli/commands/workflow.js +0 -23
  338. package/dist/cli/commands/workflow.js.map +0 -1
  339. package/dist/cli/completion.d.ts +0 -16
  340. package/dist/cli/completion.d.ts.map +0 -1
  341. package/dist/cli/completion.js +0 -535
  342. package/dist/cli/completion.js.map +0 -1
  343. package/dist/cli/formatter.d.ts +0 -66
  344. package/dist/cli/formatter.d.ts.map +0 -1
  345. package/dist/cli/formatter.js +0 -277
  346. package/dist/cli/formatter.js.map +0 -1
  347. package/dist/cli/index-remote.d.ts +0 -3
  348. package/dist/cli/index-remote.d.ts.map +0 -1
  349. package/dist/cli/index-remote.js +0 -126
  350. package/dist/cli/index-remote.js.map +0 -1
  351. package/dist/cli/index.d.ts +0 -7
  352. package/dist/cli/index.d.ts.map +0 -1
  353. package/dist/cli/index.js +0 -197
  354. package/dist/cli/index.js.map +0 -1
  355. package/dist/cli/init/batch-tools.d.ts +0 -2
  356. package/dist/cli/init/batch-tools.d.ts.map +0 -1
  357. package/dist/cli/init/batch-tools.js +0 -387
  358. package/dist/cli/init/batch-tools.js.map +0 -1
  359. package/dist/cli/init/claude-config.d.ts +0 -3
  360. package/dist/cli/init/claude-config.d.ts.map +0 -1
  361. package/dist/cli/init/claude-config.js +0 -289
  362. package/dist/cli/init/claude-config.js.map +0 -1
  363. package/dist/cli/init/directory-structure.d.ts +0 -2
  364. package/dist/cli/init/directory-structure.d.ts.map +0 -1
  365. package/dist/cli/init/directory-structure.js +0 -144
  366. package/dist/cli/init/directory-structure.js.map +0 -1
  367. package/dist/cli/init/index.d.ts +0 -6
  368. package/dist/cli/init/index.d.ts.map +0 -1
  369. package/dist/cli/init/index.js +0 -52
  370. package/dist/cli/init/index.js.map +0 -1
  371. package/dist/cli/init/sparc-environment.d.ts +0 -2
  372. package/dist/cli/init/sparc-environment.d.ts.map +0 -1
  373. package/dist/cli/init/sparc-environment.js +0 -426
  374. package/dist/cli/init/sparc-environment.js.map +0 -1
  375. package/dist/cli/init/swarm-commands.d.ts +0 -2
  376. package/dist/cli/init/swarm-commands.d.ts.map +0 -1
  377. package/dist/cli/init/swarm-commands.js +0 -795
  378. package/dist/cli/init/swarm-commands.js.map +0 -1
  379. package/dist/cli/init/utils.d.ts +0 -5
  380. package/dist/cli/init/utils.d.ts.map +0 -1
  381. package/dist/cli/init/utils.js +0 -14
  382. package/dist/cli/init/utils.js.map +0 -1
  383. package/dist/cli/main.d.ts +0 -3
  384. package/dist/cli/main.d.ts.map +0 -1
  385. package/dist/cli/main.js +0 -26
  386. package/dist/cli/main.js.map +0 -1
  387. package/dist/cli/node-repl.d.ts +0 -5
  388. package/dist/cli/node-repl.d.ts.map +0 -1
  389. package/dist/cli/node-repl.js +0 -677
  390. package/dist/cli/node-repl.js.map +0 -1
  391. package/dist/cli/repl.d.ts +0 -5
  392. package/dist/cli/repl.d.ts.map +0 -1
  393. package/dist/cli/repl.js +0 -909
  394. package/dist/cli/repl.js.map +0 -1
  395. package/dist/cli/simple-cli.d.ts +0 -3
  396. package/dist/cli/simple-cli.d.ts.map +0 -1
  397. package/dist/cli/simple-cli.js +0 -3059
  398. package/dist/cli/simple-cli.js.map +0 -1
  399. package/dist/cli/simple-mcp.d.ts +0 -6
  400. package/dist/cli/simple-mcp.d.ts.map +0 -1
  401. package/dist/cli/simple-mcp.js +0 -107
  402. package/dist/cli/simple-mcp.js.map +0 -1
  403. package/dist/cli/simple-orchestrator.d.ts +0 -16
  404. package/dist/cli/simple-orchestrator.d.ts.map +0 -1
  405. package/dist/cli/simple-orchestrator.js +0 -833
  406. package/dist/cli/simple-orchestrator.js.map +0 -1
  407. package/dist/cli/ui/compatible-ui.d.ts +0 -45
  408. package/dist/cli/ui/compatible-ui.d.ts.map +0 -1
  409. package/dist/cli/ui/compatible-ui.js +0 -318
  410. package/dist/cli/ui/compatible-ui.js.map +0 -1
  411. package/dist/cli/ui/fallback-handler.d.ts +0 -26
  412. package/dist/cli/ui/fallback-handler.d.ts.map +0 -1
  413. package/dist/cli/ui/fallback-handler.js +0 -163
  414. package/dist/cli/ui/fallback-handler.js.map +0 -1
  415. package/dist/cli/ui/index.d.ts +0 -11
  416. package/dist/cli/ui/index.d.ts.map +0 -1
  417. package/dist/cli/ui/index.js +0 -33
  418. package/dist/cli/ui/index.js.map +0 -1
  419. package/dist/cli/utils/environment-detector.d.ts +0 -52
  420. package/dist/cli/utils/environment-detector.d.ts.map +0 -1
  421. package/dist/cli/utils/environment-detector.js +0 -238
  422. package/dist/cli/utils/environment-detector.js.map +0 -1
  423. package/dist/cli/utils/prompt-defaults.d.ts +0 -82
  424. package/dist/cli/utils/prompt-defaults.d.ts.map +0 -1
  425. package/dist/cli/utils/prompt-defaults.js +0 -253
  426. package/dist/cli/utils/prompt-defaults.js.map +0 -1
  427. package/dist/communication/message-bus.d.ts +0 -283
  428. package/dist/communication/message-bus.d.ts.map +0 -1
  429. package/dist/communication/message-bus.js +0 -954
  430. package/dist/communication/message-bus.js.map +0 -1
  431. package/dist/config/config-manager.d.ts +0 -174
  432. package/dist/config/config-manager.d.ts.map +0 -1
  433. package/dist/config/config-manager.js +0 -443
  434. package/dist/config/config-manager.js.map +0 -1
  435. package/dist/config/ruv-swarm-config.d.ts +0 -167
  436. package/dist/config/ruv-swarm-config.d.ts.map +0 -1
  437. package/dist/config/ruv-swarm-config.js +0 -274
  438. package/dist/config/ruv-swarm-config.js.map +0 -1
  439. package/dist/config/ruv-swarm-integration.d.ts +0 -93
  440. package/dist/config/ruv-swarm-integration.d.ts.map +0 -1
  441. package/dist/config/ruv-swarm-integration.js +0 -292
  442. package/dist/config/ruv-swarm-integration.js.map +0 -1
  443. package/dist/constants/agent-types.d.ts +0 -46
  444. package/dist/constants/agent-types.d.ts.map +0 -1
  445. package/dist/constants/agent-types.js +0 -50
  446. package/dist/constants/agent-types.js.map +0 -1
  447. package/dist/coordination/advanced-scheduler.d.ts +0 -121
  448. package/dist/coordination/advanced-scheduler.d.ts.map +0 -1
  449. package/dist/coordination/advanced-scheduler.js +0 -386
  450. package/dist/coordination/advanced-scheduler.js.map +0 -1
  451. package/dist/coordination/advanced-task-executor.d.ts +0 -100
  452. package/dist/coordination/advanced-task-executor.d.ts.map +0 -1
  453. package/dist/coordination/advanced-task-executor.js +0 -459
  454. package/dist/coordination/advanced-task-executor.js.map +0 -1
  455. package/dist/coordination/background-executor.d.ts +0 -69
  456. package/dist/coordination/background-executor.d.ts.map +0 -1
  457. package/dist/coordination/background-executor.js +0 -362
  458. package/dist/coordination/background-executor.js.map +0 -1
  459. package/dist/coordination/circuit-breaker.d.ts +0 -124
  460. package/dist/coordination/circuit-breaker.d.ts.map +0 -1
  461. package/dist/coordination/circuit-breaker.js +0 -298
  462. package/dist/coordination/circuit-breaker.js.map +0 -1
  463. package/dist/coordination/conflict-resolution.d.ts +0 -133
  464. package/dist/coordination/conflict-resolution.d.ts.map +0 -1
  465. package/dist/coordination/conflict-resolution.js +0 -358
  466. package/dist/coordination/conflict-resolution.js.map +0 -1
  467. package/dist/coordination/dependency-graph.d.ts +0 -78
  468. package/dist/coordination/dependency-graph.d.ts.map +0 -1
  469. package/dist/coordination/dependency-graph.js +0 -386
  470. package/dist/coordination/dependency-graph.js.map +0 -1
  471. package/dist/coordination/hive-orchestrator.d.ts +0 -118
  472. package/dist/coordination/hive-orchestrator.d.ts.map +0 -1
  473. package/dist/coordination/hive-orchestrator.js +0 -321
  474. package/dist/coordination/hive-orchestrator.js.map +0 -1
  475. package/dist/coordination/hive-protocol.d.ts +0 -117
  476. package/dist/coordination/hive-protocol.d.ts.map +0 -1
  477. package/dist/coordination/hive-protocol.js +0 -373
  478. package/dist/coordination/hive-protocol.js.map +0 -1
  479. package/dist/coordination/index.d.ts +0 -14
  480. package/dist/coordination/index.d.ts.map +0 -1
  481. package/dist/coordination/index.js +0 -21
  482. package/dist/coordination/index.js.map +0 -1
  483. package/dist/coordination/load-balancer.d.ts +0 -139
  484. package/dist/coordination/load-balancer.d.ts.map +0 -1
  485. package/dist/coordination/load-balancer.js +0 -691
  486. package/dist/coordination/load-balancer.js.map +0 -1
  487. package/dist/coordination/manager.d.ts +0 -66
  488. package/dist/coordination/manager.d.ts.map +0 -1
  489. package/dist/coordination/manager.js +0 -360
  490. package/dist/coordination/manager.js.map +0 -1
  491. package/dist/coordination/messaging.d.ts +0 -37
  492. package/dist/coordination/messaging.d.ts.map +0 -1
  493. package/dist/coordination/messaging.js +0 -219
  494. package/dist/coordination/messaging.js.map +0 -1
  495. package/dist/coordination/metrics.d.ts +0 -153
  496. package/dist/coordination/metrics.d.ts.map +0 -1
  497. package/dist/coordination/metrics.js +0 -434
  498. package/dist/coordination/metrics.js.map +0 -1
  499. package/dist/coordination/resources.d.ts +0 -36
  500. package/dist/coordination/resources.d.ts.map +0 -1
  501. package/dist/coordination/resources.js +0 -250
  502. package/dist/coordination/resources.js.map +0 -1
  503. package/dist/coordination/scheduler.d.ts +0 -48
  504. package/dist/coordination/scheduler.d.ts.map +0 -1
  505. package/dist/coordination/scheduler.js +0 -308
  506. package/dist/coordination/scheduler.js.map +0 -1
  507. package/dist/coordination/swarm-coordinator.d.ts +0 -116
  508. package/dist/coordination/swarm-coordinator.d.ts.map +0 -1
  509. package/dist/coordination/swarm-coordinator.js +0 -565
  510. package/dist/coordination/swarm-coordinator.js.map +0 -1
  511. package/dist/coordination/swarm-monitor.d.ts +0 -101
  512. package/dist/coordination/swarm-monitor.d.ts.map +0 -1
  513. package/dist/coordination/swarm-monitor.js +0 -340
  514. package/dist/coordination/swarm-monitor.js.map +0 -1
  515. package/dist/coordination/work-stealing.d.ts +0 -44
  516. package/dist/coordination/work-stealing.d.ts.map +0 -1
  517. package/dist/coordination/work-stealing.js +0 -155
  518. package/dist/coordination/work-stealing.js.map +0 -1
  519. package/dist/core/config.d.ts +0 -239
  520. package/dist/core/config.d.ts.map +0 -1
  521. package/dist/core/config.js +0 -1128
  522. package/dist/core/config.js.map +0 -1
  523. package/dist/core/event-bus.d.ts +0 -60
  524. package/dist/core/event-bus.d.ts.map +0 -1
  525. package/dist/core/event-bus.js +0 -153
  526. package/dist/core/event-bus.js.map +0 -1
  527. package/dist/core/json-persistence.d.ts +0 -52
  528. package/dist/core/json-persistence.d.ts.map +0 -1
  529. package/dist/core/json-persistence.js +0 -115
  530. package/dist/core/json-persistence.js.map +0 -1
  531. package/dist/core/logger.d.ts +0 -57
  532. package/dist/core/logger.d.ts.map +0 -1
  533. package/dist/core/logger.js +0 -253
  534. package/dist/core/logger.js.map +0 -1
  535. package/dist/core/orchestrator-fixed.d.ts +0 -81
  536. package/dist/core/orchestrator-fixed.d.ts.map +0 -1
  537. package/dist/core/orchestrator-fixed.js +0 -210
  538. package/dist/core/orchestrator-fixed.js.map +0 -1
  539. package/dist/core/orchestrator.d.ts +0 -103
  540. package/dist/core/orchestrator.d.ts.map +0 -1
  541. package/dist/core/orchestrator.js +0 -965
  542. package/dist/core/orchestrator.js.map +0 -1
  543. package/dist/core/persistence.d.ts +0 -50
  544. package/dist/core/persistence.d.ts.map +0 -1
  545. package/dist/core/persistence.js +0 -186
  546. package/dist/core/persistence.js.map +0 -1
  547. package/dist/enterprise/analytics-manager.d.ts +0 -489
  548. package/dist/enterprise/analytics-manager.d.ts.map +0 -1
  549. package/dist/enterprise/analytics-manager.js +0 -949
  550. package/dist/enterprise/analytics-manager.js.map +0 -1
  551. package/dist/enterprise/audit-manager.d.ts +0 -459
  552. package/dist/enterprise/audit-manager.d.ts.map +0 -1
  553. package/dist/enterprise/audit-manager.js +0 -992
  554. package/dist/enterprise/audit-manager.js.map +0 -1
  555. package/dist/enterprise/cloud-manager.d.ts +0 -435
  556. package/dist/enterprise/cloud-manager.d.ts.map +0 -1
  557. package/dist/enterprise/cloud-manager.js +0 -784
  558. package/dist/enterprise/cloud-manager.js.map +0 -1
  559. package/dist/enterprise/deployment-manager.d.ts +0 -328
  560. package/dist/enterprise/deployment-manager.d.ts.map +0 -1
  561. package/dist/enterprise/deployment-manager.js +0 -823
  562. package/dist/enterprise/deployment-manager.js.map +0 -1
  563. package/dist/enterprise/index.d.ts +0 -13
  564. package/dist/enterprise/index.d.ts.map +0 -1
  565. package/dist/enterprise/index.js +0 -7
  566. package/dist/enterprise/index.js.map +0 -1
  567. package/dist/enterprise/project-manager.d.ts +0 -228
  568. package/dist/enterprise/project-manager.d.ts.map +0 -1
  569. package/dist/enterprise/project-manager.js +0 -529
  570. package/dist/enterprise/project-manager.js.map +0 -1
  571. package/dist/enterprise/security-manager.d.ts +0 -422
  572. package/dist/enterprise/security-manager.d.ts.map +0 -1
  573. package/dist/enterprise/security-manager.js +0 -902
  574. package/dist/enterprise/security-manager.js.map +0 -1
  575. package/dist/hive-mind/core/Agent.d.ts +0 -137
  576. package/dist/hive-mind/core/Agent.d.ts.map +0 -1
  577. package/dist/hive-mind/core/Agent.js +0 -567
  578. package/dist/hive-mind/core/Agent.js.map +0 -1
  579. package/dist/hive-mind/core/Communication.d.ts +0 -116
  580. package/dist/hive-mind/core/Communication.d.ts.map +0 -1
  581. package/dist/hive-mind/core/Communication.js +0 -407
  582. package/dist/hive-mind/core/Communication.js.map +0 -1
  583. package/dist/hive-mind/core/DatabaseManager.d.ts +0 -93
  584. package/dist/hive-mind/core/DatabaseManager.d.ts.map +0 -1
  585. package/dist/hive-mind/core/DatabaseManager.js +0 -551
  586. package/dist/hive-mind/core/DatabaseManager.js.map +0 -1
  587. package/dist/hive-mind/core/HiveMind.d.ts +0 -90
  588. package/dist/hive-mind/core/HiveMind.d.ts.map +0 -1
  589. package/dist/hive-mind/core/HiveMind.js +0 -439
  590. package/dist/hive-mind/core/HiveMind.js.map +0 -1
  591. package/dist/hive-mind/core/Memory.d.ts +0 -235
  592. package/dist/hive-mind/core/Memory.d.ts.map +0 -1
  593. package/dist/hive-mind/core/Memory.js +0 -1185
  594. package/dist/hive-mind/core/Memory.js.map +0 -1
  595. package/dist/hive-mind/core/MemoryMonitor.d.ts +0 -183
  596. package/dist/hive-mind/core/MemoryMonitor.d.ts.map +0 -1
  597. package/dist/hive-mind/core/MemoryMonitor.js +0 -547
  598. package/dist/hive-mind/core/MemoryMonitor.js.map +0 -1
  599. package/dist/hive-mind/core/Queen.d.ts +0 -115
  600. package/dist/hive-mind/core/Queen.d.ts.map +0 -1
  601. package/dist/hive-mind/core/Queen.js +0 -586
  602. package/dist/hive-mind/core/Queen.js.map +0 -1
  603. package/dist/hive-mind/index.d.ts +0 -17
  604. package/dist/hive-mind/index.d.ts.map +0 -1
  605. package/dist/hive-mind/index.js +0 -21
  606. package/dist/hive-mind/index.js.map +0 -1
  607. package/dist/hive-mind/integration/ConsensusEngine.d.ts +0 -117
  608. package/dist/hive-mind/integration/ConsensusEngine.d.ts.map +0 -1
  609. package/dist/hive-mind/integration/ConsensusEngine.js +0 -476
  610. package/dist/hive-mind/integration/ConsensusEngine.js.map +0 -1
  611. package/dist/hive-mind/integration/MCPToolWrapper.d.ts +0 -172
  612. package/dist/hive-mind/integration/MCPToolWrapper.d.ts.map +0 -1
  613. package/dist/hive-mind/integration/MCPToolWrapper.js +0 -216
  614. package/dist/hive-mind/integration/MCPToolWrapper.js.map +0 -1
  615. package/dist/hive-mind/integration/SwarmOrchestrator.d.ts +0 -172
  616. package/dist/hive-mind/integration/SwarmOrchestrator.d.ts.map +0 -1
  617. package/dist/hive-mind/integration/SwarmOrchestrator.js +0 -746
  618. package/dist/hive-mind/integration/SwarmOrchestrator.js.map +0 -1
  619. package/dist/hive-mind/types.d.ts +0 -298
  620. package/dist/hive-mind/types.d.ts.map +0 -1
  621. package/dist/hive-mind/types.js +0 -7
  622. package/dist/hive-mind/types.js.map +0 -1
  623. package/dist/integration/mock-components.d.ts +0 -107
  624. package/dist/integration/mock-components.d.ts.map +0 -1
  625. package/dist/integration/mock-components.js +0 -357
  626. package/dist/integration/mock-components.js.map +0 -1
  627. package/dist/integration/system-integration.d.ts +0 -84
  628. package/dist/integration/system-integration.d.ts.map +0 -1
  629. package/dist/integration/system-integration.js +0 -429
  630. package/dist/integration/system-integration.js.map +0 -1
  631. package/dist/integration/types.d.ts +0 -119
  632. package/dist/integration/types.d.ts.map +0 -1
  633. package/dist/integration/types.js +0 -5
  634. package/dist/integration/types.js.map +0 -1
  635. package/dist/mcp/auth.d.ts +0 -80
  636. package/dist/mcp/auth.d.ts.map +0 -1
  637. package/dist/mcp/auth.js +0 -343
  638. package/dist/mcp/auth.js.map +0 -1
  639. package/dist/mcp/claude-code-wrapper.d.ts +0 -26
  640. package/dist/mcp/claude-code-wrapper.d.ts.map +0 -1
  641. package/dist/mcp/claude-code-wrapper.js +0 -598
  642. package/dist/mcp/claude-code-wrapper.js.map +0 -1
  643. package/dist/mcp/claude-flow-tools.d.ts +0 -13
  644. package/dist/mcp/claude-flow-tools.d.ts.map +0 -1
  645. package/dist/mcp/claude-flow-tools.js +0 -1142
  646. package/dist/mcp/claude-flow-tools.js.map +0 -1
  647. package/dist/mcp/client.d.ts +0 -41
  648. package/dist/mcp/client.d.ts.map +0 -1
  649. package/dist/mcp/client.js +0 -194
  650. package/dist/mcp/client.js.map +0 -1
  651. package/dist/mcp/index.d.ts +0 -134
  652. package/dist/mcp/index.d.ts.map +0 -1
  653. package/dist/mcp/index.js +0 -212
  654. package/dist/mcp/index.js.map +0 -1
  655. package/dist/mcp/integrate-wrapper.d.ts +0 -16
  656. package/dist/mcp/integrate-wrapper.d.ts.map +0 -1
  657. package/dist/mcp/integrate-wrapper.js +0 -77
  658. package/dist/mcp/integrate-wrapper.js.map +0 -1
  659. package/dist/mcp/lifecycle-manager.d.ts +0 -121
  660. package/dist/mcp/lifecycle-manager.d.ts.map +0 -1
  661. package/dist/mcp/lifecycle-manager.js +0 -365
  662. package/dist/mcp/lifecycle-manager.js.map +0 -1
  663. package/dist/mcp/load-balancer.d.ts +0 -88
  664. package/dist/mcp/load-balancer.d.ts.map +0 -1
  665. package/dist/mcp/load-balancer.js +0 -389
  666. package/dist/mcp/load-balancer.js.map +0 -1
  667. package/dist/mcp/orchestration-integration.d.ts +0 -135
  668. package/dist/mcp/orchestration-integration.d.ts.map +0 -1
  669. package/dist/mcp/orchestration-integration.js +0 -722
  670. package/dist/mcp/orchestration-integration.js.map +0 -1
  671. package/dist/mcp/performance-monitor.d.ts +0 -164
  672. package/dist/mcp/performance-monitor.d.ts.map +0 -1
  673. package/dist/mcp/performance-monitor.js +0 -478
  674. package/dist/mcp/performance-monitor.js.map +0 -1
  675. package/dist/mcp/protocol-manager.d.ts +0 -88
  676. package/dist/mcp/protocol-manager.d.ts.map +0 -1
  677. package/dist/mcp/protocol-manager.js +0 -358
  678. package/dist/mcp/protocol-manager.js.map +0 -1
  679. package/dist/mcp/recovery/connection-health-monitor.d.ts +0 -69
  680. package/dist/mcp/recovery/connection-health-monitor.d.ts.map +0 -1
  681. package/dist/mcp/recovery/connection-health-monitor.js +0 -241
  682. package/dist/mcp/recovery/connection-health-monitor.js.map +0 -1
  683. package/dist/mcp/recovery/connection-state-manager.d.ts +0 -102
  684. package/dist/mcp/recovery/connection-state-manager.d.ts.map +0 -1
  685. package/dist/mcp/recovery/connection-state-manager.js +0 -318
  686. package/dist/mcp/recovery/connection-state-manager.js.map +0 -1
  687. package/dist/mcp/recovery/fallback-coordinator.d.ts +0 -79
  688. package/dist/mcp/recovery/fallback-coordinator.d.ts.map +0 -1
  689. package/dist/mcp/recovery/fallback-coordinator.js +0 -278
  690. package/dist/mcp/recovery/fallback-coordinator.js.map +0 -1
  691. package/dist/mcp/recovery/index.d.ts +0 -10
  692. package/dist/mcp/recovery/index.d.ts.map +0 -1
  693. package/dist/mcp/recovery/index.js +0 -10
  694. package/dist/mcp/recovery/index.js.map +0 -1
  695. package/dist/mcp/recovery/reconnection-manager.d.ts +0 -69
  696. package/dist/mcp/recovery/reconnection-manager.d.ts.map +0 -1
  697. package/dist/mcp/recovery/reconnection-manager.js +0 -226
  698. package/dist/mcp/recovery/reconnection-manager.js.map +0 -1
  699. package/dist/mcp/recovery/recovery-manager.d.ts +0 -93
  700. package/dist/mcp/recovery/recovery-manager.d.ts.map +0 -1
  701. package/dist/mcp/recovery/recovery-manager.js +0 -250
  702. package/dist/mcp/recovery/recovery-manager.js.map +0 -1
  703. package/dist/mcp/router.d.ts +0 -54
  704. package/dist/mcp/router.d.ts.map +0 -1
  705. package/dist/mcp/router.js +0 -201
  706. package/dist/mcp/router.js.map +0 -1
  707. package/dist/mcp/ruv-swarm-tools.d.ts +0 -58
  708. package/dist/mcp/ruv-swarm-tools.d.ts.map +0 -1
  709. package/dist/mcp/ruv-swarm-tools.js +0 -518
  710. package/dist/mcp/ruv-swarm-tools.js.map +0 -1
  711. package/dist/mcp/server-with-wrapper.d.ts +0 -3
  712. package/dist/mcp/server-with-wrapper.d.ts.map +0 -1
  713. package/dist/mcp/server-with-wrapper.js +0 -36
  714. package/dist/mcp/server-with-wrapper.js.map +0 -1
  715. package/dist/mcp/server-wrapper-mode.d.ts +0 -3
  716. package/dist/mcp/server-wrapper-mode.d.ts.map +0 -1
  717. package/dist/mcp/server-wrapper-mode.js +0 -28
  718. package/dist/mcp/server-wrapper-mode.js.map +0 -1
  719. package/dist/mcp/server.d.ts +0 -75
  720. package/dist/mcp/server.d.ts.map +0 -1
  721. package/dist/mcp/server.js +0 -533
  722. package/dist/mcp/server.js.map +0 -1
  723. package/dist/mcp/session-manager.d.ts +0 -60
  724. package/dist/mcp/session-manager.d.ts.map +0 -1
  725. package/dist/mcp/session-manager.js +0 -322
  726. package/dist/mcp/session-manager.js.map +0 -1
  727. package/dist/mcp/sparc-modes.d.ts +0 -12
  728. package/dist/mcp/sparc-modes.d.ts.map +0 -1
  729. package/dist/mcp/sparc-modes.js +0 -370
  730. package/dist/mcp/sparc-modes.js.map +0 -1
  731. package/dist/mcp/swarm-tools.d.ts +0 -87
  732. package/dist/mcp/swarm-tools.d.ts.map +0 -1
  733. package/dist/mcp/swarm-tools.js +0 -711
  734. package/dist/mcp/swarm-tools.js.map +0 -1
  735. package/dist/mcp/tools.d.ts +0 -145
  736. package/dist/mcp/tools.d.ts.map +0 -1
  737. package/dist/mcp/tools.js +0 -418
  738. package/dist/mcp/tools.js.map +0 -1
  739. package/dist/mcp/transports/base.d.ts +0 -22
  740. package/dist/mcp/transports/base.d.ts.map +0 -1
  741. package/dist/mcp/transports/base.js +0 -2
  742. package/dist/mcp/transports/base.js.map +0 -1
  743. package/dist/mcp/transports/http.d.ts +0 -45
  744. package/dist/mcp/transports/http.d.ts.map +0 -1
  745. package/dist/mcp/transports/http.js +0 -400
  746. package/dist/mcp/transports/http.js.map +0 -1
  747. package/dist/mcp/transports/stdio.d.ts +0 -34
  748. package/dist/mcp/transports/stdio.d.ts.map +0 -1
  749. package/dist/mcp/transports/stdio.js +0 -203
  750. package/dist/mcp/transports/stdio.js.map +0 -1
  751. package/dist/memory/advanced-memory-manager.d.ts +0 -303
  752. package/dist/memory/advanced-memory-manager.d.ts.map +0 -1
  753. package/dist/memory/advanced-memory-manager.js +0 -1458
  754. package/dist/memory/advanced-memory-manager.js.map +0 -1
  755. package/dist/memory/backends/base.d.ts +0 -21
  756. package/dist/memory/backends/base.d.ts.map +0 -1
  757. package/dist/memory/backends/base.js +0 -2
  758. package/dist/memory/backends/base.js.map +0 -1
  759. package/dist/memory/backends/markdown.d.ts +0 -32
  760. package/dist/memory/backends/markdown.d.ts.map +0 -1
  761. package/dist/memory/backends/markdown.js +0 -223
  762. package/dist/memory/backends/markdown.js.map +0 -1
  763. package/dist/memory/backends/sqlite.d.ts +0 -29
  764. package/dist/memory/backends/sqlite.d.ts.map +0 -1
  765. package/dist/memory/backends/sqlite.js +0 -272
  766. package/dist/memory/backends/sqlite.js.map +0 -1
  767. package/dist/memory/cache.d.ts +0 -65
  768. package/dist/memory/cache.d.ts.map +0 -1
  769. package/dist/memory/cache.js +0 -186
  770. package/dist/memory/cache.js.map +0 -1
  771. package/dist/memory/distributed-memory.d.ts +0 -188
  772. package/dist/memory/distributed-memory.d.ts.map +0 -1
  773. package/dist/memory/distributed-memory.js +0 -711
  774. package/dist/memory/distributed-memory.js.map +0 -1
  775. package/dist/memory/indexer.d.ts +0 -52
  776. package/dist/memory/indexer.d.ts.map +0 -1
  777. package/dist/memory/indexer.js +0 -188
  778. package/dist/memory/indexer.js.map +0 -1
  779. package/dist/memory/manager.d.ts +0 -58
  780. package/dist/memory/manager.d.ts.map +0 -1
  781. package/dist/memory/manager.js +0 -426
  782. package/dist/memory/manager.js.map +0 -1
  783. package/dist/memory/swarm-memory.d.ts +0 -91
  784. package/dist/memory/swarm-memory.d.ts.map +0 -1
  785. package/dist/memory/swarm-memory.js +0 -461
  786. package/dist/memory/swarm-memory.js.map +0 -1
  787. package/dist/migration/index.d.ts +0 -3
  788. package/dist/migration/index.d.ts.map +0 -1
  789. package/dist/migration/index.js +0 -166
  790. package/dist/migration/index.js.map +0 -1
  791. package/dist/migration/logger.d.ts +0 -26
  792. package/dist/migration/logger.d.ts.map +0 -1
  793. package/dist/migration/logger.js +0 -145
  794. package/dist/migration/logger.js.map +0 -1
  795. package/dist/migration/migration-analyzer.d.ts +0 -15
  796. package/dist/migration/migration-analyzer.d.ts.map +0 -1
  797. package/dist/migration/migration-analyzer.js +0 -279
  798. package/dist/migration/migration-analyzer.js.map +0 -1
  799. package/dist/migration/migration-runner.d.ts +0 -26
  800. package/dist/migration/migration-runner.d.ts.map +0 -1
  801. package/dist/migration/migration-runner.js +0 -499
  802. package/dist/migration/migration-runner.js.map +0 -1
  803. package/dist/migration/migration-validator.d.ts +0 -14
  804. package/dist/migration/migration-validator.d.ts.map +0 -1
  805. package/dist/migration/migration-validator.js +0 -313
  806. package/dist/migration/migration-validator.js.map +0 -1
  807. package/dist/migration/progress-reporter.d.ts +0 -25
  808. package/dist/migration/progress-reporter.d.ts.map +0 -1
  809. package/dist/migration/progress-reporter.js +0 -163
  810. package/dist/migration/progress-reporter.js.map +0 -1
  811. package/dist/migration/rollback-manager.d.ts +0 -21
  812. package/dist/migration/rollback-manager.d.ts.map +0 -1
  813. package/dist/migration/rollback-manager.js +0 -348
  814. package/dist/migration/rollback-manager.js.map +0 -1
  815. package/dist/migration/types.d.ts +0 -103
  816. package/dist/migration/types.d.ts.map +0 -1
  817. package/dist/migration/types.js +0 -6
  818. package/dist/migration/types.js.map +0 -1
  819. package/dist/monitoring/diagnostics.d.ts +0 -109
  820. package/dist/monitoring/diagnostics.d.ts.map +0 -1
  821. package/dist/monitoring/diagnostics.js +0 -545
  822. package/dist/monitoring/diagnostics.js.map +0 -1
  823. package/dist/monitoring/health-check.d.ts +0 -91
  824. package/dist/monitoring/health-check.d.ts.map +0 -1
  825. package/dist/monitoring/health-check.js +0 -371
  826. package/dist/monitoring/health-check.js.map +0 -1
  827. package/dist/monitoring/real-time-monitor.d.ts +0 -230
  828. package/dist/monitoring/real-time-monitor.d.ts.map +0 -1
  829. package/dist/monitoring/real-time-monitor.js +0 -839
  830. package/dist/monitoring/real-time-monitor.js.map +0 -1
  831. package/dist/resources/resource-manager.d.ts +0 -390
  832. package/dist/resources/resource-manager.d.ts.map +0 -1
  833. package/dist/resources/resource-manager.js +0 -1220
  834. package/dist/resources/resource-manager.js.map +0 -1
  835. package/dist/swarm/claude-flow-executor.d.ts +0 -28
  836. package/dist/swarm/claude-flow-executor.d.ts.map +0 -1
  837. package/dist/swarm/claude-flow-executor.js +0 -210
  838. package/dist/swarm/claude-flow-executor.js.map +0 -1
  839. package/dist/swarm/coordinator.d.ts +0 -134
  840. package/dist/swarm/coordinator.d.ts.map +0 -1
  841. package/dist/swarm/coordinator.js +0 -2607
  842. package/dist/swarm/coordinator.js.map +0 -1
  843. package/dist/swarm/direct-executor.d.ts +0 -48
  844. package/dist/swarm/direct-executor.d.ts.map +0 -1
  845. package/dist/swarm/direct-executor.js +0 -1113
  846. package/dist/swarm/direct-executor.js.map +0 -1
  847. package/dist/swarm/executor-v2.d.ts +0 -23
  848. package/dist/swarm/executor-v2.d.ts.map +0 -1
  849. package/dist/swarm/executor-v2.js +0 -320
  850. package/dist/swarm/executor-v2.js.map +0 -1
  851. package/dist/swarm/executor.d.ts +0 -117
  852. package/dist/swarm/executor.d.ts.map +0 -1
  853. package/dist/swarm/executor.js +0 -791
  854. package/dist/swarm/executor.js.map +0 -1
  855. package/dist/swarm/index.d.ts +0 -31
  856. package/dist/swarm/index.d.ts.map +0 -1
  857. package/dist/swarm/index.js +0 -42
  858. package/dist/swarm/index.js.map +0 -1
  859. package/dist/swarm/memory.d.ts +0 -176
  860. package/dist/swarm/memory.d.ts.map +0 -1
  861. package/dist/swarm/memory.js +0 -1068
  862. package/dist/swarm/memory.js.map +0 -1
  863. package/dist/swarm/optimizations/async-file-manager.d.ts +0 -49
  864. package/dist/swarm/optimizations/async-file-manager.d.ts.map +0 -1
  865. package/dist/swarm/optimizations/async-file-manager.js +0 -248
  866. package/dist/swarm/optimizations/async-file-manager.js.map +0 -1
  867. package/dist/swarm/optimizations/circular-buffer.d.ts +0 -46
  868. package/dist/swarm/optimizations/circular-buffer.d.ts.map +0 -1
  869. package/dist/swarm/optimizations/circular-buffer.js +0 -159
  870. package/dist/swarm/optimizations/circular-buffer.js.map +0 -1
  871. package/dist/swarm/optimizations/connection-pool.d.ts +0 -54
  872. package/dist/swarm/optimizations/connection-pool.d.ts.map +0 -1
  873. package/dist/swarm/optimizations/connection-pool.js +0 -227
  874. package/dist/swarm/optimizations/connection-pool.js.map +0 -1
  875. package/dist/swarm/optimizations/index.d.ts +0 -24
  876. package/dist/swarm/optimizations/index.d.ts.map +0 -1
  877. package/dist/swarm/optimizations/index.js +0 -30
  878. package/dist/swarm/optimizations/index.js.map +0 -1
  879. package/dist/swarm/optimizations/optimized-executor.d.ts +0 -109
  880. package/dist/swarm/optimizations/optimized-executor.d.ts.map +0 -1
  881. package/dist/swarm/optimizations/optimized-executor.js +0 -321
  882. package/dist/swarm/optimizations/optimized-executor.js.map +0 -1
  883. package/dist/swarm/optimizations/ttl-map.d.ts +0 -78
  884. package/dist/swarm/optimizations/ttl-map.d.ts.map +0 -1
  885. package/dist/swarm/optimizations/ttl-map.js +0 -229
  886. package/dist/swarm/optimizations/ttl-map.js.map +0 -1
  887. package/dist/swarm/prompt-cli.d.ts +0 -5
  888. package/dist/swarm/prompt-cli.d.ts.map +0 -1
  889. package/dist/swarm/prompt-cli.js +0 -256
  890. package/dist/swarm/prompt-cli.js.map +0 -1
  891. package/dist/swarm/prompt-copier-enhanced.d.ts +0 -17
  892. package/dist/swarm/prompt-copier-enhanced.d.ts.map +0 -1
  893. package/dist/swarm/prompt-copier-enhanced.js +0 -190
  894. package/dist/swarm/prompt-copier-enhanced.js.map +0 -1
  895. package/dist/swarm/prompt-copier.d.ts +0 -76
  896. package/dist/swarm/prompt-copier.d.ts.map +0 -1
  897. package/dist/swarm/prompt-copier.js +0 -379
  898. package/dist/swarm/prompt-copier.js.map +0 -1
  899. package/dist/swarm/prompt-manager.d.ts +0 -72
  900. package/dist/swarm/prompt-manager.d.ts.map +0 -1
  901. package/dist/swarm/prompt-manager.js +0 -270
  902. package/dist/swarm/prompt-manager.js.map +0 -1
  903. package/dist/swarm/prompt-utils.d.ts +0 -52
  904. package/dist/swarm/prompt-utils.d.ts.map +0 -1
  905. package/dist/swarm/prompt-utils.js +0 -265
  906. package/dist/swarm/prompt-utils.js.map +0 -1
  907. package/dist/swarm/sparc-executor.d.ts +0 -105
  908. package/dist/swarm/sparc-executor.d.ts.map +0 -1
  909. package/dist/swarm/sparc-executor.js +0 -1364
  910. package/dist/swarm/sparc-executor.js.map +0 -1
  911. package/dist/swarm/strategies/auto.d.ts +0 -57
  912. package/dist/swarm/strategies/auto.d.ts.map +0 -1
  913. package/dist/swarm/strategies/auto.js +0 -623
  914. package/dist/swarm/strategies/auto.js.map +0 -1
  915. package/dist/swarm/strategies/base.d.ts +0 -78
  916. package/dist/swarm/strategies/base.d.ts.map +0 -1
  917. package/dist/swarm/strategies/base.js +0 -108
  918. package/dist/swarm/strategies/base.js.map +0 -1
  919. package/dist/swarm/strategies/research.d.ts +0 -75
  920. package/dist/swarm/strategies/research.d.ts.map +0 -1
  921. package/dist/swarm/strategies/research.js +0 -841
  922. package/dist/swarm/strategies/research.js.map +0 -1
  923. package/dist/swarm/strategies/strategy-metrics-patch.d.ts +0 -11
  924. package/dist/swarm/strategies/strategy-metrics-patch.d.ts.map +0 -1
  925. package/dist/swarm/strategies/strategy-metrics-patch.js +0 -2
  926. package/dist/swarm/strategies/strategy-metrics-patch.js.map +0 -1
  927. package/dist/swarm/types.d.ts +0 -578
  928. package/dist/swarm/types.d.ts.map +0 -1
  929. package/dist/swarm/types.js +0 -51
  930. package/dist/swarm/types.js.map +0 -1
  931. package/dist/swarm/workers/copy-worker.d.ts +0 -2
  932. package/dist/swarm/workers/copy-worker.d.ts.map +0 -1
  933. package/dist/swarm/workers/copy-worker.js +0 -56
  934. package/dist/swarm/workers/copy-worker.js.map +0 -1
  935. package/dist/task/commands.d.ts +0 -60
  936. package/dist/task/commands.d.ts.map +0 -1
  937. package/dist/task/commands.js +0 -107
  938. package/dist/task/commands.js.map +0 -1
  939. package/dist/task/coordination.d.ts +0 -109
  940. package/dist/task/coordination.d.ts.map +0 -1
  941. package/dist/task/coordination.js +0 -629
  942. package/dist/task/coordination.js.map +0 -1
  943. package/dist/task/engine.d.ts +0 -198
  944. package/dist/task/engine.d.ts.map +0 -1
  945. package/dist/task/engine.js +0 -498
  946. package/dist/task/engine.js.map +0 -1
  947. package/dist/task/index.d.ts +0 -103
  948. package/dist/task/index.d.ts.map +0 -1
  949. package/dist/task/index.js +0 -276
  950. package/dist/task/index.js.map +0 -1
  951. package/dist/task/types.d.ts +0 -56
  952. package/dist/task/types.d.ts.map +0 -1
  953. package/dist/task/types.js +0 -2
  954. package/dist/task/types.js.map +0 -1
  955. package/dist/terminal/adapters/base.d.ts +0 -40
  956. package/dist/terminal/adapters/base.d.ts.map +0 -1
  957. package/dist/terminal/adapters/base.js +0 -5
  958. package/dist/terminal/adapters/base.js.map +0 -1
  959. package/dist/terminal/adapters/native.d.ts +0 -19
  960. package/dist/terminal/adapters/native.d.ts.map +0 -1
  961. package/dist/terminal/adapters/native.js +0 -414
  962. package/dist/terminal/adapters/native.js.map +0 -1
  963. package/dist/terminal/adapters/vscode.d.ts +0 -20
  964. package/dist/terminal/adapters/vscode.d.ts.map +0 -1
  965. package/dist/terminal/adapters/vscode.js +0 -265
  966. package/dist/terminal/adapters/vscode.js.map +0 -1
  967. package/dist/terminal/manager.d.ts +0 -59
  968. package/dist/terminal/manager.d.ts.map +0 -1
  969. package/dist/terminal/manager.js +0 -237
  970. package/dist/terminal/manager.js.map +0 -1
  971. package/dist/terminal/pool.d.ts +0 -32
  972. package/dist/terminal/pool.d.ts.map +0 -1
  973. package/dist/terminal/pool.js +0 -205
  974. package/dist/terminal/pool.js.map +0 -1
  975. package/dist/terminal/session.d.ts +0 -41
  976. package/dist/terminal/session.d.ts.map +0 -1
  977. package/dist/terminal/session.js +0 -206
  978. package/dist/terminal/session.js.map +0 -1
  979. package/dist/types/index.d.ts +0 -28
  980. package/dist/types/index.d.ts.map +0 -1
  981. package/dist/types/index.js +0 -15
  982. package/dist/types/index.js.map +0 -1
  983. package/dist/ui/hive-dashboard.d.ts +0 -140
  984. package/dist/ui/hive-dashboard.d.ts.map +0 -1
  985. package/dist/ui/hive-dashboard.js +0 -281
  986. package/dist/ui/hive-dashboard.js.map +0 -1
  987. package/dist/utils/error-handler.d.ts +0 -13
  988. package/dist/utils/error-handler.d.ts.map +0 -1
  989. package/dist/utils/error-handler.js +0 -45
  990. package/dist/utils/error-handler.js.map +0 -1
  991. package/dist/utils/errors.d.ts +0 -121
  992. package/dist/utils/errors.d.ts.map +0 -1
  993. package/dist/utils/errors.js +0 -194
  994. package/dist/utils/errors.js.map +0 -1
  995. package/dist/utils/formatters.d.ts +0 -15
  996. package/dist/utils/formatters.d.ts.map +0 -1
  997. package/dist/utils/formatters.js +0 -75
  998. package/dist/utils/formatters.js.map +0 -1
  999. package/dist/utils/helpers.d.ts +0 -131
  1000. package/dist/utils/helpers.d.ts.map +0 -1
  1001. package/dist/utils/helpers.js +0 -447
  1002. package/dist/utils/helpers.js.map +0 -1
  1003. package/dist/utils/paths.d.ts +0 -4
  1004. package/dist/utils/paths.d.ts.map +0 -1
  1005. package/dist/utils/paths.js +0 -39
  1006. package/dist/utils/paths.js.map +0 -1
  1007. package/dist/utils/types.d.ts +0 -512
  1008. package/dist/utils/types.d.ts.map +0 -1
  1009. package/dist/utils/types.js +0 -37
  1010. package/dist/utils/types.js.map +0 -1
  1011. package/src/cli/simple-commands/hive-mind/memory.d.ts +0 -37
  1012. package/src/cli/simple-commands/init/templates/CLAUDE-FLOW-SPECIFIC.md +0 -238
  1013. package/src/cli/simple-commands/init/templates/all-commands.js +0 -1355
  1014. package/src/cli/simple-commands/init/templates/commands/hooks/hooks-documentation.md +0 -272
  1015. package/src/cli/simple-commands/init/templates/github-enhanced.js +0 -505
  1016. package/src/cli/simple-commands/init/templates/hooks-documentation.md +0 -272
  1017. package/src/cli/simple-commands/web-server.d.ts +0 -22
  1018. package/src/cli/utils.d.ts +0 -8
@@ -1,2607 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import { promises as fs } from 'node:fs';
3
- import { Logger } from '../core/logger.js';
4
- import { generateId } from '../utils/helpers.js';
5
- import { SWARM_CONSTANTS } from './types.js';
6
- import { AutoStrategy } from './strategies/auto.js';
7
- import { getClaudeFlowRoot, getClaudeFlowBin } from '../utils/paths.js';
8
- export class SwarmCoordinator extends EventEmitter {
9
- logger;
10
- config;
11
- swarmId;
12
- // Core state management
13
- agents = new Map();
14
- tasks = new Map();
15
- objectives = new Map();
16
- // Execution state
17
- _isRunning = false;
18
- status = 'planning';
19
- startTime;
20
- endTime;
21
- // Performance tracking
22
- metrics;
23
- events = [];
24
- lastHeartbeat = new Date();
25
- // Background processes
26
- heartbeatTimer;
27
- monitoringTimer;
28
- cleanupTimer;
29
- executionIntervals;
30
- // Strategy instances
31
- autoStrategy;
32
- constructor(config = {}) {
33
- super();
34
- // Configure logger based on config or default to quiet mode
35
- const logLevel = config.logging?.level || 'error';
36
- const logFormat = config.logging?.format || 'text';
37
- const logDestination = config.logging?.destination || 'console';
38
- this.logger = new Logger({ level: logLevel, format: logFormat, destination: logDestination }, { component: 'SwarmCoordinator' });
39
- this.swarmId = this.generateSwarmId();
40
- // Initialize configuration with defaults
41
- this.config = this.mergeWithDefaults(config);
42
- // Initialize metrics
43
- this.metrics = this.initializeMetrics();
44
- // Initialize strategy instances
45
- this.autoStrategy = new AutoStrategy(config);
46
- // Setup event handlers
47
- this.setupEventHandlers();
48
- this.logger.info('SwarmCoordinator initialized', {
49
- swarmId: this.swarmId.id,
50
- mode: this.config.mode,
51
- strategy: this.config.strategy
52
- });
53
- }
54
- // ===== LIFECYCLE MANAGEMENT =====
55
- async initialize() {
56
- if (this._isRunning) {
57
- throw new Error('Swarm coordinator already running');
58
- }
59
- this.logger.info('Initializing swarm coordinator...');
60
- this.status = 'initializing';
61
- try {
62
- // Validate configuration
63
- const validation = await this.validateConfiguration();
64
- if (!validation.valid) {
65
- throw new Error(`Configuration validation failed: ${validation.errors.map(e => e.message).join(', ')}`);
66
- }
67
- // Initialize subsystems
68
- await this.initializeSubsystems();
69
- // Start background processes
70
- this.startBackgroundProcesses();
71
- this._isRunning = true;
72
- this.startTime = new Date();
73
- this.status = 'executing';
74
- this.emitSwarmEvent({
75
- id: generateId('event'),
76
- timestamp: new Date(),
77
- type: 'swarm.started',
78
- source: this.swarmId.id,
79
- data: { swarmId: this.swarmId },
80
- broadcast: true,
81
- processed: false
82
- });
83
- this.logger.info('Swarm coordinator initialized successfully');
84
- }
85
- catch (error) {
86
- this.status = 'failed';
87
- this.logger.error('Failed to initialize swarm coordinator', { error });
88
- throw error;
89
- }
90
- }
91
- async shutdown() {
92
- if (!this._isRunning) {
93
- return;
94
- }
95
- this.logger.info('Shutting down swarm coordinator...');
96
- this.status = 'paused';
97
- try {
98
- // Stop background processes
99
- this.stopBackgroundProcesses();
100
- // Gracefully stop all agents
101
- await this.stopAllAgents();
102
- // Complete any running tasks
103
- await this.completeRunningTasks();
104
- // Save final state
105
- await this.saveState();
106
- this._isRunning = false;
107
- this.endTime = new Date();
108
- this.status = 'completed';
109
- this.emitSwarmEvent({
110
- id: generateId('event'),
111
- timestamp: new Date(),
112
- type: 'swarm.completed',
113
- source: this.swarmId.id,
114
- data: {
115
- swarmId: this.swarmId,
116
- metrics: this.metrics,
117
- duration: this.endTime.getTime() - (this.startTime?.getTime() || 0)
118
- },
119
- broadcast: true,
120
- processed: false
121
- });
122
- this.logger.info('Swarm coordinator shut down successfully');
123
- }
124
- catch (error) {
125
- this.logger.error('Error during swarm coordinator shutdown', { error });
126
- throw error;
127
- }
128
- }
129
- async pause() {
130
- if (!this._isRunning || this.status === 'paused') {
131
- return;
132
- }
133
- this.logger.info('Pausing swarm coordinator...');
134
- this.status = 'paused';
135
- // Pause all agents
136
- for (const agent of this.agents.values()) {
137
- if (agent.status === 'busy') {
138
- await this.pauseAgent(agent.id);
139
- }
140
- }
141
- this.emitSwarmEvent({
142
- id: generateId('event'),
143
- timestamp: new Date(),
144
- type: 'swarm.paused',
145
- source: this.swarmId.id,
146
- data: { swarmId: this.swarmId },
147
- broadcast: true,
148
- processed: false
149
- });
150
- }
151
- async resume() {
152
- if (!this._isRunning || this.status !== 'paused') {
153
- return;
154
- }
155
- this.logger.info('Resuming swarm coordinator...');
156
- this.status = 'executing';
157
- // Resume all paused agents
158
- for (const agent of this.agents.values()) {
159
- if (agent.status === 'paused') {
160
- await this.resumeAgent(agent.id);
161
- }
162
- }
163
- this.emitSwarmEvent({
164
- id: generateId('event'),
165
- timestamp: new Date(),
166
- type: 'swarm.resumed',
167
- source: this.swarmId.id,
168
- data: { swarmId: this.swarmId },
169
- broadcast: true,
170
- processed: false
171
- });
172
- }
173
- // ===== OBJECTIVE MANAGEMENT =====
174
- async createObjective(name, description, strategy = 'auto', requirements = {}) {
175
- const objectiveId = generateId('objective');
176
- const objective = {
177
- id: objectiveId,
178
- name,
179
- description,
180
- strategy,
181
- mode: this.config.mode,
182
- requirements: {
183
- minAgents: 1,
184
- maxAgents: this.config.maxAgents,
185
- agentTypes: this.determineRequiredAgentTypes(strategy),
186
- estimatedDuration: 60 * 60 * 1000, // 1 hour default
187
- maxDuration: 4 * 60 * 60 * 1000, // 4 hours default
188
- qualityThreshold: this.config.qualityThreshold,
189
- reviewCoverage: 0.8,
190
- testCoverage: 0.7,
191
- reliabilityTarget: 0.95,
192
- ...requirements
193
- },
194
- constraints: {
195
- minQuality: this.config.qualityThreshold,
196
- requiredApprovals: [],
197
- allowedFailures: Math.floor(this.config.maxAgents * 0.1),
198
- recoveryTime: 5 * 60 * 1000, // 5 minutes
199
- milestones: []
200
- },
201
- tasks: [],
202
- dependencies: [],
203
- status: 'planning',
204
- progress: this.initializeProgress(),
205
- createdAt: new Date(),
206
- metrics: this.initializeMetrics()
207
- };
208
- // Decompose objective into tasks using optimized AUTO strategy
209
- if (objective.strategy === 'auto') {
210
- const decompositionResult = await this.autoStrategy.decomposeObjective(objective);
211
- objective.tasks = decompositionResult.tasks;
212
- objective.dependencies = this.convertDependenciesToTaskDependencies(decompositionResult.dependencies);
213
- }
214
- else {
215
- objective.tasks = await this.decomposeObjective(objective);
216
- objective.dependencies = this.analyzeDependencies(objective.tasks);
217
- }
218
- this.objectives.set(objectiveId, objective);
219
- this.logger.info('Created objective', {
220
- objectiveId,
221
- name,
222
- strategy,
223
- taskCount: objective.tasks.length
224
- });
225
- return objectiveId;
226
- }
227
- async executeObjective(objectiveId) {
228
- const objective = this.objectives.get(objectiveId);
229
- if (!objective) {
230
- throw new Error(`Objective not found: ${objectiveId}`);
231
- }
232
- if (objective.status !== 'planning') {
233
- throw new Error(`Objective already ${objective.status}`);
234
- }
235
- this.logger.info('Executing objective', { objectiveId, name: objective.name });
236
- objective.status = 'executing';
237
- objective.startedAt = new Date();
238
- try {
239
- // Ensure we have required agents
240
- await this.ensureRequiredAgents(objective);
241
- // Schedule initial tasks
242
- await this.scheduleInitialTasks(objective);
243
- // Start task execution loop
244
- this.startTaskExecutionLoop(objective);
245
- }
246
- catch (error) {
247
- objective.status = 'failed';
248
- this.logger.error('Failed to execute objective', { objectiveId, error });
249
- throw error;
250
- }
251
- }
252
- // ===== AGENT MANAGEMENT =====
253
- async registerAgent(name, type, capabilities = {}) {
254
- const agentId = {
255
- id: generateId('agent'),
256
- swarmId: this.swarmId.id,
257
- type,
258
- instance: this.getNextInstanceNumber(type)
259
- };
260
- const agentState = {
261
- id: agentId,
262
- name,
263
- type,
264
- status: 'initializing',
265
- capabilities: {
266
- // Default capabilities
267
- codeGeneration: false,
268
- codeReview: false,
269
- testing: false,
270
- documentation: false,
271
- research: false,
272
- analysis: false,
273
- webSearch: false,
274
- apiIntegration: false,
275
- fileSystem: true,
276
- terminalAccess: true,
277
- languages: [],
278
- frameworks: [],
279
- domains: [],
280
- tools: [],
281
- maxConcurrentTasks: 3,
282
- maxMemoryUsage: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,
283
- maxExecutionTime: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,
284
- reliability: 0.8,
285
- speed: 1.0,
286
- quality: 0.8,
287
- ...capabilities
288
- },
289
- metrics: {
290
- tasksCompleted: 0,
291
- tasksFailed: 0,
292
- averageExecutionTime: 0,
293
- successRate: 0,
294
- cpuUsage: 0,
295
- memoryUsage: 0,
296
- diskUsage: 0,
297
- networkUsage: 0,
298
- codeQuality: 0,
299
- testCoverage: 0,
300
- bugRate: 0,
301
- userSatisfaction: 0,
302
- totalUptime: 0,
303
- lastActivity: new Date(),
304
- responseTime: 0
305
- },
306
- workload: 0,
307
- health: 1.0,
308
- config: {
309
- autonomyLevel: 0.7,
310
- learningEnabled: true,
311
- adaptationEnabled: true,
312
- maxTasksPerHour: 10,
313
- maxConcurrentTasks: capabilities.maxConcurrentTasks || 3,
314
- timeoutThreshold: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,
315
- reportingInterval: 30000,
316
- heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,
317
- permissions: this.getDefaultPermissions(type),
318
- trustedAgents: [],
319
- expertise: {},
320
- preferences: {}
321
- },
322
- environment: {
323
- runtime: 'deno',
324
- version: '1.0.0',
325
- workingDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}`,
326
- tempDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/temp`,
327
- logDirectory: `/tmp/swarm/${this.swarmId.id}/agents/${agentId.id}/logs`,
328
- apiEndpoints: {},
329
- credentials: {},
330
- availableTools: [],
331
- toolConfigs: {}
332
- },
333
- endpoints: [],
334
- lastHeartbeat: new Date(),
335
- taskHistory: [],
336
- errorHistory: [],
337
- childAgents: [],
338
- collaborators: []
339
- };
340
- this.agents.set(agentId.id, agentState);
341
- // Initialize agent capabilities based on type
342
- await this.initializeAgentCapabilities(agentState);
343
- // Start agent
344
- await this.startAgent(agentId.id);
345
- this.logger.info('Registered agent', {
346
- agentId: agentId.id,
347
- name,
348
- type,
349
- capabilities: Object.keys(capabilities)
350
- });
351
- this.emitSwarmEvent({
352
- id: generateId('event'),
353
- timestamp: new Date(),
354
- type: 'agent.created',
355
- source: agentId.id,
356
- data: { agent: agentState },
357
- broadcast: false,
358
- processed: false
359
- });
360
- return agentId.id;
361
- }
362
- async unregisterAgent(agentId) {
363
- const agent = this.agents.get(agentId);
364
- if (!agent) {
365
- return;
366
- }
367
- this.logger.info('Unregistering agent', { agentId, name: agent.name });
368
- // Stop agent gracefully
369
- await this.stopAgent(agentId);
370
- // Reassign any active tasks
371
- if (agent.currentTask) {
372
- await this.reassignTask(agent.currentTask.id);
373
- }
374
- // Remove from agents map
375
- this.agents.delete(agentId);
376
- this.emitSwarmEvent({
377
- id: generateId('event'),
378
- timestamp: new Date(),
379
- type: 'agent.stopped',
380
- source: agentId,
381
- data: { agentId },
382
- broadcast: false,
383
- processed: false
384
- });
385
- }
386
- async startAgent(agentId) {
387
- const agent = this.agents.get(agentId);
388
- if (!agent) {
389
- throw new Error(`Agent not found: ${agentId}`);
390
- }
391
- if (agent.status !== 'initializing' && agent.status !== 'offline') {
392
- return;
393
- }
394
- this.logger.info('Starting agent', { agentId, name: agent.name });
395
- try {
396
- // Initialize agent environment
397
- await this.initializeAgentEnvironment(agent);
398
- // Start agent heartbeat
399
- this.startAgentHeartbeat(agent);
400
- agent.status = 'idle';
401
- agent.lastHeartbeat = new Date();
402
- this.emitSwarmEvent({
403
- id: generateId('event'),
404
- timestamp: new Date(),
405
- type: 'agent.started',
406
- source: agentId,
407
- data: { agent },
408
- broadcast: false,
409
- processed: false
410
- });
411
- }
412
- catch (error) {
413
- agent.status = 'error';
414
- agent.errorHistory.push({
415
- timestamp: new Date(),
416
- type: 'startup_error',
417
- message: (error instanceof Error ? error.message : String(error)),
418
- stack: error.stack,
419
- context: { agentId },
420
- severity: 'high',
421
- resolved: false
422
- });
423
- this.logger.error('Failed to start agent', { agentId, error });
424
- throw error;
425
- }
426
- }
427
- async stopAgent(agentId) {
428
- const agent = this.agents.get(agentId);
429
- if (!agent) {
430
- return;
431
- }
432
- if (agent.status === 'offline' || agent.status === 'terminated') {
433
- return;
434
- }
435
- this.logger.info('Stopping agent', { agentId, name: agent.name });
436
- agent.status = 'terminating';
437
- try {
438
- // Cancel current task if any
439
- if (agent.currentTask) {
440
- await this.cancelTask(agent.currentTask.id, 'Agent stopping');
441
- }
442
- // Stop heartbeat
443
- this.stopAgentHeartbeat(agent);
444
- // Cleanup agent environment
445
- await this.cleanupAgentEnvironment(agent);
446
- agent.status = 'terminated';
447
- }
448
- catch (error) {
449
- agent.status = 'error';
450
- this.logger.error('Error stopping agent', { agentId, error });
451
- }
452
- }
453
- async pauseAgent(agentId) {
454
- const agent = this.agents.get(agentId);
455
- if (!agent || agent.status !== 'busy') {
456
- return;
457
- }
458
- agent.status = 'paused';
459
- this.logger.info('Paused agent', { agentId });
460
- }
461
- async resumeAgent(agentId) {
462
- const agent = this.agents.get(agentId);
463
- if (!agent || agent.status !== 'paused') {
464
- return;
465
- }
466
- agent.status = 'busy';
467
- this.logger.info('Resumed agent', { agentId });
468
- }
469
- // ===== TASK MANAGEMENT =====
470
- async createTask(type, name, description, instructions, options = {}) {
471
- const taskId = {
472
- id: generateId('task'),
473
- swarmId: this.swarmId.id,
474
- sequence: this.tasks.size + 1,
475
- priority: 1
476
- };
477
- const task = {
478
- id: taskId,
479
- type,
480
- name,
481
- description,
482
- instructions,
483
- requirements: {
484
- capabilities: this.getRequiredCapabilities(type),
485
- tools: this.getRequiredTools(type),
486
- permissions: this.getRequiredPermissions(type),
487
- ...options.requirements
488
- },
489
- constraints: {
490
- dependencies: [],
491
- dependents: [],
492
- conflicts: [],
493
- maxRetries: SWARM_CONSTANTS.MAX_RETRIES,
494
- timeoutAfter: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,
495
- ...options.constraints
496
- },
497
- priority: 'normal',
498
- input: options.input || {},
499
- context: options.context || {},
500
- examples: options.examples || [],
501
- status: 'created',
502
- createdAt: new Date(),
503
- updatedAt: new Date(),
504
- attempts: [],
505
- statusHistory: [{
506
- timestamp: new Date(),
507
- from: 'created',
508
- to: 'created',
509
- reason: 'Task created',
510
- triggeredBy: 'system'
511
- }],
512
- ...options
513
- };
514
- this.tasks.set(taskId.id, task);
515
- this.logger.info('Created task', {
516
- taskId: taskId.id,
517
- type,
518
- name,
519
- priority: task.priority
520
- });
521
- this.emitSwarmEvent({
522
- id: generateId('event'),
523
- timestamp: new Date(),
524
- type: 'task.created',
525
- source: this.swarmId.id,
526
- data: { task },
527
- broadcast: false,
528
- processed: false
529
- });
530
- return taskId.id;
531
- }
532
- async assignTask(taskId, agentId) {
533
- const task = this.tasks.get(taskId);
534
- if (!task) {
535
- throw new Error(`Task not found: ${taskId}`);
536
- }
537
- if (task.status !== 'created' && task.status !== 'queued') {
538
- throw new Error(`Task cannot be assigned, current status: ${task.status}`);
539
- }
540
- // Select agent if not specified
541
- if (!agentId) {
542
- agentId = await this.selectAgentForTask(task);
543
- if (!agentId) {
544
- throw new Error('No suitable agent available for task');
545
- }
546
- }
547
- const agent = this.agents.get(agentId);
548
- if (!agent) {
549
- throw new Error(`Agent not found: ${agentId}`);
550
- }
551
- if (agent.status !== 'idle') {
552
- throw new Error(`Agent not available: ${agent.status}`);
553
- }
554
- // Assign task
555
- task.assignedTo = agent.id;
556
- task.assignedAt = new Date();
557
- task.status = 'assigned';
558
- agent.currentTask = task.id;
559
- agent.status = 'busy';
560
- // Update status history
561
- task.statusHistory.push({
562
- timestamp: new Date(),
563
- from: task.statusHistory[task.statusHistory.length - 1].to,
564
- to: 'assigned',
565
- reason: `Assigned to agent ${agent.name}`,
566
- triggeredBy: 'system'
567
- });
568
- this.logger.info('Assigned task', {
569
- taskId,
570
- agentId,
571
- agentName: agent.name
572
- });
573
- this.emitSwarmEvent({
574
- id: generateId('event'),
575
- timestamp: new Date(),
576
- type: 'task.assigned',
577
- source: agentId,
578
- data: { task, agent },
579
- broadcast: false,
580
- processed: false
581
- });
582
- // Start task execution
583
- await this.startTaskExecution(task);
584
- }
585
- async startTaskExecution(task) {
586
- if (!task.assignedTo) {
587
- throw new Error('Task not assigned to any agent');
588
- }
589
- const agent = this.agents.get(task.assignedTo.id);
590
- if (!agent) {
591
- throw new Error(`Agent not found: ${task.assignedTo.id}`);
592
- }
593
- this.logger.info('Starting task execution', {
594
- taskId: task.id.id,
595
- agentId: agent.id.id
596
- });
597
- task.status = 'running';
598
- task.startedAt = new Date();
599
- // Create attempt record
600
- const attempt = {
601
- attemptNumber: task.attempts.length + 1,
602
- agent: agent.id,
603
- startedAt: new Date(),
604
- status: 'running',
605
- resourcesUsed: {}
606
- };
607
- task.attempts.push(attempt);
608
- // Update status history
609
- task.statusHistory.push({
610
- timestamp: new Date(),
611
- from: 'assigned',
612
- to: 'running',
613
- reason: 'Task execution started',
614
- triggeredBy: agent.id
615
- });
616
- this.emitSwarmEvent({
617
- id: generateId('event'),
618
- timestamp: new Date(),
619
- type: 'task.started',
620
- source: agent.id.id,
621
- data: { task, agent, attempt },
622
- broadcast: false,
623
- processed: false
624
- });
625
- try {
626
- // Execute task (this would spawn actual Claude process)
627
- const result = await this.executeTaskWithAgent(task, agent);
628
- await this.completeTask(task.id.id, result);
629
- }
630
- catch (error) {
631
- await this.failTask(task.id.id, error);
632
- }
633
- }
634
- async completeTask(taskId, result) {
635
- const task = this.tasks.get(taskId);
636
- if (!task) {
637
- throw new Error(`Task not found: ${taskId}`);
638
- }
639
- const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;
640
- if (!agent) {
641
- throw new Error('Task not assigned to any agent');
642
- }
643
- this.logger.info('Completing task', { taskId, agentId: agent.id.id });
644
- task.status = 'completed';
645
- task.completedAt = new Date();
646
- task.result = {
647
- output: result,
648
- artifacts: {},
649
- metadata: {},
650
- quality: this.assessTaskQuality(task, result),
651
- completeness: 1.0,
652
- accuracy: 1.0,
653
- executionTime: task.completedAt.getTime() - (task.startedAt?.getTime() || 0),
654
- resourcesUsed: {},
655
- validated: false
656
- };
657
- // Update attempt
658
- const currentAttempt = task.attempts[task.attempts.length - 1];
659
- if (currentAttempt) {
660
- currentAttempt.completedAt = new Date();
661
- currentAttempt.status = 'completed';
662
- currentAttempt.result = task.result;
663
- }
664
- // Update agent state
665
- agent.status = 'idle';
666
- agent.currentTask = undefined;
667
- agent.metrics.tasksCompleted++;
668
- agent.metrics.lastActivity = new Date();
669
- agent.taskHistory.push(task.id);
670
- // Update agent metrics
671
- this.updateAgentMetrics(agent, task);
672
- // Update status history
673
- task.statusHistory.push({
674
- timestamp: new Date(),
675
- from: 'running',
676
- to: 'completed',
677
- reason: 'Task completed successfully',
678
- triggeredBy: agent.id
679
- });
680
- this.emitSwarmEvent({
681
- id: generateId('event'),
682
- timestamp: new Date(),
683
- type: 'task.completed',
684
- source: agent.id.id,
685
- data: { task, agent, result: task.result },
686
- broadcast: false,
687
- processed: false
688
- });
689
- // Check for dependent tasks
690
- await this.processDependentTasks(task);
691
- }
692
- async failTask(taskId, error) {
693
- const task = this.tasks.get(taskId);
694
- if (!task) {
695
- throw new Error(`Task not found: ${taskId}`);
696
- }
697
- const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;
698
- if (!agent) {
699
- throw new Error('Task not assigned to any agent');
700
- }
701
- this.logger.warn('Task failed', { taskId, agentId: agent.id.id, error: (error instanceof Error ? error.message : String(error)) });
702
- task.error = {
703
- type: error.constructor.name,
704
- message: (error instanceof Error ? error.message : String(error)),
705
- code: error.code,
706
- stack: error.stack,
707
- context: { taskId, agentId: agent.id.id },
708
- recoverable: this.isRecoverableError(error),
709
- retryable: this.isRetryableError(error)
710
- };
711
- // Update attempt
712
- const currentAttempt = task.attempts[task.attempts.length - 1];
713
- if (currentAttempt) {
714
- currentAttempt.completedAt = new Date();
715
- currentAttempt.status = 'failed';
716
- currentAttempt.error = task.error;
717
- }
718
- // Update agent state
719
- agent.status = 'idle';
720
- agent.currentTask = undefined;
721
- agent.metrics.tasksFailed++;
722
- agent.metrics.lastActivity = new Date();
723
- // Add to error history
724
- agent.errorHistory.push({
725
- timestamp: new Date(),
726
- type: 'task_failure',
727
- message: (error instanceof Error ? error.message : String(error)),
728
- stack: error.stack,
729
- context: { taskId },
730
- severity: 'medium',
731
- resolved: false
732
- });
733
- // Determine if we should retry
734
- const shouldRetry = task.error.retryable &&
735
- task.attempts.length < (task.constraints.maxRetries || SWARM_CONSTANTS.MAX_RETRIES);
736
- if (shouldRetry) {
737
- task.status = 'retrying';
738
- task.assignedTo = undefined;
739
- // Update status history
740
- task.statusHistory.push({
741
- timestamp: new Date(),
742
- from: 'running',
743
- to: 'retrying',
744
- reason: `Task failed, will retry: ${(error instanceof Error ? error.message : String(error))}`,
745
- triggeredBy: agent.id
746
- });
747
- this.emitSwarmEvent({
748
- id: generateId('event'),
749
- timestamp: new Date(),
750
- type: 'task.retried',
751
- source: agent.id.id,
752
- data: { task, error: task.error, attempt: task.attempts.length },
753
- broadcast: false,
754
- processed: false
755
- });
756
- // Schedule retry with exponential backoff
757
- const retryDelay = Math.pow(2, task.attempts.length) * 1000;
758
- setTimeout(() => {
759
- this.assignTask(taskId).catch(retryError => {
760
- this.logger.error('Failed to retry task', { taskId, retryError });
761
- });
762
- }, retryDelay);
763
- }
764
- else {
765
- task.status = 'failed';
766
- task.completedAt = new Date();
767
- // Update status history
768
- task.statusHistory.push({
769
- timestamp: new Date(),
770
- from: 'running',
771
- to: 'failed',
772
- reason: `Task failed permanently: ${(error instanceof Error ? error.message : String(error))}`,
773
- triggeredBy: agent.id
774
- });
775
- this.emitSwarmEvent({
776
- id: generateId('event'),
777
- timestamp: new Date(),
778
- type: 'task.failed',
779
- source: agent.id.id,
780
- data: { task, error: task.error },
781
- broadcast: false,
782
- processed: false
783
- });
784
- // Handle failure cascade
785
- await this.handleTaskFailureCascade(task);
786
- }
787
- }
788
- async cancelTask(taskId, reason) {
789
- const task = this.tasks.get(taskId);
790
- if (!task) {
791
- throw new Error(`Task not found: ${taskId}`);
792
- }
793
- const agent = task.assignedTo ? this.agents.get(task.assignedTo.id) : null;
794
- this.logger.info('Cancelling task', { taskId, reason });
795
- task.status = 'cancelled';
796
- task.completedAt = new Date();
797
- if (agent) {
798
- agent.status = 'idle';
799
- agent.currentTask = undefined;
800
- }
801
- // Update status history
802
- task.statusHistory.push({
803
- timestamp: new Date(),
804
- from: task.statusHistory[task.statusHistory.length - 1].to,
805
- to: 'cancelled',
806
- reason: `Task cancelled: ${reason}`,
807
- triggeredBy: 'system'
808
- });
809
- this.emitSwarmEvent({
810
- id: generateId('event'),
811
- timestamp: new Date(),
812
- type: 'task.cancelled',
813
- source: this.swarmId.id,
814
- data: { task, reason },
815
- broadcast: false,
816
- processed: false
817
- });
818
- }
819
- // ===== ADVANCED FEATURES =====
820
- async selectAgentForTask(task) {
821
- const availableAgents = Array.from(this.agents.values())
822
- .filter(agent => agent.status === 'idle' &&
823
- this.agentCanHandleTask(agent, task));
824
- if (availableAgents.length === 0) {
825
- return null;
826
- }
827
- // Score agents based on multiple criteria
828
- const scoredAgents = availableAgents.map(agent => ({
829
- agent,
830
- score: this.calculateAgentScore(agent, task)
831
- }));
832
- // Sort by score (highest first)
833
- scoredAgents.sort((a, b) => b.score - a.score);
834
- return scoredAgents[0].agent.id.id;
835
- }
836
- calculateAgentScore(agent, task) {
837
- let score = 0;
838
- // Capability match (40% weight)
839
- const capabilityMatch = this.calculateCapabilityMatch(agent, task);
840
- score += capabilityMatch * 0.4;
841
- // Performance history (30% weight)
842
- const performanceScore = agent.metrics.successRate * agent.capabilities.reliability;
843
- score += performanceScore * 0.3;
844
- // Current workload (20% weight)
845
- const workloadScore = 1 - agent.workload;
846
- score += workloadScore * 0.2;
847
- // Quality rating (10% weight)
848
- score += agent.capabilities.quality * 0.1;
849
- return score;
850
- }
851
- calculateCapabilityMatch(agent, task) {
852
- const requiredCapabilities = task.requirements.capabilities;
853
- let matches = 0;
854
- let total = requiredCapabilities.length;
855
- for (const capability of requiredCapabilities) {
856
- if (this.agentHasCapability(agent, capability)) {
857
- matches++;
858
- }
859
- }
860
- return total > 0 ? matches / total : 1.0;
861
- }
862
- agentHasCapability(agent, capability) {
863
- const caps = agent.capabilities;
864
- switch (capability) {
865
- case 'code-generation': return caps.codeGeneration;
866
- case 'code-review': return caps.codeReview;
867
- case 'testing': return caps.testing;
868
- case 'documentation': return caps.documentation;
869
- case 'research': return caps.research;
870
- case 'analysis': return caps.analysis;
871
- case 'web-search': return caps.webSearch;
872
- case 'api-integration': return caps.apiIntegration;
873
- case 'file-system': return caps.fileSystem;
874
- case 'terminal-access': return caps.terminalAccess;
875
- case 'validation': return caps.testing; // Validation is part of testing capability
876
- default:
877
- return caps.domains.includes(capability) ||
878
- caps.languages.includes(capability) ||
879
- caps.frameworks.includes(capability) ||
880
- caps.tools.includes(capability);
881
- }
882
- }
883
- agentCanHandleTask(agent, task) {
884
- // Check if agent type is suitable
885
- if (task.requirements.agentType && agent.type !== task.requirements.agentType) {
886
- return false;
887
- }
888
- // Check if agent has required capabilities
889
- for (const capability of task.requirements.capabilities) {
890
- if (!this.agentHasCapability(agent, capability)) {
891
- return false;
892
- }
893
- }
894
- // Check reliability requirement
895
- if (task.requirements.minReliability &&
896
- agent.capabilities.reliability < task.requirements.minReliability) {
897
- return false;
898
- }
899
- // Check if agent has capacity
900
- if (agent.workload >= 1.0) {
901
- return false;
902
- }
903
- return true;
904
- }
905
- // ===== HELPER METHODS =====
906
- generateSwarmId() {
907
- return {
908
- id: generateId('swarm'),
909
- timestamp: Date.now(),
910
- namespace: 'default'
911
- };
912
- }
913
- mergeWithDefaults(config) {
914
- return {
915
- name: 'Unnamed Swarm',
916
- description: 'Auto-generated swarm',
917
- version: '1.0.0',
918
- mode: 'centralized',
919
- strategy: 'auto',
920
- coordinationStrategy: {
921
- name: 'default',
922
- description: 'Default coordination strategy',
923
- agentSelection: 'capability-based',
924
- taskScheduling: 'priority',
925
- loadBalancing: 'work-stealing',
926
- faultTolerance: 'retry',
927
- communication: 'event-driven'
928
- },
929
- maxAgents: 10,
930
- maxTasks: 100,
931
- maxDuration: 4 * 60 * 60 * 1000, // 4 hours
932
- resourceLimits: {
933
- memory: SWARM_CONSTANTS.DEFAULT_MEMORY_LIMIT,
934
- cpu: SWARM_CONSTANTS.DEFAULT_CPU_LIMIT,
935
- disk: SWARM_CONSTANTS.DEFAULT_DISK_LIMIT
936
- },
937
- qualityThreshold: SWARM_CONSTANTS.DEFAULT_QUALITY_THRESHOLD,
938
- reviewRequired: true,
939
- testingRequired: true,
940
- monitoring: {
941
- metricsEnabled: true,
942
- loggingEnabled: true,
943
- tracingEnabled: false,
944
- metricsInterval: 10000,
945
- heartbeatInterval: SWARM_CONSTANTS.DEFAULT_HEARTBEAT_INTERVAL,
946
- healthCheckInterval: 30000,
947
- retentionPeriod: 24 * 60 * 60 * 1000, // 24 hours
948
- maxLogSize: 100 * 1024 * 1024, // 100MB
949
- maxMetricPoints: 10000,
950
- alertingEnabled: true,
951
- alertThresholds: {
952
- errorRate: 0.1,
953
- responseTime: 5000,
954
- memoryUsage: 0.8,
955
- cpuUsage: 0.8
956
- },
957
- exportEnabled: false,
958
- exportFormat: 'json',
959
- exportDestination: '/tmp/swarm-metrics'
960
- },
961
- memory: {
962
- namespace: 'default',
963
- partitions: [],
964
- permissions: {
965
- read: 'swarm',
966
- write: 'team',
967
- delete: 'private',
968
- share: 'team'
969
- },
970
- persistent: true,
971
- backupEnabled: true,
972
- distributed: false,
973
- consistency: 'eventual',
974
- cacheEnabled: true,
975
- compressionEnabled: false
976
- },
977
- security: {
978
- authenticationRequired: false,
979
- authorizationRequired: false,
980
- encryptionEnabled: false,
981
- defaultPermissions: ['read', 'write'],
982
- adminRoles: ['admin', 'coordinator'],
983
- auditEnabled: true,
984
- auditLevel: 'info',
985
- inputValidation: true,
986
- outputSanitization: true
987
- },
988
- performance: {
989
- maxConcurrency: 10,
990
- defaultTimeout: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT,
991
- cacheEnabled: true,
992
- cacheSize: 100,
993
- cacheTtl: 3600000, // 1 hour
994
- optimizationEnabled: true,
995
- adaptiveScheduling: true,
996
- predictiveLoading: false,
997
- resourcePooling: true,
998
- connectionPooling: true,
999
- memoryPooling: false
1000
- },
1001
- ...config
1002
- };
1003
- }
1004
- initializeMetrics() {
1005
- return {
1006
- throughput: 0,
1007
- latency: 0,
1008
- efficiency: 0,
1009
- reliability: 0,
1010
- averageQuality: 0,
1011
- defectRate: 0,
1012
- reworkRate: 0,
1013
- resourceUtilization: {},
1014
- costEfficiency: 0,
1015
- agentUtilization: 0,
1016
- agentSatisfaction: 0,
1017
- collaborationEffectiveness: 0,
1018
- scheduleVariance: 0,
1019
- deadlineAdherence: 0
1020
- };
1021
- }
1022
- initializeProgress() {
1023
- return {
1024
- totalTasks: 0,
1025
- completedTasks: 0,
1026
- failedTasks: 0,
1027
- runningTasks: 0,
1028
- estimatedCompletion: new Date(),
1029
- timeRemaining: 0,
1030
- percentComplete: 0,
1031
- averageQuality: 0,
1032
- passedReviews: 0,
1033
- passedTests: 0,
1034
- resourceUtilization: {},
1035
- costSpent: 0,
1036
- activeAgents: 0,
1037
- idleAgents: 0,
1038
- busyAgents: 0
1039
- };
1040
- }
1041
- // ===== EVENT HANDLING =====
1042
- setupEventHandlers() {
1043
- // Handle agent heartbeats
1044
- this.on('agent.heartbeat', (data) => {
1045
- const agent = this.agents.get(data.agentId);
1046
- if (agent) {
1047
- agent.lastHeartbeat = new Date();
1048
- agent.health = data.health || 1.0;
1049
- agent.metrics = { ...agent.metrics, ...data.metrics };
1050
- }
1051
- });
1052
- // Handle task completion events
1053
- this.on('task.completed', (data) => {
1054
- this.updateSwarmMetrics();
1055
- this.checkObjectiveCompletion();
1056
- });
1057
- // Handle task failure events
1058
- this.on('task.failed', (data) => {
1059
- this.updateSwarmMetrics();
1060
- this.checkObjectiveFailure(data.task);
1061
- });
1062
- // Handle agent errors
1063
- this.on('agent.error', (data) => {
1064
- this.handleAgentError(data.agentId, data.error);
1065
- });
1066
- }
1067
- // ===== SWARM EVENT EMITTER IMPLEMENTATION =====
1068
- emitSwarmEvent(event) {
1069
- this.events.push(event);
1070
- // Limit event history
1071
- if (this.events.length > 1000) {
1072
- this.events = this.events.slice(-500);
1073
- }
1074
- return this.emit(event.type, event);
1075
- }
1076
- emitSwarmEvents(events) {
1077
- let success = true;
1078
- for (const event of events) {
1079
- if (!this.emitSwarmEvent(event)) {
1080
- success = false;
1081
- }
1082
- }
1083
- return success;
1084
- }
1085
- onSwarmEvent(type, handler) {
1086
- return this.on(type, handler);
1087
- }
1088
- offSwarmEvent(type, handler) {
1089
- return this.off(type, handler);
1090
- }
1091
- filterEvents(predicate) {
1092
- return this.events.filter(predicate);
1093
- }
1094
- correlateEvents(correlationId) {
1095
- return this.events.filter(event => event.correlationId === correlationId);
1096
- }
1097
- // ===== PUBLIC API METHODS =====
1098
- getSwarmId() {
1099
- return this.swarmId;
1100
- }
1101
- getStatus() {
1102
- return this.status;
1103
- }
1104
- getAgents() {
1105
- return Array.from(this.agents.values());
1106
- }
1107
- getAgent(agentId) {
1108
- return this.agents.get(agentId);
1109
- }
1110
- getTasks() {
1111
- return Array.from(this.tasks.values());
1112
- }
1113
- getTask(taskId) {
1114
- return this.tasks.get(taskId);
1115
- }
1116
- getObjectives() {
1117
- return Array.from(this.objectives.values());
1118
- }
1119
- getObjective(objectiveId) {
1120
- return this.objectives.get(objectiveId);
1121
- }
1122
- getMetrics() {
1123
- return { ...this.metrics };
1124
- }
1125
- getEvents() {
1126
- return [...this.events];
1127
- }
1128
- isRunning() {
1129
- return this._isRunning;
1130
- }
1131
- getUptime() {
1132
- if (!this.startTime)
1133
- return 0;
1134
- const endTime = this.endTime || new Date();
1135
- return endTime.getTime() - this.startTime.getTime();
1136
- }
1137
- getSwarmStatus() {
1138
- const tasks = Array.from(this.tasks.values());
1139
- const completedTasks = tasks.filter(t => t.status === 'completed').length;
1140
- const failedTasks = tasks.filter(t => t.status === 'failed').length;
1141
- return {
1142
- status: this.status,
1143
- objectives: this.objectives.size,
1144
- tasks: {
1145
- completed: completedTasks,
1146
- failed: failedTasks,
1147
- total: tasks.length
1148
- },
1149
- agents: {
1150
- total: this.agents.size
1151
- }
1152
- };
1153
- }
1154
- // ===== STUB METHODS (TO BE IMPLEMENTED) =====
1155
- async validateConfiguration() {
1156
- // Implementation needed
1157
- return { valid: true, errors: [], warnings: [], validatedAt: new Date(), validator: 'SwarmCoordinator', context: {} };
1158
- }
1159
- async initializeSubsystems() {
1160
- // Implementation needed
1161
- }
1162
- startBackgroundProcesses() {
1163
- // Start heartbeat monitoring
1164
- this.heartbeatTimer = setInterval(() => {
1165
- this.processHeartbeats();
1166
- }, this.config.monitoring.heartbeatInterval);
1167
- // Start performance monitoring
1168
- this.monitoringTimer = setInterval(() => {
1169
- this.updateSwarmMetrics();
1170
- }, this.config.monitoring.metricsInterval);
1171
- // Start cleanup process
1172
- this.cleanupTimer = setInterval(() => {
1173
- this.performCleanup();
1174
- }, 60000); // Every minute
1175
- }
1176
- stopBackgroundProcesses() {
1177
- if (this.heartbeatTimer) {
1178
- clearInterval(this.heartbeatTimer);
1179
- this.heartbeatTimer = undefined;
1180
- }
1181
- if (this.monitoringTimer) {
1182
- clearInterval(this.monitoringTimer);
1183
- this.monitoringTimer = undefined;
1184
- }
1185
- if (this.cleanupTimer) {
1186
- clearInterval(this.cleanupTimer);
1187
- this.cleanupTimer = undefined;
1188
- }
1189
- // Stop all execution intervals
1190
- if (this.executionIntervals) {
1191
- for (const [objectiveId, interval] of this.executionIntervals) {
1192
- clearInterval(interval);
1193
- }
1194
- this.executionIntervals.clear();
1195
- }
1196
- }
1197
- async stopAllAgents() {
1198
- const stopPromises = Array.from(this.agents.keys()).map(agentId => this.stopAgent(agentId));
1199
- await Promise.allSettled(stopPromises);
1200
- }
1201
- async completeRunningTasks() {
1202
- const runningTasks = Array.from(this.tasks.values())
1203
- .filter(task => task.status === 'running');
1204
- // Wait for tasks to complete or timeout
1205
- const timeout = 30000; // 30 seconds
1206
- const deadline = Date.now() + timeout;
1207
- while (runningTasks.some(task => task.status === 'running') && Date.now() < deadline) {
1208
- await new Promise(resolve => setTimeout(resolve, 1000));
1209
- }
1210
- // Cancel any remaining running tasks
1211
- for (const task of runningTasks) {
1212
- if (task.status === 'running') {
1213
- await this.cancelTask(task.id.id, 'Swarm shutdown');
1214
- }
1215
- }
1216
- }
1217
- async saveState() {
1218
- // Implementation needed - save swarm state to persistence layer
1219
- }
1220
- determineRequiredAgentTypes(strategy) {
1221
- switch (strategy) {
1222
- case 'research': return ['researcher', 'analyst'];
1223
- case 'development': return ['coder', 'tester', 'reviewer'];
1224
- case 'analysis': return ['analyst', 'researcher'];
1225
- case 'testing': return ['tester', 'coder'];
1226
- case 'optimization': return ['analyst', 'coder'];
1227
- case 'maintenance': return ['coder', 'monitor'];
1228
- default: return ['coordinator', 'coder', 'analyst'];
1229
- }
1230
- }
1231
- getAgentTypeInstructions(agentType) {
1232
- switch (agentType) {
1233
- case 'coder':
1234
- return '- Focus on implementation, code quality, and best practices\n- Create clean, maintainable code\n- Consider architecture and design patterns';
1235
- case 'tester':
1236
- return '- Focus on testing, edge cases, and quality assurance\n- Create comprehensive test suites\n- Identify potential bugs and issues';
1237
- case 'analyst':
1238
- return '- Focus on analysis, research, and understanding\n- Break down complex problems\n- Provide insights and recommendations';
1239
- case 'researcher':
1240
- return '- Focus on gathering information and best practices\n- Research existing solutions and patterns\n- Document findings and recommendations';
1241
- case 'reviewer':
1242
- return '- Focus on code review and quality checks\n- Identify improvements and optimizations\n- Ensure standards compliance';
1243
- case 'coordinator':
1244
- return '- Focus on coordination and integration\n- Ensure all parts work together\n- Manage dependencies and interfaces';
1245
- case 'monitor':
1246
- return '- Focus on monitoring and observability\n- Set up logging and metrics\n- Ensure system health tracking';
1247
- default:
1248
- return '- Execute the task to the best of your ability\n- Follow best practices for your domain';
1249
- }
1250
- }
1251
- getAgentCapabilities(agentType) {
1252
- switch (agentType) {
1253
- case 'coder':
1254
- return ['code-generation', 'file-system', 'debugging'];
1255
- case 'tester':
1256
- return ['testing', 'code-generation', 'analysis'];
1257
- case 'analyst':
1258
- return ['analysis', 'documentation', 'research'];
1259
- case 'researcher':
1260
- return ['research', 'documentation', 'analysis'];
1261
- case 'reviewer':
1262
- return ['code-review', 'analysis', 'documentation'];
1263
- case 'coordinator':
1264
- return ['coordination', 'analysis', 'documentation'];
1265
- case 'monitor':
1266
- return ['monitoring', 'analysis', 'documentation'];
1267
- default:
1268
- return ['analysis', 'documentation'];
1269
- }
1270
- }
1271
- async decomposeObjective(objective) {
1272
- // Decompose objective into tasks with clear instructions for Claude
1273
- this.logger.info('Decomposing objective', {
1274
- objectiveId: objective.id,
1275
- description: objective.description
1276
- });
1277
- const tasks = [];
1278
- // Extract target directory from objective
1279
- const targetDirMatch = objective.description.match(/(?:in|to|at)\s+([^\s]+\/[^\s]+)|([^\s]+\/[^\s]+)$/);
1280
- const targetDir = targetDirMatch ? targetDirMatch[1] || targetDirMatch[2] : null;
1281
- const targetPath = targetDir ? (targetDir.startsWith('/') ? targetDir : `${getClaudeFlowRoot()}/${targetDir}`) : null;
1282
- // Check if objective requests "each agent" or "each agent type" for parallel execution
1283
- const eachAgentPattern = /\beach\s+agent(?:\s+type)?\b/i;
1284
- const requestsParallelAgents = eachAgentPattern.test(objective.description);
1285
- // Create tasks with specific prompts for Claude
1286
- if (requestsParallelAgents && this.config.mode === 'parallel') {
1287
- // Create parallel tasks for each agent type
1288
- const agentTypes = this.determineRequiredAgentTypes(objective.strategy);
1289
- this.logger.info('Creating parallel tasks for each agent type', {
1290
- agentTypes,
1291
- mode: this.config.mode
1292
- });
1293
- for (const agentType of agentTypes) {
1294
- const taskId = this.createTaskForObjective(`${agentType}-task`, agentType, {
1295
- title: `${agentType.charAt(0).toUpperCase() + agentType.slice(1)} Agent Task`,
1296
- description: `${agentType} agent executing: ${objective.description}`,
1297
- instructions: `You are a ${agentType} agent. Please execute the following task from your perspective:
1298
-
1299
- ${objective.description}
1300
-
1301
- ${targetPath ? `Target Directory: ${targetPath}` : ''}
1302
-
1303
- As a ${agentType} agent, focus on aspects relevant to your role:
1304
- ${this.getAgentTypeInstructions(agentType)}
1305
-
1306
- Work independently but be aware that other agents are working on this same objective from their perspectives.`,
1307
- priority: 'high',
1308
- estimatedDuration: 10 * 60 * 1000,
1309
- requiredCapabilities: this.getAgentCapabilities(agentType)
1310
- });
1311
- tasks.push(taskId);
1312
- }
1313
- }
1314
- else if (objective.strategy === 'development') {
1315
- // Task 1: Analyze and Plan
1316
- const task1 = this.createTaskForObjective('analyze-requirements', 'analysis', {
1317
- title: 'Analyze Requirements and Plan Implementation',
1318
- description: `Analyze the requirements and create a plan for: ${objective.description}`,
1319
- instructions: `Please analyze the following request and create a detailed implementation plan:
1320
-
1321
- Request: ${objective.description}
1322
-
1323
- Target Directory: ${targetPath || 'Not specified - determine appropriate location'}
1324
-
1325
- Your analysis should include:
1326
- 1. Understanding of what needs to be built
1327
- 2. Technology choices and rationale
1328
- 3. Project structure and file organization
1329
- 4. Key components and their responsibilities
1330
- 5. Any external dependencies needed
1331
-
1332
- Please provide a clear, structured plan that the next tasks can follow.`,
1333
- priority: 'high',
1334
- estimatedDuration: 5 * 60 * 1000,
1335
- requiredCapabilities: ['analysis', 'documentation']
1336
- });
1337
- tasks.push(task1);
1338
- // Task 2: Implementation
1339
- const task2 = this.createTaskForObjective('create-implementation', 'coding', {
1340
- title: 'Implement the Solution',
1341
- description: `Create the implementation for: ${objective.description}`,
1342
- instructions: `Please implement the following request:
1343
-
1344
- Request: ${objective.description}
1345
-
1346
- Target Directory: ${targetPath || 'Create in an appropriate location'}
1347
-
1348
- Based on the analysis from the previous task, please:
1349
- 1. Create all necessary files and directories
1350
- 2. Implement the core functionality as requested
1351
- 3. Ensure the code is well-structured and follows best practices
1352
- 4. Include appropriate error handling
1353
- 5. Add any necessary configuration files (package.json, requirements.txt, etc.)
1354
-
1355
- Focus on creating a working implementation that matches the user's request exactly.`,
1356
- priority: 'high',
1357
- estimatedDuration: 10 * 60 * 1000,
1358
- requiredCapabilities: ['code-generation', 'file-system'],
1359
- dependencies: [task1.id.id]
1360
- });
1361
- tasks.push(task2);
1362
- // Task 3: Testing
1363
- const task3 = this.createTaskForObjective('write-tests', 'testing', {
1364
- title: 'Create Tests',
1365
- description: `Write tests for the implementation`,
1366
- instructions: `Please create comprehensive tests for the implementation created in the previous task.
1367
-
1368
- Target Directory: ${targetPath || 'Use the same directory as the implementation'}
1369
-
1370
- Create appropriate test files that:
1371
- 1. Test the main functionality
1372
- 2. Cover edge cases
1373
- 3. Ensure the implementation works as expected
1374
- 4. Use appropriate testing frameworks for the technology stack
1375
- 5. Include both unit tests and integration tests where applicable`,
1376
- priority: 'medium',
1377
- estimatedDuration: 5 * 60 * 1000,
1378
- requiredCapabilities: ['testing', 'code-generation'],
1379
- dependencies: [task2.id.id]
1380
- });
1381
- tasks.push(task3);
1382
- // Task 4: Documentation
1383
- const task4 = this.createTaskForObjective('create-documentation', 'documentation', {
1384
- title: 'Create Documentation',
1385
- description: `Document the implementation`,
1386
- instructions: `Please create comprehensive documentation for the implemented solution.
1387
-
1388
- Target Directory: ${targetPath || 'Use the same directory as the implementation'}
1389
-
1390
- Create documentation that includes:
1391
- 1. README.md with project overview, setup instructions, and usage examples
1392
- 2. API documentation (if applicable)
1393
- 3. Configuration options
1394
- 4. Architecture overview
1395
- 5. Deployment instructions (if applicable)
1396
- 6. Any other relevant documentation
1397
-
1398
- Make sure the documentation is clear, complete, and helps users understand and use the implementation.`,
1399
- priority: 'medium',
1400
- estimatedDuration: 5 * 60 * 1000,
1401
- requiredCapabilities: ['documentation'],
1402
- dependencies: [task2.id.id]
1403
- });
1404
- tasks.push(task4);
1405
- }
1406
- else {
1407
- // For other strategies, create a comprehensive single task
1408
- tasks.push(this.createTaskForObjective('execute-objective', 'generic', {
1409
- title: 'Execute Objective',
1410
- description: objective.description,
1411
- instructions: `Please complete the following request:
1412
-
1413
- ${objective.description}
1414
-
1415
- ${targetPath ? `Target Directory: ${targetPath}` : ''}
1416
-
1417
- Please analyze what is being requested and implement it appropriately. This may involve:
1418
- - Creating files and directories
1419
- - Writing code
1420
- - Setting up configurations
1421
- - Creating documentation
1422
- - Any other tasks necessary to fulfill the request
1423
-
1424
- Ensure your implementation is complete, well-structured, and follows best practices.`,
1425
- priority: 'high',
1426
- estimatedDuration: 15 * 60 * 1000,
1427
- requiredCapabilities: ['code-generation', 'file-system', 'documentation']
1428
- }));
1429
- }
1430
- this.logger.info('Objective decomposed', {
1431
- objectiveId: objective.id,
1432
- taskCount: tasks.length
1433
- });
1434
- return tasks;
1435
- }
1436
- createTaskForObjective(id, type, params) {
1437
- const taskId = {
1438
- id: generateId('task'),
1439
- swarmId: this.swarmId.id,
1440
- sequence: this.tasks.size + 1,
1441
- priority: 1
1442
- };
1443
- return {
1444
- id: taskId,
1445
- type,
1446
- name: params.title,
1447
- description: params.description,
1448
- instructions: params.description,
1449
- requirements: {
1450
- capabilities: params.requiredCapabilities || [],
1451
- tools: this.getRequiredTools(type),
1452
- permissions: this.getRequiredPermissions(type)
1453
- },
1454
- constraints: {
1455
- dependencies: params.dependencies || [],
1456
- dependents: [],
1457
- conflicts: [],
1458
- maxRetries: SWARM_CONSTANTS.MAX_RETRIES,
1459
- timeoutAfter: params.estimatedDuration || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT
1460
- },
1461
- priority: params.priority || 'medium',
1462
- input: {
1463
- description: params.description,
1464
- objective: params.description
1465
- },
1466
- context: {
1467
- objectiveId: id,
1468
- targetDir: params.targetDir
1469
- },
1470
- examples: [],
1471
- status: 'created',
1472
- createdAt: new Date(),
1473
- updatedAt: new Date(),
1474
- attempts: [],
1475
- statusHistory: [{
1476
- timestamp: new Date(),
1477
- from: 'created',
1478
- to: 'created',
1479
- reason: 'Task created',
1480
- triggeredBy: 'system'
1481
- }]
1482
- };
1483
- }
1484
- analyzeDependencies(tasks) {
1485
- // Implementation needed - analyze task dependencies
1486
- return [];
1487
- }
1488
- convertDependenciesToTaskDependencies(dependencies) {
1489
- // Convert decomposition dependencies to task dependencies format
1490
- const result = [];
1491
- dependencies.forEach((deps, taskId) => {
1492
- deps.forEach(dependsOn => {
1493
- result.push({
1494
- taskId,
1495
- dependsOn,
1496
- type: 'sequential'
1497
- });
1498
- });
1499
- });
1500
- return result;
1501
- }
1502
- async ensureRequiredAgents(objective) {
1503
- // Implementation needed - ensure required agents are available
1504
- }
1505
- async scheduleInitialTasks(objective) {
1506
- this.logger.info('Scheduling initial tasks for objective', {
1507
- objectiveId: objective.id,
1508
- taskCount: objective.tasks.length
1509
- });
1510
- // Extract target directory from objective description
1511
- const targetDirPatterns = [
1512
- /in\s+([^\s]+\/?)$/i,
1513
- /(?:in|to|at)\s+([^\s]+\/[^\s]+)/i,
1514
- /([^\s]+\/[^\s]+)$/,
1515
- /examples\/[^\s]+/i
1516
- ];
1517
- let objectiveTargetDir = null;
1518
- for (const pattern of targetDirPatterns) {
1519
- const match = objective.description.match(pattern);
1520
- if (match) {
1521
- objectiveTargetDir = match[1] || match[0];
1522
- break;
1523
- }
1524
- }
1525
- // Add all tasks to the tasks map
1526
- for (const task of objective.tasks) {
1527
- task.context.objectiveId = objective.id;
1528
- // Propagate target directory to all tasks
1529
- if (objectiveTargetDir && !task.context.targetDir) {
1530
- task.context.targetDir = objectiveTargetDir;
1531
- }
1532
- this.tasks.set(task.id.id, task);
1533
- }
1534
- // Find tasks with no dependencies and queue them
1535
- const initialTasks = objective.tasks.filter(task => !task.constraints.dependencies || task.constraints.dependencies.length === 0);
1536
- this.logger.info('Found initial tasks without dependencies', {
1537
- count: initialTasks.length,
1538
- tasks: initialTasks.map(t => ({ id: t.id.id, name: t.name }))
1539
- });
1540
- // Queue initial tasks for execution
1541
- for (const task of initialTasks) {
1542
- task.status = 'queued';
1543
- task.updatedAt = new Date();
1544
- // Update status history
1545
- task.statusHistory.push({
1546
- timestamp: new Date(),
1547
- from: 'created',
1548
- to: 'queued',
1549
- reason: 'Task queued for execution',
1550
- triggeredBy: 'system'
1551
- });
1552
- // Emit task queued event
1553
- this.emitSwarmEvent({
1554
- id: generateId('event'),
1555
- timestamp: new Date(),
1556
- type: 'task.queued',
1557
- source: this.swarmId.id,
1558
- data: { task },
1559
- broadcast: false,
1560
- processed: false
1561
- });
1562
- }
1563
- // Update objective progress
1564
- objective.progress.totalTasks = objective.tasks.length;
1565
- objective.progress.runningTasks = 0;
1566
- objective.progress.completedTasks = 0;
1567
- objective.progress.failedTasks = 0;
1568
- }
1569
- startTaskExecutionLoop(objective) {
1570
- this.logger.info('Starting task execution loop for objective', {
1571
- objectiveId: objective.id
1572
- });
1573
- // Create an interval to process queued tasks
1574
- const executionInterval = setInterval(async () => {
1575
- try {
1576
- // Check if objective is still executing
1577
- if (objective.status !== 'executing') {
1578
- clearInterval(executionInterval);
1579
- return;
1580
- }
1581
- // Find queued tasks
1582
- const queuedTasks = Array.from(this.tasks.values())
1583
- .filter(task => task.context?.objectiveId === objective.id &&
1584
- task.status === 'queued');
1585
- // Find idle agents
1586
- const idleAgents = Array.from(this.agents.values())
1587
- .filter(agent => agent.status === 'idle');
1588
- if (queuedTasks.length > 0 && idleAgents.length > 0) {
1589
- this.logger.debug('Processing queued tasks', {
1590
- queuedTasks: queuedTasks.length,
1591
- idleAgents: idleAgents.length
1592
- });
1593
- }
1594
- // Assign tasks to idle agents
1595
- for (const task of queuedTasks) {
1596
- if (idleAgents.length === 0)
1597
- break;
1598
- // Find suitable agent
1599
- const suitableAgents = idleAgents.filter(agent => this.agentCanHandleTask(agent, task));
1600
- if (suitableAgents.length > 0) {
1601
- // Assign to first suitable agent
1602
- await this.assignTask(task.id.id, suitableAgents[0].id.id);
1603
- // Remove agent from idle list
1604
- const agentIndex = idleAgents.findIndex(a => a.id.id === suitableAgents[0].id.id);
1605
- if (agentIndex >= 0) {
1606
- idleAgents.splice(agentIndex, 1);
1607
- }
1608
- }
1609
- }
1610
- // Check for completed tasks and process dependencies
1611
- const completedTasks = Array.from(this.tasks.values())
1612
- .filter(task => task.context?.objectiveId === objective.id &&
1613
- task.status === 'completed');
1614
- // Find tasks that can now be queued (dependencies met)
1615
- const pendingTasks = Array.from(this.tasks.values())
1616
- .filter(task => task.context?.objectiveId === objective.id &&
1617
- task.status === 'created' &&
1618
- this.taskDependenciesMet(task, completedTasks));
1619
- // Queue tasks with met dependencies
1620
- for (const task of pendingTasks) {
1621
- task.status = 'queued';
1622
- task.updatedAt = new Date();
1623
- task.statusHistory.push({
1624
- timestamp: new Date(),
1625
- from: 'created',
1626
- to: 'queued',
1627
- reason: 'Dependencies met, task queued',
1628
- triggeredBy: 'system'
1629
- });
1630
- this.emitSwarmEvent({
1631
- id: generateId('event'),
1632
- timestamp: new Date(),
1633
- type: 'task.queued',
1634
- source: this.swarmId.id,
1635
- data: { task },
1636
- broadcast: false,
1637
- processed: false
1638
- });
1639
- }
1640
- // Check for stuck/timed out tasks
1641
- const runningTasks = Array.from(this.tasks.values())
1642
- .filter(task => task.context?.objectiveId === objective.id &&
1643
- task.status === 'running');
1644
- const now = Date.now();
1645
- for (const task of runningTasks) {
1646
- if (task.startedAt) {
1647
- const runtime = now - task.startedAt.getTime();
1648
- const timeout = task.constraints?.timeoutAfter || SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT;
1649
- if (runtime > timeout) {
1650
- this.logger.warn('Task timed out', {
1651
- taskId: task.id.id,
1652
- runtime: Math.round(runtime / 1000),
1653
- timeout: Math.round(timeout / 1000)
1654
- });
1655
- // Mark task as failed due to timeout
1656
- task.status = 'failed';
1657
- task.completedAt = new Date();
1658
- task.error = {
1659
- type: 'TimeoutError',
1660
- message: `Task exceeded timeout of ${timeout}ms`,
1661
- code: 'TASK_TIMEOUT',
1662
- context: { taskId: task.id.id, runtime },
1663
- recoverable: true,
1664
- retryable: true
1665
- };
1666
- // Update agent state if assigned
1667
- if (task.assignedTo) {
1668
- const agent = this.agents.get(task.assignedTo.id);
1669
- if (agent) {
1670
- agent.status = 'idle';
1671
- agent.currentTask = undefined;
1672
- agent.metrics.tasksFailed++;
1673
- }
1674
- }
1675
- // Emit timeout event
1676
- this.emitSwarmEvent({
1677
- id: generateId('event'),
1678
- timestamp: new Date(),
1679
- type: 'task.failed',
1680
- source: this.swarmId.id,
1681
- data: { task, reason: 'timeout' },
1682
- broadcast: false,
1683
- processed: false
1684
- });
1685
- }
1686
- }
1687
- }
1688
- // Update objective progress
1689
- const allTasks = Array.from(this.tasks.values())
1690
- .filter(task => task.context?.objectiveId === objective.id);
1691
- objective.progress.totalTasks = allTasks.length;
1692
- objective.progress.completedTasks = allTasks.filter(t => t.status === 'completed').length;
1693
- objective.progress.failedTasks = allTasks.filter(t => t.status === 'failed').length;
1694
- objective.progress.runningTasks = allTasks.filter(t => t.status === 'running').length;
1695
- objective.progress.percentComplete = objective.progress.totalTasks > 0
1696
- ? (objective.progress.completedTasks / objective.progress.totalTasks) * 100
1697
- : 0;
1698
- // Check if objective is complete
1699
- if (objective.progress.completedTasks + objective.progress.failedTasks === objective.progress.totalTasks) {
1700
- objective.status = objective.progress.failedTasks === 0 ? 'completed' : 'failed';
1701
- objective.completedAt = new Date();
1702
- clearInterval(executionInterval);
1703
- this.logger.info('Objective completed', {
1704
- objectiveId: objective.id,
1705
- status: objective.status,
1706
- completedTasks: objective.progress.completedTasks,
1707
- failedTasks: objective.progress.failedTasks
1708
- });
1709
- this.emitSwarmEvent({
1710
- id: generateId('event'),
1711
- timestamp: new Date(),
1712
- type: objective.status === 'completed' ? 'objective.completed' : 'objective.failed',
1713
- source: this.swarmId.id,
1714
- data: { objective },
1715
- broadcast: true,
1716
- processed: false
1717
- });
1718
- }
1719
- }
1720
- catch (error) {
1721
- this.logger.error('Error in task execution loop', { error });
1722
- }
1723
- }, 2000); // Check every 2 seconds
1724
- // Store interval reference for cleanup
1725
- if (!this.executionIntervals) {
1726
- this.executionIntervals = new Map();
1727
- }
1728
- this.executionIntervals.set(objective.id, executionInterval);
1729
- }
1730
- taskDependenciesMet(task, completedTasks) {
1731
- if (!task.constraints.dependencies || task.constraints.dependencies.length === 0) {
1732
- return true;
1733
- }
1734
- const completedTaskIds = completedTasks.map(t => t.id.id);
1735
- return task.constraints.dependencies.every(dep => {
1736
- // Handle both string and TaskId object dependencies
1737
- const depId = typeof dep === 'string' ? dep : dep.id;
1738
- return completedTaskIds.includes(depId);
1739
- });
1740
- }
1741
- getNextInstanceNumber(type) {
1742
- const agentsOfType = Array.from(this.agents.values())
1743
- .filter(agent => agent.type === type);
1744
- return agentsOfType.length + 1;
1745
- }
1746
- getDefaultPermissions(type) {
1747
- switch (type) {
1748
- case 'coordinator': return ['read', 'write', 'execute', 'admin'];
1749
- case 'coder': return ['read', 'write', 'execute'];
1750
- case 'tester': return ['read', 'execute'];
1751
- case 'reviewer': return ['read', 'write'];
1752
- default: return ['read'];
1753
- }
1754
- }
1755
- async initializeAgentCapabilities(agent) {
1756
- // Set capabilities based on agent type
1757
- switch (agent.type) {
1758
- case 'coordinator':
1759
- agent.capabilities.codeGeneration = false;
1760
- agent.capabilities.codeReview = true;
1761
- agent.capabilities.testing = false;
1762
- agent.capabilities.documentation = true;
1763
- agent.capabilities.research = true;
1764
- agent.capabilities.analysis = true;
1765
- break;
1766
- case 'coder':
1767
- agent.capabilities.codeGeneration = true;
1768
- agent.capabilities.codeReview = true;
1769
- agent.capabilities.testing = true;
1770
- agent.capabilities.documentation = true;
1771
- break;
1772
- case 'researcher':
1773
- agent.capabilities.research = true;
1774
- agent.capabilities.analysis = true;
1775
- agent.capabilities.webSearch = true;
1776
- agent.capabilities.documentation = true;
1777
- break;
1778
- case 'analyst':
1779
- agent.capabilities.analysis = true;
1780
- agent.capabilities.research = true;
1781
- agent.capabilities.documentation = true;
1782
- break;
1783
- case 'reviewer':
1784
- agent.capabilities.codeReview = true;
1785
- agent.capabilities.testing = true;
1786
- agent.capabilities.documentation = true;
1787
- break;
1788
- case 'tester':
1789
- agent.capabilities.testing = true;
1790
- agent.capabilities.codeReview = true;
1791
- break;
1792
- }
1793
- }
1794
- async initializeAgentEnvironment(agent) {
1795
- // Implementation needed - setup agent environment
1796
- }
1797
- startAgentHeartbeat(agent) {
1798
- // Implementation needed - start agent heartbeat
1799
- }
1800
- stopAgentHeartbeat(agent) {
1801
- // Implementation needed - stop agent heartbeat
1802
- }
1803
- async cleanupAgentEnvironment(agent) {
1804
- // Implementation needed - cleanup agent environment
1805
- }
1806
- getRequiredCapabilities(type) {
1807
- switch (type) {
1808
- case 'coding': return ['code-generation', 'file-system'];
1809
- case 'testing': return ['testing', 'code-review'];
1810
- case 'research': return ['research', 'web-search'];
1811
- case 'analysis': return ['analysis', 'documentation'];
1812
- case 'review': return ['code-review', 'documentation'];
1813
- case 'documentation': return ['documentation'];
1814
- default: return [];
1815
- }
1816
- }
1817
- getRequiredTools(type) {
1818
- switch (type) {
1819
- case 'coding': return ['editor', 'compiler', 'debugger'];
1820
- case 'testing': return ['test-runner', 'coverage-tool'];
1821
- case 'research': return ['web-browser', 'search-engine'];
1822
- case 'analysis': return ['data-tools', 'visualization'];
1823
- default: return [];
1824
- }
1825
- }
1826
- getRequiredPermissions(type) {
1827
- switch (type) {
1828
- case 'coding': return ['read', 'write', 'execute'];
1829
- case 'testing': return ['read', 'execute'];
1830
- case 'research': return ['read', 'network'];
1831
- default: return ['read'];
1832
- }
1833
- }
1834
- async executeTaskWithAgent(task, agent) {
1835
- this.logger.info('Executing task with agent', {
1836
- taskId: task.id.id,
1837
- taskName: task.name,
1838
- agentId: agent.id.id,
1839
- agentName: agent.name
1840
- });
1841
- // Extract target directory from task
1842
- const targetDir = this.extractTargetDirectory(task);
1843
- try {
1844
- // Use Claude Flow executor for full SPARC system in non-interactive mode
1845
- const { ClaudeFlowExecutor } = await import('./claude-flow-executor.ts');
1846
- const executor = new ClaudeFlowExecutor({
1847
- logger: this.logger,
1848
- claudeFlowPath: getClaudeFlowBin(),
1849
- enableSparc: true,
1850
- verbose: this.config.logging?.level === 'debug',
1851
- timeoutMinutes: this.config.taskTimeoutMinutes
1852
- });
1853
- const result = await executor.executeTask(task, agent, targetDir);
1854
- this.logger.info('Task execution completed', {
1855
- taskId: task.id.id,
1856
- success: true,
1857
- outputLength: JSON.stringify(result).length
1858
- });
1859
- return result;
1860
- }
1861
- catch (error) {
1862
- this.logger.error('Task execution failed', {
1863
- taskId: task.id.id,
1864
- error: (error instanceof Error ? error.message : String(error))
1865
- });
1866
- throw error;
1867
- }
1868
- }
1869
- createExecutionPrompt(task) {
1870
- // Create a prompt that Claude will understand
1871
- let prompt = `# Swarm Task Execution\n\n`;
1872
- prompt += `## Task: ${task.name}\n\n`;
1873
- prompt += `${task.instructions || task.description}\n\n`;
1874
- // Add working directory information if available
1875
- const targetDir = this.extractTargetDirectory(task);
1876
- if (targetDir) {
1877
- prompt += `## Working Directory\n`;
1878
- prompt += `Please create all files in: ${targetDir}\n\n`;
1879
- }
1880
- if (task.input && Object.keys(task.input).length > 0) {
1881
- prompt += `## Additional Input\n`;
1882
- prompt += `${JSON.stringify(task.input, null, 2)}\n\n`;
1883
- }
1884
- if (task.context && Object.keys(task.context).length > 0) {
1885
- prompt += `## Context\n`;
1886
- prompt += `${JSON.stringify(task.context, null, 2)}\n\n`;
1887
- }
1888
- // Add execution guidelines
1889
- prompt += `## Guidelines\n`;
1890
- prompt += `- Focus on completing this specific task\n`;
1891
- prompt += `- Create all necessary files and directories\n`;
1892
- prompt += `- Follow best practices for the technology being used\n`;
1893
- prompt += `- Ensure the implementation is complete and functional\n`;
1894
- return prompt;
1895
- }
1896
- extractTargetDirectory(task) {
1897
- // Try multiple patterns to find the target directory
1898
- const patterns = [
1899
- /in\s+([^\s]+\/?)$/i, // "in examples/dir" at end
1900
- /(?:in|to|at)\s+([^\s]+\/[^\s]+)/i, // "in examples/gradio" anywhere
1901
- /([^\s]+\/[^\s]+)$/, // "examples/gradio" at end
1902
- /examples\/[^\s]+/i // specifically match examples/ paths
1903
- ];
1904
- let targetDir = null;
1905
- // First check task description and input
1906
- for (const pattern of patterns) {
1907
- const descMatch = task.description.match(pattern);
1908
- const inputMatch = task.input?.objective?.match(pattern);
1909
- if (descMatch || inputMatch) {
1910
- targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];
1911
- break;
1912
- }
1913
- }
1914
- // If not found and task has context with targetDir, use that
1915
- if (!targetDir && task.context?.targetDir) {
1916
- targetDir = task.context.targetDir;
1917
- }
1918
- // If still not found, check objective description from context
1919
- if (!targetDir && task.context?.objectiveId) {
1920
- const objective = this.objectives.get(task.context.objectiveId);
1921
- if (objective) {
1922
- for (const pattern of patterns) {
1923
- const match = objective.description.match(pattern);
1924
- if (match) {
1925
- targetDir = match[1] || match[0];
1926
- break;
1927
- }
1928
- }
1929
- }
1930
- }
1931
- if (targetDir) {
1932
- // Clean up the target directory
1933
- targetDir = targetDir.replace(/\s+.*$/, '');
1934
- // Resolve relative to current directory
1935
- if (!targetDir.startsWith('/')) {
1936
- targetDir = `${getClaudeFlowRoot()}/${targetDir}`;
1937
- }
1938
- }
1939
- return targetDir;
1940
- }
1941
- async executeClaudeTask(task, agent, prompt, targetDir) {
1942
- // Create unique instance ID for this execution
1943
- const instanceId = `swarm-${this.swarmId.id}-${task.id.id}-${Date.now()}`;
1944
- // Build Claude arguments for non-interactive execution
1945
- const claudeArgs = [prompt];
1946
- // Always skip permissions for swarm automation
1947
- claudeArgs.push("--dangerously-skip-permissions");
1948
- // Add non-interactive flags for automation
1949
- claudeArgs.push("-p"); // Print mode
1950
- claudeArgs.push("--output-format", "stream-json");
1951
- claudeArgs.push("--verbose"); // Required when using stream-json with -p
1952
- // Set working directory if specified
1953
- if (targetDir) {
1954
- // Ensure directory exists
1955
- await Deno.mkdir(targetDir, { recursive: true });
1956
- // Add directory context to prompt
1957
- const enhancedPrompt = `${prompt}\n\n## Important: Working Directory\nPlease ensure all files are created in: ${targetDir}`;
1958
- claudeArgs[0] = enhancedPrompt;
1959
- }
1960
- try {
1961
- // Check if claude command exists
1962
- const checkCommand = new Deno.Command('which', {
1963
- args: ['claude'],
1964
- stdout: 'piped',
1965
- stderr: 'piped',
1966
- });
1967
- const checkResult = await checkCommand.output();
1968
- if (!checkResult.success) {
1969
- throw new Error('Claude CLI not found. Please ensure claude is installed and in PATH.');
1970
- }
1971
- // Execute Claude with the prompt
1972
- const command = new Deno.Command("claude", {
1973
- args: claudeArgs,
1974
- cwd: targetDir || process.cwd(),
1975
- env: {
1976
- ...Deno.env.toObject(),
1977
- CLAUDE_INSTANCE_ID: instanceId,
1978
- CLAUDE_SWARM_MODE: "true",
1979
- CLAUDE_SWARM_ID: this.swarmId.id,
1980
- CLAUDE_TASK_ID: task.id.id,
1981
- CLAUDE_AGENT_ID: agent.id.id,
1982
- CLAUDE_WORKING_DIRECTORY: targetDir || process.cwd(),
1983
- CLAUDE_FLOW_MEMORY_ENABLED: "true",
1984
- CLAUDE_FLOW_MEMORY_NAMESPACE: `swarm-${this.swarmId.id}`,
1985
- },
1986
- stdin: "null",
1987
- stdout: "piped",
1988
- stderr: "piped",
1989
- });
1990
- this.logger.info('Spawning Claude agent for task', {
1991
- taskId: task.id.id,
1992
- agentId: agent.id.id,
1993
- instanceId,
1994
- targetDir
1995
- });
1996
- const child = command.spawn();
1997
- const { code, stdout, stderr } = await child.output();
1998
- if (code === 0) {
1999
- const output = new TextDecoder().decode(stdout);
2000
- this.logger.info('Claude agent completed task successfully', {
2001
- taskId: task.id.id,
2002
- outputLength: output.length
2003
- });
2004
- return {
2005
- success: true,
2006
- output,
2007
- instanceId,
2008
- targetDir
2009
- };
2010
- }
2011
- else {
2012
- const errorOutput = new TextDecoder().decode(stderr);
2013
- this.logger.error(`Claude agent failed with code ${code}`, {
2014
- taskId: task.id.id,
2015
- error: errorOutput
2016
- });
2017
- throw new Error(`Claude execution failed: ${errorOutput}`);
2018
- }
2019
- }
2020
- catch (error) {
2021
- this.logger.error('Failed to execute Claude agent', {
2022
- taskId: task.id.id,
2023
- error: (error instanceof Error ? error.message : String(error))
2024
- });
2025
- throw error;
2026
- }
2027
- }
2028
- determineToolsForTask(task, agent) {
2029
- const tools = new Set();
2030
- // Basic tools for all tasks
2031
- tools.add("View");
2032
- tools.add("Edit");
2033
- tools.add("Bash");
2034
- // Add tools based on task type
2035
- switch (task.type) {
2036
- case 'coding':
2037
- tools.add("Create");
2038
- tools.add("Write");
2039
- tools.add("MultiEdit");
2040
- tools.add("Test");
2041
- break;
2042
- case 'testing':
2043
- tools.add("Test");
2044
- tools.add("View");
2045
- break;
2046
- case 'documentation':
2047
- tools.add("Write");
2048
- tools.add("Create");
2049
- break;
2050
- case 'analysis':
2051
- tools.add("Analyze");
2052
- tools.add("Search");
2053
- break;
2054
- case 'research':
2055
- tools.add("WebSearch");
2056
- tools.add("Search");
2057
- break;
2058
- }
2059
- // Add tools based on agent capabilities
2060
- if (agent.capabilities.fileSystem) {
2061
- tools.add("FileSystem");
2062
- }
2063
- if (agent.capabilities.terminalAccess) {
2064
- tools.add("Terminal");
2065
- }
2066
- if (agent.capabilities.webSearch) {
2067
- tools.add("WebSearch");
2068
- }
2069
- if (agent.capabilities.apiIntegration) {
2070
- tools.add("API");
2071
- }
2072
- return Array.from(tools);
2073
- }
2074
- async simulateTaskExecution(task, agent, prompt) {
2075
- // Simulate different task types with actual file operations
2076
- // Check if task has a target directory in the description or context
2077
- let workDir = `/tmp/swarm/${this.swarmId.id}/work`;
2078
- // Extract target directory from task description or input
2079
- // Try multiple patterns to find the target directory
2080
- const patterns = [
2081
- /in\s+([^\s]+\/?)$/i, // "in examples/dir" at end
2082
- /(?:in|to|at)\s+([^\s]+\/[^\s]+)/i, // "in examples/gradio" anywhere
2083
- /([^\s]+\/[^\s]+)$/, // "examples/gradio" at end
2084
- /examples\/[^\s]+/i // specifically match examples/ paths
2085
- ];
2086
- let targetDir = null;
2087
- for (const pattern of patterns) {
2088
- const descMatch = task.description.match(pattern);
2089
- const inputMatch = task.input?.objective?.match(pattern);
2090
- if (descMatch || inputMatch) {
2091
- targetDir = (descMatch || inputMatch)[descMatch ? 1 : 0];
2092
- break;
2093
- }
2094
- }
2095
- if (targetDir) {
2096
- // Clean up the target directory (remove trailing words if needed)
2097
- targetDir = targetDir.replace(/\s+.*$/, '');
2098
- // Use absolute path or resolve relative to current directory
2099
- workDir = targetDir.startsWith('/') ? targetDir : `${getClaudeFlowRoot()}/${targetDir}`;
2100
- this.logger.debug('Extracted target directory', {
2101
- original: task.description,
2102
- targetDir,
2103
- workDir
2104
- });
2105
- }
2106
- try {
2107
- // Ensure work directory exists
2108
- await Deno.mkdir(workDir, { recursive: true });
2109
- switch (task.type) {
2110
- case 'coding':
2111
- return await this.executeCodeGenerationTask(task, workDir, agent);
2112
- case 'analysis':
2113
- return await this.executeAnalysisTask(task, workDir, agent);
2114
- case 'documentation':
2115
- return await this.executeDocumentationTask(task, workDir, agent);
2116
- case 'testing':
2117
- return await this.executeTestingTask(task, workDir, agent);
2118
- default:
2119
- return await this.executeGenericTask(task, workDir, agent);
2120
- }
2121
- }
2122
- catch (error) {
2123
- throw new Error(`Task execution failed: ${(error instanceof Error ? error.message : String(error))}`);
2124
- }
2125
- }
2126
- async executeCodeGenerationTask(task, workDir, agent) {
2127
- this.logger.info('Executing code generation task', { taskId: task.id.id });
2128
- // Detect technology from description
2129
- const description = task.description.toLowerCase();
2130
- const isGradio = description.includes('gradio');
2131
- const isPython = isGradio || description.includes('python') || description.includes('fastapi') || description.includes('django');
2132
- const isHelloWorld = description.includes('hello') && description.includes('world');
2133
- const isRestAPI = description.includes('rest api') || description.includes('api');
2134
- if (isGradio) {
2135
- // Create a Gradio application
2136
- return await this.createGradioApp(task, workDir);
2137
- }
2138
- else if (isPython && isRestAPI) {
2139
- // Create a Python REST API (FastAPI)
2140
- return await this.createPythonRestAPI(task, workDir);
2141
- }
2142
- else if (isRestAPI) {
2143
- // Create a REST API application
2144
- const projectName = 'rest-api';
2145
- const projectDir = `${workDir}/${projectName}`;
2146
- await Deno.mkdir(projectDir, { recursive: true });
2147
- // Create main API file
2148
- const apiCode = `const express = require('express');
2149
- const app = express();
2150
- const port = process.env.PORT || 3000;
2151
-
2152
- // Middleware
2153
- app.use(express.json());
2154
- app.use(express.urlencoded({ extended: true }));
2155
-
2156
- // Health check endpoint
2157
- app.get('/health', (req, res) => {
2158
- res.json({
2159
- status: 'healthy',
2160
- service: 'REST API',
2161
- swarmId: '${this.swarmId.id}',
2162
- created: '${new Date().toISOString()}'
2163
- });
2164
- });
2165
-
2166
- // Sample endpoints
2167
- app.get('/api/v1/items', (req, res) => {
2168
- res.json({
2169
- items: [
2170
- { id: 1, name: 'Item 1', description: 'First item' },
2171
- { id: 2, name: 'Item 2', description: 'Second item' }
2172
- ],
2173
- total: 2
2174
- });
2175
- });
2176
-
2177
- app.get('/api/v1/items/:id', (req, res) => {
2178
- const id = parseInt(req.params.id);
2179
- res.json({
2180
- id,
2181
- name: \`Item \${id}\`,
2182
- description: \`Description for item \${id}\`
2183
- });
2184
- });
2185
-
2186
- app.post('/api/v1/items', (req, res) => {
2187
- const newItem = {
2188
- id: Date.now(),
2189
- ...req.body,
2190
- createdAt: new Date().toISOString()
2191
- };
2192
- res.status(201).json(newItem);
2193
- });
2194
-
2195
- app.put('/api/v1/items/:id', (req, res) => {
2196
- const id = parseInt(req.params.id);
2197
- const updatedItem = {
2198
- id,
2199
- ...req.body,
2200
- updatedAt: new Date().toISOString()
2201
- };
2202
- res.json(updatedItem);
2203
- });
2204
-
2205
- app.delete('/api/v1/items/:id', (req, res) => {
2206
- const id = parseInt(req.params.id);
2207
- res.json({ message: \`Item \${id} deleted successfully\` });
2208
- });
2209
-
2210
- // Error handling middleware
2211
- app.use((err, req, res, next) => {
2212
- console.error(err.stack);
2213
- res.status(500).json({ error: 'Internal server error' });
2214
- });
2215
-
2216
- // Start server
2217
- app.listen(port, () => {
2218
- console.log(\`REST API server running on port \${port}\`);
2219
- console.log('Created by Claude Flow Swarm');
2220
- });
2221
-
2222
- module.exports = app;
2223
- `;
2224
- await fs.writeFile(`${projectDir}/server.js`, apiCode);
2225
- // Create package.json
2226
- const packageJson = {
2227
- name: projectName,
2228
- version: "1.0.0",
2229
- description: "REST API created by Claude Flow Swarm",
2230
- main: "server.js",
2231
- scripts: {
2232
- start: "node server.js",
2233
- dev: "nodemon server.js",
2234
- test: "jest"
2235
- },
2236
- keywords: ["rest", "api", "swarm", "claude-flow"],
2237
- author: "Claude Flow Swarm",
2238
- license: "MIT",
2239
- dependencies: {
2240
- express: "^4.18.2"
2241
- },
2242
- devDependencies: {
2243
- nodemon: "^3.0.1",
2244
- jest: "^29.7.0",
2245
- supertest: "^6.3.3"
2246
- },
2247
- swarmMetadata: {
2248
- swarmId: this.swarmId.id,
2249
- taskId: task.id.id,
2250
- agentId: agent.id.id,
2251
- created: new Date().toISOString()
2252
- }
2253
- };
2254
- await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));
2255
- // Create README
2256
- const readme = `# REST API
2257
-
2258
- This REST API was created by the Claude Flow Swarm system.
2259
-
2260
- ## Swarm Details
2261
- - Swarm ID: ${this.swarmId.id}
2262
- - Task: ${task.name}
2263
- - Agent: ${agent.name}
2264
- - Generated: ${new Date().toISOString()}
2265
-
2266
- ## Installation
2267
-
2268
- \`\`\`bash
2269
- npm install
2270
- \`\`\`
2271
-
2272
- ## Usage
2273
-
2274
- Start the server:
2275
- \`\`\`bash
2276
- npm start
2277
- \`\`\`
2278
-
2279
- Development mode with auto-reload:
2280
- \`\`\`bash
2281
- npm run dev
2282
- \`\`\`
2283
-
2284
- ## API Endpoints
2285
-
2286
- - \`GET /health\` - Health check
2287
- - \`GET /api/v1/items\` - Get all items
2288
- - \`GET /api/v1/items/:id\` - Get item by ID
2289
- - \`POST /api/v1/items\` - Create new item
2290
- - \`PUT /api/v1/items/:id\` - Update item
2291
- - \`DELETE /api/v1/items/:id\` - Delete item
2292
-
2293
- ## Description
2294
- ${task.description}
2295
-
2296
- ---
2297
- Created by Claude Flow Swarm
2298
- `;
2299
- await fs.writeFile(`${projectDir}/README.md`, readme);
2300
- // Create .gitignore
2301
- const gitignore = `node_modules/
2302
- .env
2303
- *.log
2304
- .DS_Store
2305
- coverage/
2306
- `;
2307
- await fs.writeFile(`${projectDir}/.gitignore`, gitignore);
2308
- return {
2309
- success: true,
2310
- output: {
2311
- message: 'REST API created successfully',
2312
- location: projectDir,
2313
- files: ['server.js', 'package.json', 'README.md', '.gitignore']
2314
- },
2315
- artifacts: {
2316
- mainFile: `${projectDir}/server.js`,
2317
- packageFile: `${projectDir}/package.json`,
2318
- readmeFile: `${projectDir}/README.md`
2319
- }
2320
- };
2321
- }
2322
- else if (isHelloWorld) {
2323
- // Create a simple hello world application
2324
- const projectDir = `${workDir}/hello-world`;
2325
- await Deno.mkdir(projectDir, { recursive: true });
2326
- // Create main application file
2327
- const mainCode = `#!/usr/bin/env node
2328
-
2329
- // Hello World Application
2330
- // Generated by Claude Flow Swarm
2331
-
2332
- console.log('Hello, World!');
2333
- console.log('This application was created by the Claude Flow Swarm system.');
2334
- console.log('Swarm ID: ${this.swarmId.id}');
2335
- console.log('Task: ${task.name}');
2336
- console.log('Generated at: ${new Date().toISOString()}');
2337
-
2338
- // Export for testing
2339
- if (typeof module !== 'undefined' && module.exports) {
2340
- module.exports = { message: 'Hello, World!' };
2341
- }
2342
- `;
2343
- await fs.writeFile(`${projectDir}/index.js`, mainCode);
2344
- // Create package.json
2345
- const packageJson = {
2346
- name: "hello-world",
2347
- version: "1.0.0",
2348
- description: "Hello World application created by Claude Flow Swarm",
2349
- main: "index.js",
2350
- scripts: {
2351
- start: "node index.js",
2352
- test: "node test.js"
2353
- },
2354
- keywords: ["hello-world", "swarm", "claude-flow"],
2355
- author: "Claude Flow Swarm",
2356
- license: "MIT"
2357
- };
2358
- await fs.writeFile(`${projectDir}/package.json`, JSON.stringify(packageJson, null, 2));
2359
- // Create README
2360
- const readme = `# Hello World
2361
-
2362
- This application was created by the Claude Flow Swarm system.
2363
-
2364
- ## Swarm Details
2365
- - Swarm ID: ${this.swarmId.id}
2366
- - Task: ${task.name}
2367
- - Generated: ${new Date().toISOString()}
2368
-
2369
- ## Usage
2370
-
2371
- \`\`\`bash
2372
- npm start
2373
- \`\`\`
2374
-
2375
- ## Description
2376
- ${task.description}
2377
- `;
2378
- await fs.writeFile(`${projectDir}/README.md`, readme);
2379
- return {
2380
- success: true,
2381
- output: {
2382
- message: 'Hello World application created successfully',
2383
- location: projectDir,
2384
- files: ['index.js', 'package.json', 'README.md']
2385
- },
2386
- artifacts: {
2387
- mainFile: `${projectDir}/index.js`,
2388
- packageFile: `${projectDir}/package.json`,
2389
- readmeFile: `${projectDir}/README.md`
2390
- }
2391
- };
2392
- }
2393
- // For other code generation tasks, create a basic structure
2394
- const projectDir = `${workDir}/generated-code`;
2395
- await Deno.mkdir(projectDir, { recursive: true });
2396
- const code = `// Generated code for: ${task.name}
2397
- // ${task.description}
2398
-
2399
- function main() {
2400
- console.log('Executing task: ${task.name}');
2401
- // Implementation would go here
2402
- }
2403
-
2404
- main();
2405
- `;
2406
- await fs.writeFile(`${projectDir}/main.js`, code);
2407
- return {
2408
- success: true,
2409
- output: {
2410
- message: 'Code generated successfully',
2411
- location: projectDir,
2412
- files: ['main.js']
2413
- }
2414
- };
2415
- }
2416
- async executeAnalysisTask(task, workDir, agent) {
2417
- this.logger.info('Executing analysis task', { taskId: task.id.id });
2418
- const analysisDir = `${workDir}/analysis`;
2419
- await Deno.mkdir(analysisDir, { recursive: true });
2420
- const analysis = {
2421
- task: task.name,
2422
- description: task.description,
2423
- timestamp: new Date().toISOString(),
2424
- findings: [
2425
- 'Analysis point 1: Task objectives are clear',
2426
- 'Analysis point 2: Resources are allocated',
2427
- 'Analysis point 3: Implementation path is defined'
2428
- ],
2429
- recommendations: [
2430
- 'Proceed with implementation',
2431
- 'Monitor progress regularly',
2432
- 'Adjust resources as needed'
2433
- ]
2434
- };
2435
- await fs.writeFile(`${analysisDir}/analysis-report.json`, JSON.stringify(analysis, null, 2));
2436
- return {
2437
- success: true,
2438
- output: analysis,
2439
- artifacts: {
2440
- report: `${analysisDir}/analysis-report.json`
2441
- }
2442
- };
2443
- }
2444
- async executeDocumentationTask(task, workDir, agent) {
2445
- this.logger.info('Executing documentation task', { taskId: task.id.id });
2446
- const docsDir = `${workDir}/docs`;
2447
- await Deno.mkdir(docsDir, { recursive: true });
2448
- const documentation = `# ${task.name}
2449
-
2450
- ${task.description}
2451
-
2452
- ## Overview
2453
- This documentation was generated by the Claude Flow Swarm system.
2454
-
2455
- ## Details
2456
- - Task ID: ${task.id.id}
2457
- - Generated: ${new Date().toISOString()}
2458
- - Swarm ID: ${this.swarmId.id}
2459
-
2460
- ## Instructions
2461
- ${task.instructions}
2462
-
2463
- ## Implementation Notes
2464
- - This is an automated documentation generated by the swarm
2465
- - Further details would be added based on actual implementation
2466
- `;
2467
- await fs.writeFile(`${docsDir}/documentation.md`, documentation);
2468
- return {
2469
- success: true,
2470
- output: {
2471
- message: 'Documentation created successfully',
2472
- location: docsDir,
2473
- files: ['documentation.md']
2474
- },
2475
- artifacts: {
2476
- documentation: `${docsDir}/documentation.md`
2477
- }
2478
- };
2479
- }
2480
- async executeTestingTask(task, workDir, agent) {
2481
- this.logger.info('Executing testing task', { taskId: task.id.id });
2482
- const testDir = `${workDir}/tests`;
2483
- await Deno.mkdir(testDir, { recursive: true });
2484
- const testCode = `// Test suite for: ${task.name}
2485
- // ${task.description}
2486
-
2487
- const assert = require('assert');
2488
-
2489
- describe('${task.name}', () => {
2490
- it('should pass basic test', () => {
2491
- assert.strictEqual(1 + 1, 2);
2492
- });
2493
-
2494
- it('should validate implementation', () => {
2495
- // Test implementation would go here
2496
- assert.ok(true, 'Implementation validated');
2497
- });
2498
- });
2499
-
2500
- console.log('Tests completed for: ${task.name}');
2501
- `;
2502
- await fs.writeFile(`${testDir}/test.js`, testCode);
2503
- return {
2504
- success: true,
2505
- output: {
2506
- message: 'Test suite created successfully',
2507
- location: testDir,
2508
- files: ['test.js'],
2509
- testsPassed: 2,
2510
- testsFailed: 0
2511
- },
2512
- artifacts: {
2513
- testFile: `${testDir}/test.js`
2514
- }
2515
- };
2516
- }
2517
- async executeGenericTask(task, workDir, agent) {
2518
- this.logger.info('Executing generic task', { taskId: task.id.id });
2519
- const outputDir = `${workDir}/output`;
2520
- await Deno.mkdir(outputDir, { recursive: true });
2521
- const output = {
2522
- task: task.name,
2523
- type: task.type,
2524
- description: task.description,
2525
- status: 'completed',
2526
- timestamp: new Date().toISOString(),
2527
- result: 'Task executed successfully'
2528
- };
2529
- await fs.writeFile(`${outputDir}/result.json`, JSON.stringify(output, null, 2));
2530
- return {
2531
- success: true,
2532
- output,
2533
- artifacts: {
2534
- result: `${outputDir}/result.json`
2535
- }
2536
- };
2537
- }
2538
- assessTaskQuality(task, result) {
2539
- // Implementation needed - assess task quality
2540
- return 0.8;
2541
- }
2542
- updateAgentMetrics(agent, task) {
2543
- // Update agent performance metrics
2544
- const executionTime = task.completedAt.getTime() - (task.startedAt?.getTime() || 0);
2545
- agent.metrics.averageExecutionTime =
2546
- (agent.metrics.averageExecutionTime * agent.metrics.tasksCompleted + executionTime) /
2547
- (agent.metrics.tasksCompleted + 1);
2548
- agent.metrics.successRate =
2549
- agent.metrics.tasksCompleted / (agent.metrics.tasksCompleted + agent.metrics.tasksFailed);
2550
- }
2551
- async processDependentTasks(task) {
2552
- // Implementation needed - process tasks that depend on this one
2553
- }
2554
- isRecoverableError(error) {
2555
- // Implementation needed - determine if error is recoverable
2556
- return true;
2557
- }
2558
- isRetryableError(error) {
2559
- // Implementation needed - determine if error is retryable
2560
- return true;
2561
- }
2562
- async handleTaskFailureCascade(task) {
2563
- // Implementation needed - handle failure cascade
2564
- }
2565
- async reassignTask(taskId) {
2566
- // Implementation needed - reassign task to different agent
2567
- }
2568
- processHeartbeats() {
2569
- const now = new Date();
2570
- const timeout = this.config.monitoring.heartbeatInterval * 10; // Increased multiplier for long-running Claude tasks
2571
- for (const agent of this.agents.values()) {
2572
- if (agent.status === 'offline' || agent.status === 'terminated') {
2573
- continue;
2574
- }
2575
- const timeSinceHeartbeat = now.getTime() - agent.lastHeartbeat.getTime();
2576
- if (timeSinceHeartbeat > timeout) {
2577
- this.logger.warn('Agent heartbeat timeout', {
2578
- agentId: agent.id.id,
2579
- timeSinceHeartbeat
2580
- });
2581
- agent.status = 'error';
2582
- agent.health = 0;
2583
- }
2584
- }
2585
- }
2586
- updateSwarmMetrics() {
2587
- // Implementation needed - update swarm-level metrics
2588
- }
2589
- performCleanup() {
2590
- // Implementation needed - perform periodic cleanup
2591
- }
2592
- checkObjectiveCompletion() {
2593
- // Implementation needed - check if objectives are complete
2594
- }
2595
- checkObjectiveFailure(task) {
2596
- // Implementation needed - check if objective has failed
2597
- }
2598
- handleAgentError(agentId, error) {
2599
- const agent = this.agents.get(agentId);
2600
- if (agent) {
2601
- agent.status = 'error';
2602
- agent.health = 0;
2603
- this.logger.error('Agent error', { agentId, error });
2604
- }
2605
- }
2606
- }
2607
- //# sourceMappingURL=coordinator.js.map