claude-flow-novice 2.0.3 → 2.0.4

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 (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -1,173 +1,144 @@
1
1
  /**
2
2
  * MCP Tool Wrapper for Hive Mind System
3
3
  * Wraps all 87 MCP tools for coordinated swarm usage
4
- */
5
-
6
- import { spawn } from 'child_process';
7
-
8
- /**
4
+ */ /**
9
5
  * MCP Tool categories and their methods
10
- */
11
- const MCP_TOOLS = {
12
- swarm: [
13
- 'swarm_init',
14
- 'agent_spawn',
15
- 'task_orchestrate',
16
- 'swarm_status',
17
- 'agent_list',
18
- 'agent_metrics',
19
- 'swarm_monitor',
20
- 'topology_optimize',
21
- 'load_balance',
22
- 'coordination_sync',
23
- 'swarm_scale',
24
- 'swarm_destroy',
25
- ],
26
- neural: [
27
- 'neural_status',
28
- 'neural_train',
29
- 'neural_patterns',
30
- 'neural_predict',
31
- 'model_load',
32
- 'model_save',
33
- 'wasm_optimize',
34
- 'inference_run',
35
- 'pattern_recognize',
36
- 'cognitive_analyze',
37
- 'learning_adapt',
38
- 'neural_compress',
39
- 'ensemble_create',
40
- 'transfer_learn',
41
- 'neural_explain',
42
- ],
43
- memory: [
44
- 'memory_usage',
45
- 'memory_search',
46
- 'memory_persist',
47
- 'memory_namespace',
48
- 'memory_backup',
49
- 'memory_restore',
50
- 'memory_compress',
51
- 'memory_sync',
52
- 'cache_manage',
53
- 'state_snapshot',
54
- 'context_restore',
55
- 'memory_analytics',
56
- ],
57
- performance: [
58
- 'performance_report',
59
- 'bottleneck_analyze',
60
- 'token_usage',
61
- 'benchmark_run',
62
- 'metrics_collect',
63
- 'trend_analysis',
64
- 'cost_analysis',
65
- 'quality_assess',
66
- 'error_analysis',
67
- 'usage_stats',
68
- 'health_check',
69
- ],
70
- github: [
71
- 'github_repo_analyze',
72
- 'github_pr_manage',
73
- 'github_issue_track',
74
- 'github_release_coord',
75
- 'github_workflow_auto',
76
- 'github_code_review',
77
- 'github_sync_coord',
78
- 'github_metrics',
79
- ],
80
- workflow: [
81
- 'workflow_create',
82
- 'workflow_execute',
83
- 'workflow_export',
84
- 'automation_setup',
85
- 'pipeline_create',
86
- 'scheduler_manage',
87
- 'trigger_setup',
88
- 'workflow_template',
89
- 'batch_process',
90
- 'parallel_execute',
91
- ],
92
- daa: [
93
- 'daa_agent_create',
94
- 'daa_capability_match',
95
- 'daa_resource_alloc',
96
- 'daa_lifecycle_manage',
97
- 'daa_communication',
98
- 'daa_consensus',
99
- 'daa_fault_tolerance',
100
- 'daa_optimization',
101
- ],
102
- system: [
103
- 'terminal_execute',
104
- 'config_manage',
105
- 'features_detect',
106
- 'security_scan',
107
- 'backup_create',
108
- 'restore_system',
109
- 'log_analysis',
110
- 'diagnostic_run',
111
- ],
112
- sparc: ['sparc_mode'],
113
- task: ['task_status', 'task_results'],
6
+ */ const MCP_TOOLS = {
7
+ swarm: [
8
+ 'swarm_init',
9
+ 'agent_spawn',
10
+ 'task_orchestrate',
11
+ 'swarm_status',
12
+ 'agent_list',
13
+ 'agent_metrics',
14
+ 'swarm_monitor',
15
+ 'topology_optimize',
16
+ 'load_balance',
17
+ 'coordination_sync',
18
+ 'swarm_scale',
19
+ 'swarm_destroy'
20
+ ],
21
+ neural: [
22
+ 'neural_status',
23
+ 'neural_train',
24
+ 'neural_patterns',
25
+ 'neural_predict',
26
+ 'model_load',
27
+ 'model_save',
28
+ 'wasm_optimize',
29
+ 'inference_run',
30
+ 'pattern_recognize',
31
+ 'cognitive_analyze',
32
+ 'learning_adapt',
33
+ 'neural_compress',
34
+ 'ensemble_create',
35
+ 'transfer_learn',
36
+ 'neural_explain'
37
+ ],
38
+ memory: [
39
+ 'memory_usage',
40
+ 'memory_search',
41
+ 'memory_persist',
42
+ 'memory_namespace',
43
+ 'memory_backup',
44
+ 'memory_restore',
45
+ 'memory_compress',
46
+ 'memory_sync',
47
+ 'cache_manage',
48
+ 'state_snapshot',
49
+ 'context_restore',
50
+ 'memory_analytics'
51
+ ],
52
+ performance: [
53
+ 'performance_report',
54
+ 'bottleneck_analyze',
55
+ 'token_usage',
56
+ 'benchmark_run',
57
+ 'metrics_collect',
58
+ 'trend_analysis',
59
+ 'cost_analysis',
60
+ 'quality_assess',
61
+ 'error_analysis',
62
+ 'usage_stats',
63
+ 'health_check'
64
+ ],
65
+ github: [
66
+ 'github_repo_analyze',
67
+ 'github_pr_manage',
68
+ 'github_issue_track',
69
+ 'github_release_coord',
70
+ 'github_workflow_auto',
71
+ 'github_code_review',
72
+ 'github_sync_coord',
73
+ 'github_metrics'
74
+ ],
75
+ workflow: [
76
+ 'workflow_create',
77
+ 'workflow_execute',
78
+ 'workflow_export',
79
+ 'automation_setup',
80
+ 'pipeline_create',
81
+ 'scheduler_manage',
82
+ 'trigger_setup',
83
+ 'workflow_template',
84
+ 'batch_process',
85
+ 'parallel_execute'
86
+ ],
87
+ daa: [
88
+ 'daa_agent_create',
89
+ 'daa_capability_match',
90
+ 'daa_resource_alloc',
91
+ 'daa_lifecycle_manage',
92
+ 'daa_communication',
93
+ 'daa_consensus',
94
+ 'daa_fault_tolerance',
95
+ 'daa_optimization'
96
+ ],
97
+ system: [
98
+ 'terminal_execute',
99
+ 'config_manage',
100
+ 'features_detect',
101
+ 'security_scan',
102
+ 'backup_create',
103
+ 'restore_system',
104
+ 'log_analysis',
105
+ 'diagnostic_run'
106
+ ],
107
+ sparc: [
108
+ 'sparc_mode'
109
+ ],
110
+ task: [
111
+ 'task_status',
112
+ 'task_results'
113
+ ]
114
114
  };
115
-
116
115
  /**
117
116
  * MCPToolWrapper class for unified MCP tool access
118
- */
119
- export class MCPToolWrapper {
120
- constructor(config = {}) {
121
- this.config = {
122
- parallel: true,
123
- timeout: 60000,
124
- retryCount: 3,
125
- ...config,
126
- };
127
-
128
- this.toolStats = new Map();
129
- this.parallelQueue = [];
130
- this.executing = false;
131
-
132
- /** @type {import('better-sqlite3').Database | null} */
133
- this.memoryDb = null;
134
-
135
- // Initialize memory store for fallback
136
- this.memoryStore = new Map();
137
-
138
- // Initialize real memory storage
139
- this.initializeMemoryStorage();
140
- }
141
-
142
- /**
117
+ */ export class MCPToolWrapper {
118
+ /**
143
119
  * Initialize real memory storage using SQLite
144
- */
145
- async initializeMemoryStorage() {
146
- try {
147
- const { createDatabase, isSQLiteAvailable } = await import(
148
- '../../../memory/sqlite-wrapper.js'
149
- );
150
- const path = await import('path');
151
- const fs = await import('fs');
152
-
153
- // Check if SQLite is available
154
- const sqliteAvailable = await isSQLiteAvailable();
155
- if (!sqliteAvailable) {
156
- throw new Error('SQLite not available');
157
- }
158
-
159
- // Create .hive-mind directory if it doesn't exist
160
- const hiveMindDir = path.join(process.cwd(), '.hive-mind');
161
- if (!fs.existsSync(hiveMindDir)) {
162
- fs.mkdirSync(hiveMindDir, { recursive: true });
163
- }
164
-
165
- // Initialize SQLite database
166
- const dbPath = path.join(hiveMindDir, 'memory.db');
167
- this.memoryDb = await createDatabase(dbPath);
168
-
169
- // Create memories table
170
- this.memoryDb.exec(`
120
+ */ async initializeMemoryStorage() {
121
+ try {
122
+ const { createDatabase, isSQLiteAvailable } = await import("../../../memory/sqlite-wrapper.js");
123
+ const path = await import("path");
124
+ const fs = await import("fs");
125
+ // Check if SQLite is available
126
+ const sqliteAvailable = await isSQLiteAvailable();
127
+ if (!sqliteAvailable) {
128
+ throw new Error('SQLite not available');
129
+ }
130
+ // Create .hive-mind directory if it doesn't exist
131
+ const hiveMindDir = path.join(process.cwd(), '.hive-mind');
132
+ if (!fs.existsSync(hiveMindDir)) {
133
+ fs.mkdirSync(hiveMindDir, {
134
+ recursive: true
135
+ });
136
+ }
137
+ // Initialize SQLite database
138
+ const dbPath = path.join(hiveMindDir, 'memory.db');
139
+ this.memoryDb = await createDatabase(dbPath);
140
+ // Create memories table
141
+ this.memoryDb.exec(`
171
142
  CREATE TABLE IF NOT EXISTS memories (
172
143
  id INTEGER PRIMARY KEY AUTOINCREMENT,
173
144
  namespace TEXT NOT NULL,
@@ -179,989 +150,890 @@ export class MCPToolWrapper {
179
150
  UNIQUE(namespace, key)
180
151
  )
181
152
  `);
182
-
183
- // Real memory storage initialized with SQLite
184
- } catch (error) {
185
- console.warn(
186
- 'Failed to initialize SQLite storage, falling back to in-memory:',
187
- error.message,
188
- );
189
- this.memoryDb = null;
190
- this.memoryStore = new Map(); // Fallback to in-memory storage
191
-
192
- // Log Windows-specific help if applicable
193
- if (process.platform === 'win32') {
194
- console.info(`
153
+ // Real memory storage initialized with SQLite
154
+ } catch (error) {
155
+ console.warn('Failed to initialize SQLite storage, falling back to in-memory:', error.message);
156
+ this.memoryDb = null;
157
+ this.memoryStore = new Map(); // Fallback to in-memory storage
158
+ // Log Windows-specific help if applicable
159
+ if (process.platform === 'win32') {
160
+ console.info(`
195
161
  Windows users: For persistent storage, please see installation guide:
196
162
  https://github.com/ruvnet/claude-code-flow/docs/windows-installation.md
197
163
  `);
198
- }
164
+ }
165
+ }
199
166
  }
200
- }
201
-
202
- /**
167
+ /**
203
168
  * Execute MCP tool with automatic retry and error handling
204
- */
205
- async executeTool(toolName, params = {}) {
206
- const startTime = Date.now();
207
- let lastError = null;
208
-
209
- for (let attempt = 1; attempt <= this.config.retryCount; attempt++) {
210
- try {
211
- const result = await this._executeToolInternal(toolName, params);
212
-
213
- // Track statistics
214
- this._trackToolUsage(toolName, Date.now() - startTime, true);
215
-
216
- return result;
217
- } catch (error) {
218
- lastError = error;
219
- console.error(`Attempt ${attempt} failed for ${toolName}:`, error.message);
220
-
221
- if (attempt < this.config.retryCount) {
222
- // Exponential backoff
223
- await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 1000));
169
+ */ async executeTool(toolName, params = {}) {
170
+ const startTime = Date.now();
171
+ let lastError = null;
172
+ for(let attempt = 1; attempt <= this.config.retryCount; attempt++){
173
+ try {
174
+ const result = await this._executeToolInternal(toolName, params);
175
+ // Track statistics
176
+ this._trackToolUsage(toolName, Date.now() - startTime, true);
177
+ return result;
178
+ } catch (error) {
179
+ lastError = error;
180
+ console.error(`Attempt ${attempt} failed for ${toolName}:`, error.message);
181
+ if (attempt < this.config.retryCount) {
182
+ // Exponential backoff
183
+ await new Promise((resolve)=>setTimeout(resolve, Math.pow(2, attempt) * 1000));
184
+ }
185
+ }
224
186
  }
225
- }
187
+ // Track failure
188
+ this._trackToolUsage(toolName, Date.now() - startTime, false);
189
+ throw new Error(`Failed to execute ${toolName} after ${this.config.retryCount} attempts: ${lastError.message}`);
226
190
  }
227
-
228
- // Track failure
229
- this._trackToolUsage(toolName, Date.now() - startTime, false);
230
-
231
- throw new Error(
232
- `Failed to execute ${toolName} after ${this.config.retryCount} attempts: ${lastError.message}`,
233
- );
234
- }
235
-
236
- /**
191
+ /**
237
192
  * Execute multiple tools in parallel with optimized batching
238
- */
239
- async executeParallel(toolCalls) {
240
- if (!this.config.parallel) {
241
- // Execute sequentially if parallel is disabled
242
- const results = [];
243
- for (const call of toolCalls) {
244
- results.push(await this.executeTool(call.tool, call.params));
245
- }
246
- return results;
247
- }
248
-
249
- if (!Array.isArray(toolCalls) || toolCalls.length === 0) {
250
- return [];
251
- }
252
-
253
- const startTime = Date.now();
254
-
255
- // Intelligent concurrency limit based on tool types
256
- const concurrencyLimit = this._calculateOptimalConcurrency(toolCalls);
257
-
258
- // Group tools by priority and dependency
259
- const toolGroups = this._groupToolsByPriority(toolCalls);
260
- const allResults = [];
261
-
262
- try {
263
- // Execute high-priority tools first
264
- for (const group of toolGroups) {
265
- const groupResults = [];
266
-
267
- for (let i = 0; i < group.length; i += concurrencyLimit) {
268
- const batch = group.slice(i, i + concurrencyLimit);
269
-
270
- // Execute batch with timeout and retry logic
271
- const batchPromises = batch.map((call) =>
272
- this._executeWithTimeout(call, this.config.timeout),
273
- );
274
-
275
- const batchResults = await Promise.allSettled(batchPromises);
276
-
277
- // Process results and handle failures
278
- for (let j = 0; j < batchResults.length; j++) {
279
- const result = batchResults[j];
280
- if (result.status === 'fulfilled') {
281
- groupResults.push(result.value);
282
- } else {
283
- console.warn(`Tool execution failed: ${batch[j].tool}`, result.reason);
284
- groupResults.push({ error: result.reason.message, tool: batch[j].tool });
193
+ */ async executeParallel(toolCalls) {
194
+ if (!this.config.parallel) {
195
+ // Execute sequentially if parallel is disabled
196
+ const results = [];
197
+ for (const call of toolCalls){
198
+ results.push(await this.executeTool(call.tool, call.params));
285
199
  }
286
- }
200
+ return results;
201
+ }
202
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) {
203
+ return [];
204
+ }
205
+ const startTime = Date.now();
206
+ // Intelligent concurrency limit based on tool types
207
+ const concurrencyLimit = this._calculateOptimalConcurrency(toolCalls);
208
+ // Group tools by priority and dependency
209
+ const toolGroups = this._groupToolsByPriority(toolCalls);
210
+ const allResults = [];
211
+ try {
212
+ // Execute high-priority tools first
213
+ for (const group of toolGroups){
214
+ const groupResults = [];
215
+ for(let i = 0; i < group.length; i += concurrencyLimit){
216
+ const batch = group.slice(i, i + concurrencyLimit);
217
+ // Execute batch with timeout and retry logic
218
+ const batchPromises = batch.map((call)=>this._executeWithTimeout(call, this.config.timeout));
219
+ const batchResults = await Promise.allSettled(batchPromises);
220
+ // Process results and handle failures
221
+ for(let j = 0; j < batchResults.length; j++){
222
+ const result = batchResults[j];
223
+ if (result.status === 'fulfilled') {
224
+ groupResults.push(result.value);
225
+ } else {
226
+ console.warn(`Tool execution failed: ${batch[j].tool}`, result.reason);
227
+ groupResults.push({
228
+ error: result.reason.message,
229
+ tool: batch[j].tool
230
+ });
231
+ }
232
+ }
233
+ }
234
+ allResults.push(...groupResults);
235
+ }
236
+ // Track performance metrics
237
+ const executionTime = Date.now() - startTime;
238
+ this._trackBatchPerformance(toolCalls.length, executionTime, concurrencyLimit);
239
+ return allResults;
240
+ } catch (error) {
241
+ console.error('Parallel execution failed:', error);
242
+ throw error;
287
243
  }
288
-
289
- allResults.push(...groupResults);
290
- }
291
-
292
- // Track performance metrics
293
- const executionTime = Date.now() - startTime;
294
- this._trackBatchPerformance(toolCalls.length, executionTime, concurrencyLimit);
295
-
296
- return allResults;
297
- } catch (error) {
298
- console.error('Parallel execution failed:', error);
299
- throw error;
300
244
  }
301
- }
302
-
303
- /**
245
+ /**
304
246
  * Calculate optimal concurrency based on tool types
305
- */
306
- _calculateOptimalConcurrency(toolCalls) {
307
- const toolTypes = toolCalls.map((call) => this._getToolCategory(call.tool));
308
- const uniqueTypes = new Set(toolTypes);
309
-
310
- // Heavy operations (neural, github) need lower concurrency
311
- const heavyTypes = ['neural', 'github', 'workflow'];
312
- const hasHeavyOps = toolTypes.some((type) => heavyTypes.includes(type));
313
-
314
- if (hasHeavyOps) {
315
- return Math.min(3, Math.max(1, Math.floor(toolCalls.length / 2)));
247
+ */ _calculateOptimalConcurrency(toolCalls) {
248
+ const toolTypes = toolCalls.map((call)=>this._getToolCategory(call.tool));
249
+ const uniqueTypes = new Set(toolTypes);
250
+ // Heavy operations (neural, github) need lower concurrency
251
+ const heavyTypes = [
252
+ 'neural',
253
+ 'github',
254
+ 'workflow'
255
+ ];
256
+ const hasHeavyOps = toolTypes.some((type)=>heavyTypes.includes(type));
257
+ if (hasHeavyOps) {
258
+ return Math.min(3, Math.max(1, Math.floor(toolCalls.length / 2)));
259
+ }
260
+ // Light operations (memory, performance) can handle higher concurrency
261
+ return Math.min(8, Math.max(2, Math.floor(toolCalls.length / 1.5)));
316
262
  }
317
-
318
- // Light operations (memory, performance) can handle higher concurrency
319
- return Math.min(8, Math.max(2, Math.floor(toolCalls.length / 1.5)));
320
- }
321
-
322
- /**
263
+ /**
323
264
  * Group tools by execution priority
324
- */
325
- _groupToolsByPriority(toolCalls) {
326
- const priorities = {
327
- critical: [], // swarm_init, swarm_destroy
328
- high: [], // agent_spawn, memory operations
329
- medium: [], // task operations, monitoring
330
- low: [], // analytics, reporting
331
- };
332
-
333
- toolCalls.forEach((call) => {
334
- const category = this._getToolCategory(call.tool);
335
- const tool = call.tool;
336
-
337
- if (['swarm_init', 'swarm_destroy', 'memory_backup'].includes(tool)) {
338
- priorities.critical.push(call);
339
- } else if (['agent_spawn', 'memory_usage', 'neural_train'].includes(tool)) {
340
- priorities.high.push(call);
341
- } else if (category === 'performance' || tool.includes('report')) {
342
- priorities.low.push(call);
343
- } else {
344
- priorities.medium.push(call);
345
- }
346
- });
347
-
348
- // Return groups in priority order, filtering empty groups
349
- return [priorities.critical, priorities.high, priorities.medium, priorities.low].filter(
350
- (group) => group.length > 0,
351
- );
352
- }
353
-
354
- /**
265
+ */ _groupToolsByPriority(toolCalls) {
266
+ const priorities = {
267
+ critical: [],
268
+ high: [],
269
+ medium: [],
270
+ low: []
271
+ };
272
+ toolCalls.forEach((call)=>{
273
+ const category = this._getToolCategory(call.tool);
274
+ const tool = call.tool;
275
+ if ([
276
+ 'swarm_init',
277
+ 'swarm_destroy',
278
+ 'memory_backup'
279
+ ].includes(tool)) {
280
+ priorities.critical.push(call);
281
+ } else if ([
282
+ 'agent_spawn',
283
+ 'memory_usage',
284
+ 'neural_train'
285
+ ].includes(tool)) {
286
+ priorities.high.push(call);
287
+ } else if (category === 'performance' || tool.includes('report')) {
288
+ priorities.low.push(call);
289
+ } else {
290
+ priorities.medium.push(call);
291
+ }
292
+ });
293
+ // Return groups in priority order, filtering empty groups
294
+ return [
295
+ priorities.critical,
296
+ priorities.high,
297
+ priorities.medium,
298
+ priorities.low
299
+ ].filter((group)=>group.length > 0);
300
+ }
301
+ /**
355
302
  * Execute tool with timeout wrapper
356
- */
357
- async _executeWithTimeout(call, timeout) {
358
- return new Promise((resolve, reject) => {
359
- const timer = setTimeout(() => {
360
- reject(new Error(`Tool ${call.tool} timed out after ${timeout}ms`));
361
- }, timeout);
362
-
363
- this.executeTool(call.tool, call.params)
364
- .then((result) => {
365
- clearTimeout(timer);
366
- resolve(result);
367
- })
368
- .catch((error) => {
369
- clearTimeout(timer);
370
- reject(error);
303
+ */ async _executeWithTimeout(call, timeout) {
304
+ return new Promise((resolve, reject)=>{
305
+ const timer = setTimeout(()=>{
306
+ reject(new Error(`Tool ${call.tool} timed out after ${timeout}ms`));
307
+ }, timeout);
308
+ this.executeTool(call.tool, call.params).then((result)=>{
309
+ clearTimeout(timer);
310
+ resolve(result);
311
+ }).catch((error)=>{
312
+ clearTimeout(timer);
313
+ reject(error);
314
+ });
371
315
  });
372
- });
373
- }
374
-
375
- /**
316
+ }
317
+ /**
376
318
  * Track batch execution performance
377
- */
378
- _trackBatchPerformance(toolCount, executionTime, concurrency) {
379
- if (!this.batchStats) {
380
- this.batchStats = {
381
- totalBatches: 0,
382
- totalTools: 0,
383
- totalTime: 0,
384
- avgConcurrency: 0,
385
- avgToolsPerBatch: 0,
386
- avgTimePerTool: 0,
387
- };
319
+ */ _trackBatchPerformance(toolCount, executionTime, concurrency) {
320
+ if (!this.batchStats) {
321
+ this.batchStats = {
322
+ totalBatches: 0,
323
+ totalTools: 0,
324
+ totalTime: 0,
325
+ avgConcurrency: 0,
326
+ avgToolsPerBatch: 0,
327
+ avgTimePerTool: 0
328
+ };
329
+ }
330
+ this.batchStats.totalBatches++;
331
+ this.batchStats.totalTools += toolCount;
332
+ this.batchStats.totalTime += executionTime;
333
+ this.batchStats.avgConcurrency = (this.batchStats.avgConcurrency * (this.batchStats.totalBatches - 1) + concurrency) / this.batchStats.totalBatches;
334
+ this.batchStats.avgToolsPerBatch = this.batchStats.totalTools / this.batchStats.totalBatches;
335
+ this.batchStats.avgTimePerTool = this.batchStats.totalTime / this.batchStats.totalTools;
388
336
  }
389
-
390
- this.batchStats.totalBatches++;
391
- this.batchStats.totalTools += toolCount;
392
- this.batchStats.totalTime += executionTime;
393
- this.batchStats.avgConcurrency =
394
- (this.batchStats.avgConcurrency * (this.batchStats.totalBatches - 1) + concurrency) /
395
- this.batchStats.totalBatches;
396
- this.batchStats.avgToolsPerBatch = this.batchStats.totalTools / this.batchStats.totalBatches;
397
- this.batchStats.avgTimePerTool = this.batchStats.totalTime / this.batchStats.totalTools;
398
- }
399
-
400
- /**
337
+ /**
401
338
  * Internal tool execution
402
- */
403
- async _executeToolInternal(toolName, params) {
404
- const toolCategory = this._getToolCategory(toolName);
405
- if (!toolCategory) {
406
- throw new Error(`Unknown MCP tool: ${toolName}`);
407
- }
408
-
409
- // Handle memory operations with real storage
410
- if (toolName === 'memory_usage') {
411
- if (params.action === 'store') {
412
- return await this.storeMemory(params.namespace, params.key, params.value, params.type);
413
- } else if (params.action === 'retrieve') {
414
- return await this.retrieveMemory(params.namespace, params.key);
415
- }
416
- } else if (toolName === 'memory_search') {
417
- return await this.searchMemory(params.namespace, params.pattern);
418
- } else if (toolName === 'swarm_status') {
419
- return await this.getSwarmStatus(params);
339
+ */ async _executeToolInternal(toolName, params) {
340
+ const toolCategory = this._getToolCategory(toolName);
341
+ if (!toolCategory) {
342
+ throw new Error(`Unknown MCP tool: ${toolName}`);
343
+ }
344
+ // Handle memory operations with real storage
345
+ if (toolName === 'memory_usage') {
346
+ if (params.action === 'store') {
347
+ return await this.storeMemory(params.namespace, params.key, params.value, params.type);
348
+ } else if (params.action === 'retrieve') {
349
+ return await this.retrieveMemory(params.namespace, params.key);
350
+ }
351
+ } else if (toolName === 'memory_search') {
352
+ return await this.searchMemory(params.namespace, params.pattern);
353
+ } else if (toolName === 'swarm_status') {
354
+ return await this.getSwarmStatus(params);
355
+ }
356
+ // For other tools, use mock responses
357
+ console.log(`Executing MCP tool: mcp__claude-flow__${toolName} with params:`, params);
358
+ // Simulate async execution for non-memory tools
359
+ await new Promise((resolve)=>setTimeout(resolve, Math.random() * 500));
360
+ // Mock response based on tool type
361
+ const mockResponse = this._getMockResponse(toolName, params);
362
+ return mockResponse;
420
363
  }
421
-
422
- // For other tools, use mock responses
423
- console.log(`Executing MCP tool: mcp__claude-flow__${toolName} with params:`, params);
424
-
425
- // Simulate async execution for non-memory tools
426
- await new Promise((resolve) => setTimeout(resolve, Math.random() * 500));
427
-
428
- // Mock response based on tool type
429
- const mockResponse = this._getMockResponse(toolName, params);
430
- return mockResponse;
431
- }
432
-
433
- /**
364
+ /**
434
365
  * Get tool category
435
- */
436
- _getToolCategory(toolName) {
437
- for (const [category, tools] of Object.entries(MCP_TOOLS)) {
438
- if (tools.includes(toolName)) {
439
- return category;
440
- }
366
+ */ _getToolCategory(toolName) {
367
+ for (const [category, tools] of Object.entries(MCP_TOOLS)){
368
+ if (tools.includes(toolName)) {
369
+ return category;
370
+ }
371
+ }
372
+ return null;
441
373
  }
442
- return null;
443
- }
444
-
445
- /**
374
+ /**
446
375
  * Get mock response for demonstration
447
- */
448
- _getMockResponse(toolName, params) {
449
- // Mock responses for different tool types
450
- const mockResponses = {
451
- swarm_init: {
452
- swarmId: `swarm-${Date.now()}`,
453
- topology: params.topology || 'hierarchical',
454
- status: 'initialized',
455
- },
456
- agent_spawn: {
457
- agentId: `agent-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
458
- type: params.type,
459
- status: 'active',
460
- },
461
- task_orchestrate: {
462
- taskId: `task-${Date.now()}`,
463
- status: 'orchestrated',
464
- strategy: params.strategy || 'parallel',
465
- },
466
- memory_usage: {
467
- action: params.action,
468
- result: params.action === 'store' ? 'stored' : 'retrieved',
469
- data: params.value || null,
470
- },
471
- neural_status: {
472
- status: 'ready',
473
- models: 27,
474
- accuracy: 0.848,
475
- },
476
- };
477
-
478
- return mockResponses[toolName] || { status: 'success', toolName };
479
- }
480
-
481
- /**
482
- * Track tool usage statistics
483
- */
484
- _trackToolUsage(toolName, duration, success) {
485
- if (!this.toolStats.has(toolName)) {
486
- this.toolStats.set(toolName, {
487
- calls: 0,
488
- successes: 0,
489
- failures: 0,
490
- totalDuration: 0,
491
- avgDuration: 0,
492
- });
376
+ */ _getMockResponse(toolName, params) {
377
+ // Mock responses for different tool types
378
+ const mockResponses = {
379
+ swarm_init: {
380
+ swarmId: `swarm-${Date.now()}`,
381
+ topology: params.topology || 'hierarchical',
382
+ status: 'initialized'
383
+ },
384
+ agent_spawn: {
385
+ agentId: `agent-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
386
+ type: params.type,
387
+ status: 'active'
388
+ },
389
+ task_orchestrate: {
390
+ taskId: `task-${Date.now()}`,
391
+ status: 'orchestrated',
392
+ strategy: params.strategy || 'parallel'
393
+ },
394
+ memory_usage: {
395
+ action: params.action,
396
+ result: params.action === 'store' ? 'stored' : 'retrieved',
397
+ data: params.value || null
398
+ },
399
+ neural_status: {
400
+ status: 'ready',
401
+ models: 27,
402
+ accuracy: 0.848
403
+ }
404
+ };
405
+ return mockResponses[toolName] || {
406
+ status: 'success',
407
+ toolName
408
+ };
493
409
  }
494
-
495
- const stats = this.toolStats.get(toolName);
496
- stats.calls++;
497
- if (success) {
498
- stats.successes++;
499
- } else {
500
- stats.failures++;
410
+ /**
411
+ * Track tool usage statistics
412
+ */ _trackToolUsage(toolName, duration, success) {
413
+ if (!this.toolStats.has(toolName)) {
414
+ this.toolStats.set(toolName, {
415
+ calls: 0,
416
+ successes: 0,
417
+ failures: 0,
418
+ totalDuration: 0,
419
+ avgDuration: 0
420
+ });
421
+ }
422
+ const stats = this.toolStats.get(toolName);
423
+ stats.calls++;
424
+ if (success) {
425
+ stats.successes++;
426
+ } else {
427
+ stats.failures++;
428
+ }
429
+ stats.totalDuration += duration;
430
+ stats.avgDuration = stats.totalDuration / stats.calls;
501
431
  }
502
- stats.totalDuration += duration;
503
- stats.avgDuration = stats.totalDuration / stats.calls;
504
- }
505
-
506
- /**
432
+ /**
507
433
  * Get comprehensive tool statistics
508
- */
509
- getStatistics() {
510
- const toolStats = {};
511
- this.toolStats.forEach((value, key) => {
512
- toolStats[key] = { ...value };
513
- });
514
-
515
- return {
516
- tools: toolStats,
517
- batch: this.batchStats || {
518
- totalBatches: 0,
519
- totalTools: 0,
520
- totalTime: 0,
521
- avgConcurrency: 0,
522
- avgToolsPerBatch: 0,
523
- avgTimePerTool: 0,
524
- },
525
- spawn: this.spawnStats || {
526
- totalSpawns: 0,
527
- totalAgents: 0,
528
- totalTime: 0,
529
- avgTimePerAgent: 0,
530
- bestTime: 0,
531
- worstTime: 0,
532
- },
533
- performance: {
534
- totalCalls: Array.from(this.toolStats.values()).reduce((sum, stat) => sum + stat.calls, 0),
535
- successRate: this._calculateOverallSuccessRate(),
536
- avgLatency: this._calculateAvgLatency(),
537
- throughput: this._calculateThroughput(),
538
- },
539
- };
540
- }
541
-
542
- /**
434
+ */ getStatistics() {
435
+ const toolStats = {};
436
+ this.toolStats.forEach((value, key)=>{
437
+ toolStats[key] = {
438
+ ...value
439
+ };
440
+ });
441
+ return {
442
+ tools: toolStats,
443
+ batch: this.batchStats || {
444
+ totalBatches: 0,
445
+ totalTools: 0,
446
+ totalTime: 0,
447
+ avgConcurrency: 0,
448
+ avgToolsPerBatch: 0,
449
+ avgTimePerTool: 0
450
+ },
451
+ spawn: this.spawnStats || {
452
+ totalSpawns: 0,
453
+ totalAgents: 0,
454
+ totalTime: 0,
455
+ avgTimePerAgent: 0,
456
+ bestTime: 0,
457
+ worstTime: 0
458
+ },
459
+ performance: {
460
+ totalCalls: Array.from(this.toolStats.values()).reduce((sum, stat)=>sum + stat.calls, 0),
461
+ successRate: this._calculateOverallSuccessRate(),
462
+ avgLatency: this._calculateAvgLatency(),
463
+ throughput: this._calculateThroughput()
464
+ }
465
+ };
466
+ }
467
+ /**
543
468
  * Calculate overall success rate
544
- */
545
- _calculateOverallSuccessRate() {
546
- const total = Array.from(this.toolStats.values()).reduce((sum, stat) => sum + stat.calls, 0);
547
- const successes = Array.from(this.toolStats.values()).reduce(
548
- (sum, stat) => sum + stat.successes,
549
- 0,
550
- );
551
-
552
- return total > 0 ? ((successes / total) * 100).toFixed(2) : 100;
553
- }
554
-
555
- /**
469
+ */ _calculateOverallSuccessRate() {
470
+ const total = Array.from(this.toolStats.values()).reduce((sum, stat)=>sum + stat.calls, 0);
471
+ const successes = Array.from(this.toolStats.values()).reduce((sum, stat)=>sum + stat.successes, 0);
472
+ return total > 0 ? (successes / total * 100).toFixed(2) : 100;
473
+ }
474
+ /**
556
475
  * Calculate average latency
557
- */
558
- _calculateAvgLatency() {
559
- const stats = Array.from(this.toolStats.values()).filter((stat) => stat.calls > 0);
560
- if (stats.length === 0) return 0;
561
-
562
- const totalLatency = stats.reduce((sum, stat) => sum + stat.avgDuration, 0);
563
- return (totalLatency / stats.length).toFixed(2);
564
- }
565
-
566
- /**
476
+ */ _calculateAvgLatency() {
477
+ const stats = Array.from(this.toolStats.values()).filter((stat)=>stat.calls > 0);
478
+ if (stats.length === 0) return 0;
479
+ const totalLatency = stats.reduce((sum, stat)=>sum + stat.avgDuration, 0);
480
+ return (totalLatency / stats.length).toFixed(2);
481
+ }
482
+ /**
567
483
  * Calculate throughput (operations per second)
568
- */
569
- _calculateThroughput() {
570
- const batchStats = this.batchStats;
571
- if (!batchStats || batchStats.totalTime === 0) return 0;
572
-
573
- return (batchStats.totalTools / (batchStats.totalTime / 1000)).toFixed(2);
574
- }
575
-
576
- /**
484
+ */ _calculateThroughput() {
485
+ const batchStats = this.batchStats;
486
+ if (!batchStats || batchStats.totalTime === 0) return 0;
487
+ return (batchStats.totalTools / (batchStats.totalTime / 1000)).toFixed(2);
488
+ }
489
+ /**
577
490
  * Create batch of tool calls for parallel execution
578
- */
579
- createBatch(calls) {
580
- return calls.map((call) => ({
581
- tool: call.tool,
582
- params: call.params || {},
583
- }));
584
- }
585
-
586
- /**
491
+ */ createBatch(calls) {
492
+ return calls.map((call)=>({
493
+ tool: call.tool,
494
+ params: call.params || {}
495
+ }));
496
+ }
497
+ /**
587
498
  * Execute swarm initialization sequence with optimization
588
- */
589
- async initializeSwarm(config) {
590
- const swarmId = config.swarmId || `swarm-${Date.now()}`;
591
- const startTime = Date.now();
592
-
593
- try {
594
- // Phase 1: Critical initialization (sequential)
595
- const criticalOps = [
596
- {
597
- tool: 'swarm_init',
598
- params: {
599
- topology: config.topology || 'hierarchical',
600
- maxAgents: config.maxAgents || 8,
601
- strategy: 'auto',
602
- swarmId,
603
- },
604
- },
605
- ];
606
-
607
- const [swarmInitResult] = await this.executeParallel(criticalOps);
608
-
609
- // Phase 2: Supporting services (parallel)
610
- const supportingOps = [
611
- {
612
- tool: 'memory_namespace',
613
- params: {
614
- action: 'create',
615
- namespace: swarmId,
616
- maxSize: config.memorySize || 100,
617
- },
618
- },
619
- { tool: 'neural_status', params: {} },
620
- { tool: 'performance_report', params: { format: 'summary' } },
621
- { tool: 'features_detect', params: { component: 'swarm' } },
622
- ];
623
-
624
- const supportingResults = await this.executeParallel(supportingOps);
625
-
626
- // Store initialization metadata
627
- const initTime = Date.now() - startTime;
628
- await this.storeMemory(
629
- swarmId,
630
- 'init_performance',
631
- {
632
- initTime,
633
- topology: config.topology || 'hierarchical',
634
- maxAgents: config.maxAgents || 8,
635
- timestamp: Date.now(),
636
- },
637
- 'metrics',
638
- );
639
-
640
- // Store swarm status
641
- await this.storeMemory(swarmId, 'status', 'active', 'status');
642
-
643
- // Store swarm config
644
- await this.storeMemory(
645
- swarmId,
646
- 'config',
647
- {
648
- topology: config.topology || 'hierarchical',
649
- maxAgents: config.maxAgents || 8,
650
- strategy: config.strategy || 'auto',
651
- createdAt: Date.now(),
652
- },
653
- 'config',
654
- );
655
-
656
- return [swarmInitResult, ...supportingResults];
657
- } catch (error) {
658
- console.error('Swarm initialization failed:', error);
659
- throw error;
499
+ */ async initializeSwarm(config) {
500
+ const swarmId = config.swarmId || `swarm-${Date.now()}`;
501
+ const startTime = Date.now();
502
+ try {
503
+ // Phase 1: Critical initialization (sequential)
504
+ const criticalOps = [
505
+ {
506
+ tool: 'swarm_init',
507
+ params: {
508
+ topology: config.topology || 'hierarchical',
509
+ maxAgents: config.maxAgents || 8,
510
+ strategy: 'auto',
511
+ swarmId
512
+ }
513
+ }
514
+ ];
515
+ const [swarmInitResult] = await this.executeParallel(criticalOps);
516
+ // Phase 2: Supporting services (parallel)
517
+ const supportingOps = [
518
+ {
519
+ tool: 'memory_namespace',
520
+ params: {
521
+ action: 'create',
522
+ namespace: swarmId,
523
+ maxSize: config.memorySize || 100
524
+ }
525
+ },
526
+ {
527
+ tool: 'neural_status',
528
+ params: {}
529
+ },
530
+ {
531
+ tool: 'performance_report',
532
+ params: {
533
+ format: 'summary'
534
+ }
535
+ },
536
+ {
537
+ tool: 'features_detect',
538
+ params: {
539
+ component: 'swarm'
540
+ }
541
+ }
542
+ ];
543
+ const supportingResults = await this.executeParallel(supportingOps);
544
+ // Store initialization metadata
545
+ const initTime = Date.now() - startTime;
546
+ await this.storeMemory(swarmId, 'init_performance', {
547
+ initTime,
548
+ topology: config.topology || 'hierarchical',
549
+ maxAgents: config.maxAgents || 8,
550
+ timestamp: Date.now()
551
+ }, 'metrics');
552
+ // Store swarm status
553
+ await this.storeMemory(swarmId, 'status', 'active', 'status');
554
+ // Store swarm config
555
+ await this.storeMemory(swarmId, 'config', {
556
+ topology: config.topology || 'hierarchical',
557
+ maxAgents: config.maxAgents || 8,
558
+ strategy: config.strategy || 'auto',
559
+ createdAt: Date.now()
560
+ }, 'config');
561
+ return [
562
+ swarmInitResult,
563
+ ...supportingResults
564
+ ];
565
+ } catch (error) {
566
+ console.error('Swarm initialization failed:', error);
567
+ throw error;
568
+ }
660
569
  }
661
- }
662
-
663
- /**
570
+ /**
664
571
  * Spawn multiple agents in parallel with optimization
665
- */
666
- async spawnAgents(types, swarmId) {
667
- if (!Array.isArray(types) || types.length === 0) {
668
- return [];
669
- }
670
-
671
- const startTime = Date.now();
672
-
673
- // Optimize agent spawning by grouping similar types
674
- const groupedTypes = this._groupAgentTypes(types);
675
- const allResults = [];
676
-
677
- try {
678
- // Spawn each group in parallel
679
- for (const group of groupedTypes) {
680
- const batch = group.map((type) => ({
681
- tool: 'agent_spawn',
682
- params: {
683
- type,
684
- swarmId,
685
- timestamp: Date.now(),
686
- batchId: `batch-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
687
- },
688
- }));
689
-
690
- const groupResults = await this.executeParallel(batch);
691
- allResults.push(...groupResults);
692
-
693
- // Store agent information in memory
694
- for (const result of groupResults) {
695
- if (result && result.agentId && !result.error) {
696
- await this.storeMemory(
697
- swarmId,
698
- `agent-${result.agentId}`,
699
- {
700
- id: result.agentId,
701
- type: result.type,
702
- status: result.status || 'active',
703
- createdAt: Date.now(),
704
- },
705
- 'agent',
706
- );
707
- }
572
+ */ async spawnAgents(types, swarmId) {
573
+ if (!Array.isArray(types) || types.length === 0) {
574
+ return [];
575
+ }
576
+ const startTime = Date.now();
577
+ // Optimize agent spawning by grouping similar types
578
+ const groupedTypes = this._groupAgentTypes(types);
579
+ const allResults = [];
580
+ try {
581
+ // Spawn each group in parallel
582
+ for (const group of groupedTypes){
583
+ const batch = group.map((type)=>({
584
+ tool: 'agent_spawn',
585
+ params: {
586
+ type,
587
+ swarmId,
588
+ timestamp: Date.now(),
589
+ batchId: `batch-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
590
+ }
591
+ }));
592
+ const groupResults = await this.executeParallel(batch);
593
+ allResults.push(...groupResults);
594
+ // Store agent information in memory
595
+ for (const result of groupResults){
596
+ if (result && result.agentId && !result.error) {
597
+ await this.storeMemory(swarmId, `agent-${result.agentId}`, {
598
+ id: result.agentId,
599
+ type: result.type,
600
+ status: result.status || 'active',
601
+ createdAt: Date.now()
602
+ }, 'agent');
603
+ }
604
+ }
605
+ }
606
+ // Track spawn performance
607
+ const spawnTime = Date.now() - startTime;
608
+ this._trackSpawnPerformance(types.length, spawnTime);
609
+ return allResults;
610
+ } catch (error) {
611
+ console.error('Agent spawning failed:', error);
612
+ throw error;
708
613
  }
709
- }
710
-
711
- // Track spawn performance
712
- const spawnTime = Date.now() - startTime;
713
- this._trackSpawnPerformance(types.length, spawnTime);
714
-
715
- return allResults;
716
- } catch (error) {
717
- console.error('Agent spawning failed:', error);
718
- throw error;
719
614
  }
720
- }
721
-
722
- /**
615
+ /**
723
616
  * Group agent types for optimized spawning
724
- */
725
- _groupAgentTypes(types) {
726
- // Group complementary agent types that work well together
727
- const groups = {
728
- development: ['coder', 'architect', 'reviewer'],
729
- analysis: ['researcher', 'analyst', 'optimizer'],
730
- quality: ['tester', 'documenter'],
731
- coordination: ['coordinator'],
732
- };
733
-
734
- const result = [];
735
- const remaining = [...types];
736
-
737
- // Create groups of complementary agents
738
- Object.values(groups).forEach((groupTypes) => {
739
- const groupAgents = remaining.filter((type) => groupTypes.includes(type));
740
- if (groupAgents.length > 0) {
741
- result.push(groupAgents);
742
- groupAgents.forEach((type) => {
743
- const index = remaining.indexOf(type);
744
- if (index > -1) remaining.splice(index, 1);
617
+ */ _groupAgentTypes(types) {
618
+ // Group complementary agent types that work well together
619
+ const groups = {
620
+ development: [
621
+ 'coder',
622
+ 'architect',
623
+ 'reviewer'
624
+ ],
625
+ analysis: [
626
+ 'researcher',
627
+ 'analyst',
628
+ 'optimizer'
629
+ ],
630
+ quality: [
631
+ 'tester',
632
+ 'documenter'
633
+ ],
634
+ coordination: [
635
+ 'coordinator'
636
+ ]
637
+ };
638
+ const result = [];
639
+ const remaining = [
640
+ ...types
641
+ ];
642
+ // Create groups of complementary agents
643
+ Object.values(groups).forEach((groupTypes)=>{
644
+ const groupAgents = remaining.filter((type)=>groupTypes.includes(type));
645
+ if (groupAgents.length > 0) {
646
+ result.push(groupAgents);
647
+ groupAgents.forEach((type)=>{
648
+ const index = remaining.indexOf(type);
649
+ if (index > -1) remaining.splice(index, 1);
650
+ });
651
+ }
745
652
  });
746
- }
747
- });
748
-
749
- // Add remaining agents as individual groups
750
- remaining.forEach((type) => result.push([type]));
751
-
752
- return result;
753
- }
754
-
755
- /**
653
+ // Add remaining agents as individual groups
654
+ remaining.forEach((type)=>result.push([
655
+ type
656
+ ]));
657
+ return result;
658
+ }
659
+ /**
756
660
  * Track agent spawn performance
757
- */
758
- _trackSpawnPerformance(agentCount, spawnTime) {
759
- if (!this.spawnStats) {
760
- this.spawnStats = {
761
- totalSpawns: 0,
762
- totalAgents: 0,
763
- totalTime: 0,
764
- avgTimePerAgent: 0,
765
- bestTime: Infinity,
766
- worstTime: 0,
767
- };
661
+ */ _trackSpawnPerformance(agentCount, spawnTime) {
662
+ if (!this.spawnStats) {
663
+ this.spawnStats = {
664
+ totalSpawns: 0,
665
+ totalAgents: 0,
666
+ totalTime: 0,
667
+ avgTimePerAgent: 0,
668
+ bestTime: Infinity,
669
+ worstTime: 0
670
+ };
671
+ }
672
+ this.spawnStats.totalSpawns++;
673
+ this.spawnStats.totalAgents += agentCount;
674
+ this.spawnStats.totalTime += spawnTime;
675
+ this.spawnStats.avgTimePerAgent = this.spawnStats.totalTime / this.spawnStats.totalAgents;
676
+ this.spawnStats.bestTime = Math.min(this.spawnStats.bestTime, spawnTime);
677
+ this.spawnStats.worstTime = Math.max(this.spawnStats.worstTime, spawnTime);
768
678
  }
769
-
770
- this.spawnStats.totalSpawns++;
771
- this.spawnStats.totalAgents += agentCount;
772
- this.spawnStats.totalTime += spawnTime;
773
- this.spawnStats.avgTimePerAgent = this.spawnStats.totalTime / this.spawnStats.totalAgents;
774
- this.spawnStats.bestTime = Math.min(this.spawnStats.bestTime, spawnTime);
775
- this.spawnStats.worstTime = Math.max(this.spawnStats.worstTime, spawnTime);
776
- }
777
-
778
- /**
679
+ /**
779
680
  * Store data in collective memory (REAL IMPLEMENTATION)
780
- */
781
- async storeMemory(swarmId, key, value, type = 'knowledge') {
782
- try {
783
- // Don't reinitialize if we already have storage
784
- if (!this.memoryDb && !this.memoryStore) {
785
- await this.initializeMemoryStorage();
786
- }
787
-
788
- const timestamp = Date.now();
789
- const valueStr = typeof value === 'string' ? value : JSON.stringify(value);
790
-
791
- if (this.memoryDb) {
792
- // SQLite storage
793
- const stmt = this.memoryDb.prepare(`
681
+ */ async storeMemory(swarmId, key, value, type = 'knowledge') {
682
+ try {
683
+ // Don't reinitialize if we already have storage
684
+ if (!this.memoryDb && !this.memoryStore) {
685
+ await this.initializeMemoryStorage();
686
+ }
687
+ const timestamp = Date.now();
688
+ const valueStr = typeof value === 'string' ? value : JSON.stringify(value);
689
+ if (this.memoryDb) {
690
+ // SQLite storage
691
+ const stmt = this.memoryDb.prepare(`
794
692
  INSERT OR REPLACE INTO memories (namespace, key, value, type, timestamp)
795
693
  VALUES (?, ?, ?, ?, ?)
796
694
  `);
797
-
798
- const result = stmt.run(swarmId, key, valueStr, type, timestamp);
799
-
800
- return {
801
- success: true,
802
- action: 'store',
803
- namespace: swarmId,
804
- key,
805
- type,
806
- timestamp,
807
- id: result.lastInsertRowid,
808
- };
809
- } else {
810
- // Fallback in-memory storage
811
- const memoryKey = `${swarmId}:${key}`;
812
- this.memoryStore.set(memoryKey, {
813
- namespace: swarmId,
814
- key,
815
- value: valueStr,
816
- type,
817
- timestamp,
818
- });
819
-
820
- return {
821
- success: true,
822
- action: 'store',
823
- namespace: swarmId,
824
- key,
825
- type,
826
- timestamp,
827
- };
828
- }
829
- } catch (error) {
830
- console.error('Error storing memory:', error);
831
- throw error;
695
+ const result = stmt.run(swarmId, key, valueStr, type, timestamp);
696
+ return {
697
+ success: true,
698
+ action: 'store',
699
+ namespace: swarmId,
700
+ key,
701
+ type,
702
+ timestamp,
703
+ id: result.lastInsertRowid
704
+ };
705
+ } else {
706
+ // Fallback in-memory storage
707
+ const memoryKey = `${swarmId}:${key}`;
708
+ this.memoryStore.set(memoryKey, {
709
+ namespace: swarmId,
710
+ key,
711
+ value: valueStr,
712
+ type,
713
+ timestamp
714
+ });
715
+ return {
716
+ success: true,
717
+ action: 'store',
718
+ namespace: swarmId,
719
+ key,
720
+ type,
721
+ timestamp
722
+ };
723
+ }
724
+ } catch (error) {
725
+ console.error('Error storing memory:', error);
726
+ throw error;
727
+ }
832
728
  }
833
- }
834
-
835
- /**
729
+ /**
836
730
  * Retrieve data from collective memory (REAL IMPLEMENTATION)
837
- */
838
- async retrieveMemory(swarmId, key) {
839
- try {
840
- // Don't reinitialize if we already have storage
841
- if (!this.memoryDb && !this.memoryStore) {
842
- await this.initializeMemoryStorage();
843
- }
844
-
845
- if (this.memoryDb) {
846
- // SQLite retrieval
847
- const stmt = this.memoryDb.prepare(`
731
+ */ async retrieveMemory(swarmId, key) {
732
+ try {
733
+ // Don't reinitialize if we already have storage
734
+ if (!this.memoryDb && !this.memoryStore) {
735
+ await this.initializeMemoryStorage();
736
+ }
737
+ if (this.memoryDb) {
738
+ // SQLite retrieval
739
+ const stmt = this.memoryDb.prepare(`
848
740
  SELECT * FROM memories WHERE namespace = ? AND key = ?
849
741
  `);
850
-
851
- const row = stmt.get(swarmId, key);
852
- if (row) {
853
- try {
854
- return {
855
- ...row,
856
- value: JSON.parse(row.value),
857
- };
858
- } catch {
859
- return row;
860
- }
861
- }
862
- } else {
863
- // Fallback in-memory retrieval
864
- const memoryKey = `${swarmId}:${key}`;
865
- const memory = this.memoryStore.get(memoryKey);
866
- if (memory) {
867
- try {
868
- return {
869
- ...memory,
870
- value: JSON.parse(memory.value),
871
- };
872
- } catch {
873
- return memory;
874
- }
742
+ const row = stmt.get(swarmId, key);
743
+ if (row) {
744
+ try {
745
+ return {
746
+ ...row,
747
+ value: JSON.parse(row.value)
748
+ };
749
+ } catch {
750
+ return row;
751
+ }
752
+ }
753
+ } else {
754
+ // Fallback in-memory retrieval
755
+ const memoryKey = `${swarmId}:${key}`;
756
+ const memory = this.memoryStore.get(memoryKey);
757
+ if (memory) {
758
+ try {
759
+ return {
760
+ ...memory,
761
+ value: JSON.parse(memory.value)
762
+ };
763
+ } catch {
764
+ return memory;
765
+ }
766
+ }
767
+ }
768
+ return null;
769
+ } catch (error) {
770
+ console.error('Error retrieving memory:', error);
771
+ throw error;
875
772
  }
876
- }
877
-
878
- return null;
879
- } catch (error) {
880
- console.error('Error retrieving memory:', error);
881
- throw error;
882
773
  }
883
- }
884
-
885
- /**
774
+ /**
886
775
  * Search collective memory (REAL IMPLEMENTATION)
887
- */
888
- async searchMemory(swarmId, pattern) {
889
- try {
890
- // Don't reinitialize if we already have storage
891
- if (!this.memoryDb && !this.memoryStore) {
892
- await this.initializeMemoryStorage();
893
- }
894
-
895
- let results = [];
896
-
897
- if (this.memoryDb) {
898
- // SQLite search
899
- let query, params;
900
-
901
- if (pattern && pattern.trim()) {
902
- // Search with pattern
903
- query = `
776
+ */ async searchMemory(swarmId, pattern) {
777
+ try {
778
+ // Don't reinitialize if we already have storage
779
+ if (!this.memoryDb && !this.memoryStore) {
780
+ await this.initializeMemoryStorage();
781
+ }
782
+ let results = [];
783
+ if (this.memoryDb) {
784
+ // SQLite search
785
+ let query, params;
786
+ if (pattern && pattern.trim()) {
787
+ // Search with pattern
788
+ query = `
904
789
  SELECT * FROM memories
905
790
  WHERE namespace = ? AND (key LIKE ? OR value LIKE ? OR type LIKE ?)
906
791
  ORDER BY timestamp DESC
907
792
  LIMIT 50
908
793
  `;
909
- const searchPattern = `%${pattern}%`;
910
- params = [swarmId, searchPattern, searchPattern, searchPattern];
911
- } else {
912
- // Get all memories for namespace
913
- query = `
794
+ const searchPattern = `%${pattern}%`;
795
+ params = [
796
+ swarmId,
797
+ searchPattern,
798
+ searchPattern,
799
+ searchPattern
800
+ ];
801
+ } else {
802
+ // Get all memories for namespace
803
+ query = `
914
804
  SELECT * FROM memories
915
805
  WHERE namespace = ?
916
806
  ORDER BY timestamp DESC
917
807
  LIMIT 50
918
808
  `;
919
- params = [swarmId];
920
- }
921
-
922
- const stmt = this.memoryDb.prepare(query);
923
- results = stmt.all(...params);
924
-
925
- // Parse JSON values where possible
926
- results = results.map((row) => {
927
- try {
928
- return {
929
- ...row,
930
- value: JSON.parse(row.value),
931
- };
932
- } catch {
933
- return row;
934
- }
935
- });
936
- } else {
937
- // Fallback in-memory search
938
- for (const [memKey, memory] of this.memoryStore) {
939
- if (memory.namespace === swarmId) {
940
- if (
941
- !pattern ||
942
- memory.key.includes(pattern) ||
943
- memory.value.includes(pattern) ||
944
- memory.type.includes(pattern)
945
- ) {
946
- try {
947
- results.push({
948
- ...memory,
949
- value: JSON.parse(memory.value),
809
+ params = [
810
+ swarmId
811
+ ];
812
+ }
813
+ const stmt = this.memoryDb.prepare(query);
814
+ results = stmt.all(...params);
815
+ // Parse JSON values where possible
816
+ results = results.map((row)=>{
817
+ try {
818
+ return {
819
+ ...row,
820
+ value: JSON.parse(row.value)
821
+ };
822
+ } catch {
823
+ return row;
824
+ }
950
825
  });
951
- } catch {
952
- results.push(memory);
953
- }
826
+ } else {
827
+ // Fallback in-memory search
828
+ for (const [memKey, memory] of this.memoryStore){
829
+ if (memory.namespace === swarmId) {
830
+ if (!pattern || memory.key.includes(pattern) || memory.value.includes(pattern) || memory.type.includes(pattern)) {
831
+ try {
832
+ results.push({
833
+ ...memory,
834
+ value: JSON.parse(memory.value)
835
+ });
836
+ } catch {
837
+ results.push(memory);
838
+ }
839
+ }
840
+ }
841
+ }
842
+ // Sort by timestamp descending
843
+ results.sort((a, b)=>b.timestamp - a.timestamp);
844
+ results = results.slice(0, 50);
954
845
  }
955
- }
846
+ return {
847
+ success: true,
848
+ namespace: swarmId,
849
+ pattern: pattern || '',
850
+ total: results.length,
851
+ results: results
852
+ };
853
+ } catch (error) {
854
+ console.error('Error searching memory:', error);
855
+ throw error;
956
856
  }
957
-
958
- // Sort by timestamp descending
959
- results.sort((a, b) => b.timestamp - a.timestamp);
960
- results = results.slice(0, 50);
961
- }
962
-
963
- return {
964
- success: true,
965
- namespace: swarmId,
966
- pattern: pattern || '',
967
- total: results.length,
968
- results: results,
969
- };
970
- } catch (error) {
971
- console.error('Error searching memory:', error);
972
- throw error;
973
857
  }
974
- }
975
-
976
- /**
858
+ /**
977
859
  * Orchestrate task with monitoring and optimization
978
- */
979
- async orchestrateTask(task, strategy = 'parallel', metadata = {}) {
980
- const taskId = metadata.taskId || `task-${Date.now()}`;
981
- const swarmId = metadata.swarmId || 'default-swarm';
982
- const complexity = metadata.complexity || 'medium';
983
-
984
- // Store task information
985
- await this.storeMemory(
986
- swarmId,
987
- `task-${taskId}`,
988
- {
989
- id: taskId,
990
- task,
991
- strategy,
992
- status: 'pending',
993
- priority: metadata.priority || 5,
994
- complexity,
995
- createdAt: Date.now(),
996
- },
997
- 'task',
998
- );
999
-
1000
- // Adjust monitoring frequency based on task complexity
1001
- const monitoringInterval =
1002
- {
1003
- low: 10000,
1004
- medium: 5000,
1005
- high: 2000,
1006
- }[complexity] || 5000;
1007
-
1008
- const batch = [
1009
- {
1010
- tool: 'task_orchestrate',
1011
- params: {
1012
- task,
1013
- strategy,
1014
- taskId,
1015
- priority: metadata.priority || 5,
1016
- estimatedDuration: metadata.estimatedDuration || 30000,
1017
- },
1018
- },
1019
- {
1020
- tool: 'swarm_monitor',
1021
- params: {
1022
- interval: monitoringInterval,
1023
- taskId,
1024
- metrics: ['performance', 'progress', 'bottlenecks'],
1025
- },
1026
- },
1027
- // Add performance tracking for high-priority tasks
1028
- ...(metadata.priority > 7
1029
- ? [
860
+ */ async orchestrateTask(task, strategy = 'parallel', metadata = {}) {
861
+ const taskId = metadata.taskId || `task-${Date.now()}`;
862
+ const swarmId = metadata.swarmId || 'default-swarm';
863
+ const complexity = metadata.complexity || 'medium';
864
+ // Store task information
865
+ await this.storeMemory(swarmId, `task-${taskId}`, {
866
+ id: taskId,
867
+ task,
868
+ strategy,
869
+ status: 'pending',
870
+ priority: metadata.priority || 5,
871
+ complexity,
872
+ createdAt: Date.now()
873
+ }, 'task');
874
+ // Adjust monitoring frequency based on task complexity
875
+ const monitoringInterval = {
876
+ low: 10000,
877
+ medium: 5000,
878
+ high: 2000
879
+ }[complexity] || 5000;
880
+ const batch = [
881
+ {
882
+ tool: 'task_orchestrate',
883
+ params: {
884
+ task,
885
+ strategy,
886
+ taskId,
887
+ priority: metadata.priority || 5,
888
+ estimatedDuration: metadata.estimatedDuration || 30000
889
+ }
890
+ },
1030
891
  {
1031
- tool: 'performance_report',
1032
- params: { format: 'detailed', taskId },
892
+ tool: 'swarm_monitor',
893
+ params: {
894
+ interval: monitoringInterval,
895
+ taskId,
896
+ metrics: [
897
+ 'performance',
898
+ 'progress',
899
+ 'bottlenecks'
900
+ ]
901
+ }
1033
902
  },
1034
- ]
1035
- : []),
1036
- ];
1037
-
1038
- const results = await this.executeParallel(batch);
1039
-
1040
- // Update task status
1041
- await this.storeMemory(
1042
- swarmId,
1043
- `task-${taskId}`,
1044
- {
1045
- id: taskId,
1046
- task,
1047
- strategy,
1048
- status: 'in_progress',
1049
- priority: metadata.priority || 5,
1050
- complexity,
1051
- createdAt: Date.now(),
1052
- },
1053
- 'task',
1054
- );
1055
-
1056
- return results;
1057
- }
1058
-
1059
- /**
903
+ // Add performance tracking for high-priority tasks
904
+ ...metadata.priority > 7 ? [
905
+ {
906
+ tool: 'performance_report',
907
+ params: {
908
+ format: 'detailed',
909
+ taskId
910
+ }
911
+ }
912
+ ] : []
913
+ ];
914
+ const results = await this.executeParallel(batch);
915
+ // Update task status
916
+ await this.storeMemory(swarmId, `task-${taskId}`, {
917
+ id: taskId,
918
+ task,
919
+ strategy,
920
+ status: 'in_progress',
921
+ priority: metadata.priority || 5,
922
+ complexity,
923
+ createdAt: Date.now()
924
+ }, 'task');
925
+ return results;
926
+ }
927
+ /**
1060
928
  * Analyze performance bottlenecks
1061
- */
1062
- async analyzePerformance(swarmId) {
1063
- const batch = [
1064
- { tool: 'bottleneck_analyze', params: { component: swarmId } },
1065
- { tool: 'performance_report', params: { format: 'detailed' } },
1066
- { tool: 'token_usage', params: { operation: swarmId } },
1067
- ];
1068
-
1069
- return await this.executeParallel(batch);
1070
- }
1071
-
1072
- /**
929
+ */ async analyzePerformance(swarmId) {
930
+ const batch = [
931
+ {
932
+ tool: 'bottleneck_analyze',
933
+ params: {
934
+ component: swarmId
935
+ }
936
+ },
937
+ {
938
+ tool: 'performance_report',
939
+ params: {
940
+ format: 'detailed'
941
+ }
942
+ },
943
+ {
944
+ tool: 'token_usage',
945
+ params: {
946
+ operation: swarmId
947
+ }
948
+ }
949
+ ];
950
+ return await this.executeParallel(batch);
951
+ }
952
+ /**
1073
953
  * GitHub integration for code operations
1074
- */
1075
- async githubOperations(repo, operation, params = {}) {
1076
- const githubTools = {
1077
- analyze: 'github_repo_analyze',
1078
- pr: 'github_pr_manage',
1079
- issue: 'github_issue_track',
1080
- review: 'github_code_review',
1081
- };
1082
-
1083
- const tool = githubTools[operation];
1084
- if (!tool) {
1085
- throw new Error(`Unknown GitHub operation: ${operation}`);
954
+ */ async githubOperations(repo, operation, params = {}) {
955
+ const githubTools = {
956
+ analyze: 'github_repo_analyze',
957
+ pr: 'github_pr_manage',
958
+ issue: 'github_issue_track',
959
+ review: 'github_code_review'
960
+ };
961
+ const tool = githubTools[operation];
962
+ if (!tool) {
963
+ throw new Error(`Unknown GitHub operation: ${operation}`);
964
+ }
965
+ return await this.executeTool(tool, {
966
+ repo,
967
+ ...params
968
+ });
1086
969
  }
1087
-
1088
- return await this.executeTool(tool, { repo, ...params });
1089
- }
1090
-
1091
- /**
970
+ /**
1092
971
  * Neural network operations
1093
- */
1094
- async neuralOperation(operation, params = {}) {
1095
- const neuralTools = {
1096
- train: 'neural_train',
1097
- predict: 'neural_predict',
1098
- analyze: 'neural_patterns',
1099
- optimize: 'wasm_optimize',
1100
- };
1101
-
1102
- const tool = neuralTools[operation];
1103
- if (!tool) {
1104
- throw new Error(`Unknown neural operation: ${operation}`);
972
+ */ async neuralOperation(operation, params = {}) {
973
+ const neuralTools = {
974
+ train: 'neural_train',
975
+ predict: 'neural_predict',
976
+ analyze: 'neural_patterns',
977
+ optimize: 'wasm_optimize'
978
+ };
979
+ const tool = neuralTools[operation];
980
+ if (!tool) {
981
+ throw new Error(`Unknown neural operation: ${operation}`);
982
+ }
983
+ return await this.executeTool(tool, params);
1105
984
  }
1106
-
1107
- return await this.executeTool(tool, params);
1108
- }
1109
-
1110
- /**
985
+ /**
1111
986
  * Clean up and destroy swarm
1112
- */
1113
- async destroySwarm(swarmId) {
1114
- const batch = [
1115
- { tool: 'swarm_destroy', params: { swarmId } },
1116
- {
1117
- tool: 'memory_namespace',
1118
- params: {
1119
- action: 'delete',
1120
- namespace: swarmId,
1121
- },
1122
- },
1123
- {
1124
- tool: 'cache_manage',
1125
- params: {
1126
- action: 'clear',
1127
- key: `swarm-${swarmId}`,
1128
- },
1129
- },
1130
- ];
1131
-
1132
- return await this.executeParallel(batch);
1133
- }
1134
-
1135
- /**
987
+ */ async destroySwarm(swarmId) {
988
+ const batch = [
989
+ {
990
+ tool: 'swarm_destroy',
991
+ params: {
992
+ swarmId
993
+ }
994
+ },
995
+ {
996
+ tool: 'memory_namespace',
997
+ params: {
998
+ action: 'delete',
999
+ namespace: swarmId
1000
+ }
1001
+ },
1002
+ {
1003
+ tool: 'cache_manage',
1004
+ params: {
1005
+ action: 'clear',
1006
+ key: `swarm-${swarmId}`
1007
+ }
1008
+ }
1009
+ ];
1010
+ return await this.executeParallel(batch);
1011
+ }
1012
+ /**
1136
1013
  * Get real swarm status from memory storage
1137
- */
1138
- async getSwarmStatus(params = {}) {
1139
- try {
1140
- // Don't reinitialize if we already have storage
1141
- if (!this.memoryDb && !this.memoryStore) {
1142
- await this.initializeMemoryStorage();
1143
- }
1144
-
1145
- const swarms = [];
1146
- let activeAgents = 0;
1147
- let totalTasks = 0;
1148
- let completedTasks = 0;
1149
-
1150
- if (this.memoryDb) {
1151
- // Get all unique swarm namespaces
1152
- const namespacesQuery = this.memoryDb.prepare(`
1014
+ */ async getSwarmStatus(params = {}) {
1015
+ try {
1016
+ // Don't reinitialize if we already have storage
1017
+ if (!this.memoryDb && !this.memoryStore) {
1018
+ await this.initializeMemoryStorage();
1019
+ }
1020
+ const swarms = [];
1021
+ let activeAgents = 0;
1022
+ let totalTasks = 0;
1023
+ let completedTasks = 0;
1024
+ if (this.memoryDb) {
1025
+ // Get all unique swarm namespaces
1026
+ const namespacesQuery = this.memoryDb.prepare(`
1153
1027
  SELECT DISTINCT namespace FROM memories
1154
1028
  WHERE namespace LIKE 'swarm-%' OR namespace LIKE 'hive-%'
1155
1029
  ORDER BY timestamp DESC
1156
1030
  `);
1157
- const namespaces = namespacesQuery.all();
1158
-
1159
- // For each swarm, gather its information
1160
- for (const { namespace } of namespaces) {
1161
- const swarmId = namespace;
1162
-
1163
- // Get swarm metadata
1164
- const metadataQuery = this.memoryDb.prepare(`
1031
+ const namespaces = namespacesQuery.all();
1032
+ // For each swarm, gather its information
1033
+ for (const { namespace } of namespaces){
1034
+ const swarmId = namespace;
1035
+ // Get swarm metadata
1036
+ const metadataQuery = this.memoryDb.prepare(`
1165
1037
  SELECT key, value, type, timestamp FROM memories
1166
1038
  WHERE namespace = ? AND (
1167
1039
  key IN ('init_performance', 'config', 'status', 'agents', 'tasks', 'topology')
@@ -1169,196 +1041,204 @@ https://github.com/ruvnet/claude-code-flow/docs/windows-installation.md
1169
1041
  OR key LIKE 'task-%'
1170
1042
  )
1171
1043
  `);
1172
- const swarmData = metadataQuery.all(swarmId);
1173
-
1174
- // Parse swarm information
1175
- let swarmInfo = {
1176
- id: swarmId,
1177
- name: swarmId,
1178
- status: 'unknown',
1179
- agents: 0,
1180
- tasks: { total: 0, completed: 0, pending: 0, failed: 0 },
1181
- topology: 'hierarchical',
1182
- createdAt: null,
1183
- lastActivity: null,
1184
- memoryUsage: swarmData.length,
1185
- };
1186
-
1187
- // Process swarm data
1188
- for (const record of swarmData) {
1189
- try {
1190
- const value =
1191
- typeof record.value === 'string' ? JSON.parse(record.value) : record.value;
1192
-
1193
- switch (record.key) {
1194
- case 'init_performance':
1195
- swarmInfo.createdAt = value.timestamp;
1196
- swarmInfo.topology = value.topology || 'hierarchical';
1197
- break;
1198
- case 'status':
1199
- swarmInfo.status = value;
1200
- break;
1201
- case 'config':
1202
- swarmInfo.topology = value.topology || swarmInfo.topology;
1203
- break;
1204
- }
1205
-
1206
- // Count agents
1207
- if (record.key.startsWith('agent-')) {
1208
- swarmInfo.agents++;
1209
- activeAgents++;
1210
- }
1211
-
1212
- // Count tasks
1213
- if (record.key.startsWith('task-')) {
1214
- swarmInfo.tasks.total++;
1215
- totalTasks++;
1216
- if (value.status === 'completed') {
1217
- swarmInfo.tasks.completed++;
1218
- completedTasks++;
1219
- } else if (value.status === 'failed') {
1220
- swarmInfo.tasks.failed++;
1221
- } else if (value.status === 'pending' || value.status === 'in_progress') {
1222
- swarmInfo.tasks.pending++;
1044
+ const swarmData = metadataQuery.all(swarmId);
1045
+ // Parse swarm information
1046
+ let swarmInfo = {
1047
+ id: swarmId,
1048
+ name: swarmId,
1049
+ status: 'unknown',
1050
+ agents: 0,
1051
+ tasks: {
1052
+ total: 0,
1053
+ completed: 0,
1054
+ pending: 0,
1055
+ failed: 0
1056
+ },
1057
+ topology: 'hierarchical',
1058
+ createdAt: null,
1059
+ lastActivity: null,
1060
+ memoryUsage: swarmData.length
1061
+ };
1062
+ // Process swarm data
1063
+ for (const record of swarmData){
1064
+ try {
1065
+ const value = typeof record.value === 'string' ? JSON.parse(record.value) : record.value;
1066
+ switch(record.key){
1067
+ case 'init_performance':
1068
+ swarmInfo.createdAt = value.timestamp;
1069
+ swarmInfo.topology = value.topology || 'hierarchical';
1070
+ break;
1071
+ case 'status':
1072
+ swarmInfo.status = value;
1073
+ break;
1074
+ case 'config':
1075
+ swarmInfo.topology = value.topology || swarmInfo.topology;
1076
+ break;
1077
+ }
1078
+ // Count agents
1079
+ if (record.key.startsWith('agent-')) {
1080
+ swarmInfo.agents++;
1081
+ activeAgents++;
1082
+ }
1083
+ // Count tasks
1084
+ if (record.key.startsWith('task-')) {
1085
+ swarmInfo.tasks.total++;
1086
+ totalTasks++;
1087
+ if (value.status === 'completed') {
1088
+ swarmInfo.tasks.completed++;
1089
+ completedTasks++;
1090
+ } else if (value.status === 'failed') {
1091
+ swarmInfo.tasks.failed++;
1092
+ } else if (value.status === 'pending' || value.status === 'in_progress') {
1093
+ swarmInfo.tasks.pending++;
1094
+ }
1095
+ }
1096
+ // Track last activity
1097
+ if (record.timestamp > (swarmInfo.lastActivity || 0)) {
1098
+ swarmInfo.lastActivity = record.timestamp;
1099
+ }
1100
+ } catch (e) {
1101
+ // Skip invalid JSON values
1102
+ }
1103
+ }
1104
+ // Determine swarm status based on activity
1105
+ if (swarmInfo.status === 'unknown') {
1106
+ const now = Date.now();
1107
+ const lastActivityAge = now - (swarmInfo.lastActivity || 0);
1108
+ if (lastActivityAge < 60000) {
1109
+ // Active within last minute
1110
+ swarmInfo.status = 'active';
1111
+ } else if (lastActivityAge < 300000) {
1112
+ // Active within last 5 minutes
1113
+ swarmInfo.status = 'idle';
1114
+ } else {
1115
+ swarmInfo.status = 'inactive';
1116
+ }
1117
+ }
1118
+ swarms.push(swarmInfo);
1223
1119
  }
1224
- }
1225
-
1226
- // Track last activity
1227
- if (record.timestamp > (swarmInfo.lastActivity || 0)) {
1228
- swarmInfo.lastActivity = record.timestamp;
1229
- }
1230
- } catch (e) {
1231
- // Skip invalid JSON values
1232
- }
1233
- }
1234
-
1235
- // Determine swarm status based on activity
1236
- if (swarmInfo.status === 'unknown') {
1237
- const now = Date.now();
1238
- const lastActivityAge = now - (swarmInfo.lastActivity || 0);
1239
-
1240
- if (lastActivityAge < 60000) {
1241
- // Active within last minute
1242
- swarmInfo.status = 'active';
1243
- } else if (lastActivityAge < 300000) {
1244
- // Active within last 5 minutes
1245
- swarmInfo.status = 'idle';
1246
- } else {
1247
- swarmInfo.status = 'inactive';
1248
- }
1249
- }
1250
-
1251
- swarms.push(swarmInfo);
1252
- }
1253
-
1254
- // Get recent activity logs
1255
- const activityQuery = this.memoryDb.prepare(`
1120
+ // Get recent activity logs
1121
+ const activityQuery = this.memoryDb.prepare(`
1256
1122
  SELECT namespace, key, type, timestamp FROM memories
1257
1123
  WHERE (namespace LIKE 'swarm-%' OR namespace LIKE 'hive-%')
1258
1124
  AND timestamp > ?
1259
1125
  ORDER BY timestamp DESC
1260
1126
  LIMIT 10
1261
1127
  `);
1262
- const recentActivity = activityQuery.all(Date.now() - 300000); // Last 5 minutes
1263
-
1264
- return {
1265
- swarms,
1266
- activeAgents,
1267
- totalTasks,
1268
- completedTasks,
1269
- pendingTasks: totalTasks - completedTasks,
1270
- recentActivity: recentActivity.map((r) => ({
1271
- swarmId: r.namespace,
1272
- action: r.key,
1273
- type: r.type,
1274
- timestamp: r.timestamp,
1275
- })),
1276
- summary: {
1277
- totalSwarms: swarms.length,
1278
- activeSwarms: swarms.filter((s) => s.status === 'active').length,
1279
- idleSwarms: swarms.filter((s) => s.status === 'idle').length,
1280
- inactiveSwarms: swarms.filter((s) => s.status === 'inactive').length,
1281
- },
1282
- };
1283
- } else {
1284
- // Fallback to in-memory storage
1285
- const swarmMap = new Map();
1286
-
1287
- for (const [key, memory] of this.memoryStore) {
1288
- const namespace = memory.namespace;
1289
- if (namespace && (namespace.startsWith('swarm-') || namespace.startsWith('hive-'))) {
1290
- if (!swarmMap.has(namespace)) {
1291
- swarmMap.set(namespace, {
1292
- id: namespace,
1293
- name: namespace,
1294
- status: 'active',
1295
- agents: 0,
1296
- tasks: { total: 0, completed: 0, pending: 0, failed: 0 },
1297
- memoryUsage: 0,
1298
- });
1299
- }
1300
-
1301
- const swarm = swarmMap.get(namespace);
1302
- swarm.memoryUsage++;
1303
-
1304
- if (memory.key.startsWith('agent-')) {
1305
- swarm.agents++;
1306
- activeAgents++;
1307
- }
1308
-
1309
- if (memory.key.startsWith('task-')) {
1310
- swarm.tasks.total++;
1311
- totalTasks++;
1312
- try {
1313
- const taskData = JSON.parse(memory.value);
1314
- if (taskData.status === 'completed') {
1315
- swarm.tasks.completed++;
1316
- completedTasks++;
1317
- } else if (taskData.status === 'failed') {
1318
- swarm.tasks.failed++;
1319
- } else if (taskData.status === 'pending' || taskData.status === 'in_progress') {
1320
- swarm.tasks.pending++;
1128
+ const recentActivity = activityQuery.all(Date.now() - 300000); // Last 5 minutes
1129
+ return {
1130
+ swarms,
1131
+ activeAgents,
1132
+ totalTasks,
1133
+ completedTasks,
1134
+ pendingTasks: totalTasks - completedTasks,
1135
+ recentActivity: recentActivity.map((r)=>({
1136
+ swarmId: r.namespace,
1137
+ action: r.key,
1138
+ type: r.type,
1139
+ timestamp: r.timestamp
1140
+ })),
1141
+ summary: {
1142
+ totalSwarms: swarms.length,
1143
+ activeSwarms: swarms.filter((s)=>s.status === 'active').length,
1144
+ idleSwarms: swarms.filter((s)=>s.status === 'idle').length,
1145
+ inactiveSwarms: swarms.filter((s)=>s.status === 'inactive').length
1146
+ }
1147
+ };
1148
+ } else {
1149
+ // Fallback to in-memory storage
1150
+ const swarmMap = new Map();
1151
+ for (const [key, memory] of this.memoryStore){
1152
+ const namespace = memory.namespace;
1153
+ if (namespace && (namespace.startsWith('swarm-') || namespace.startsWith('hive-'))) {
1154
+ if (!swarmMap.has(namespace)) {
1155
+ swarmMap.set(namespace, {
1156
+ id: namespace,
1157
+ name: namespace,
1158
+ status: 'active',
1159
+ agents: 0,
1160
+ tasks: {
1161
+ total: 0,
1162
+ completed: 0,
1163
+ pending: 0,
1164
+ failed: 0
1165
+ },
1166
+ memoryUsage: 0
1167
+ });
1168
+ }
1169
+ const swarm = swarmMap.get(namespace);
1170
+ swarm.memoryUsage++;
1171
+ if (memory.key.startsWith('agent-')) {
1172
+ swarm.agents++;
1173
+ activeAgents++;
1174
+ }
1175
+ if (memory.key.startsWith('task-')) {
1176
+ swarm.tasks.total++;
1177
+ totalTasks++;
1178
+ try {
1179
+ const taskData = JSON.parse(memory.value);
1180
+ if (taskData.status === 'completed') {
1181
+ swarm.tasks.completed++;
1182
+ completedTasks++;
1183
+ } else if (taskData.status === 'failed') {
1184
+ swarm.tasks.failed++;
1185
+ } else if (taskData.status === 'pending' || taskData.status === 'in_progress') {
1186
+ swarm.tasks.pending++;
1187
+ }
1188
+ } catch (e) {
1189
+ // Skip invalid JSON
1190
+ }
1191
+ }
1192
+ }
1321
1193
  }
1322
- } catch (e) {
1323
- // Skip invalid JSON
1324
- }
1194
+ return {
1195
+ swarms: Array.from(swarmMap.values()),
1196
+ activeAgents,
1197
+ totalTasks,
1198
+ completedTasks,
1199
+ pendingTasks: totalTasks - completedTasks,
1200
+ summary: {
1201
+ totalSwarms: swarmMap.size,
1202
+ activeSwarms: swarmMap.size
1203
+ }
1204
+ };
1325
1205
  }
1326
- }
1206
+ } catch (error) {
1207
+ console.error('Error getting swarm status:', error);
1208
+ // Return empty status on error
1209
+ return {
1210
+ swarms: [],
1211
+ activeAgents: 0,
1212
+ totalTasks: 0,
1213
+ completedTasks: 0,
1214
+ pendingTasks: 0,
1215
+ recentActivity: [],
1216
+ summary: {
1217
+ totalSwarms: 0,
1218
+ activeSwarms: 0,
1219
+ idleSwarms: 0,
1220
+ inactiveSwarms: 0
1221
+ },
1222
+ error: error.message
1223
+ };
1327
1224
  }
1328
-
1329
- return {
1330
- swarms: Array.from(swarmMap.values()),
1331
- activeAgents,
1332
- totalTasks,
1333
- completedTasks,
1334
- pendingTasks: totalTasks - completedTasks,
1335
- summary: {
1336
- totalSwarms: swarmMap.size,
1337
- activeSwarms: swarmMap.size,
1338
- },
1225
+ }
1226
+ constructor(config = {}){
1227
+ this.config = {
1228
+ parallel: true,
1229
+ timeout: 60000,
1230
+ retryCount: 3,
1231
+ ...config
1339
1232
  };
1340
- }
1341
- } catch (error) {
1342
- console.error('Error getting swarm status:', error);
1343
- // Return empty status on error
1344
- return {
1345
- swarms: [],
1346
- activeAgents: 0,
1347
- totalTasks: 0,
1348
- completedTasks: 0,
1349
- pendingTasks: 0,
1350
- recentActivity: [],
1351
- summary: {
1352
- totalSwarms: 0,
1353
- activeSwarms: 0,
1354
- idleSwarms: 0,
1355
- inactiveSwarms: 0,
1356
- },
1357
- error: error.message,
1358
- };
1233
+ this.toolStats = new Map();
1234
+ this.parallelQueue = [];
1235
+ this.executing = false;
1236
+ /** @type {import('better-sqlite3').Database | null} */ this.memoryDb = null;
1237
+ // Initialize memory store for fallback
1238
+ this.memoryStore = new Map();
1239
+ // Initialize real memory storage
1240
+ this.initializeMemoryStorage();
1359
1241
  }
1360
- }
1361
1242
  }
1362
-
1363
1243
  // Export tool categories for reference
1364
1244
  export { MCP_TOOLS };