claude-flow-novice 2.0.4 → 2.0.5

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 (496) hide show
  1. package/dist/src/cli/commands/guidance.js +668 -487
  2. package/dist/src/cli/commands/index-validate.js +29 -18
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +282 -230
  4. package/dist/src/cli/commands/neural-goal-init.js +125 -92
  5. package/dist/src/cli/commands/swarm-exec.js +393 -317
  6. package/dist/src/cli/commands/validate-framework.js +1100 -983
  7. package/dist/src/cli/commands/validate.js +223 -144
  8. package/dist/src/cli/main.js +1 -1
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +277 -265
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +7 -6
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +356 -373
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +7 -6
  13. package/dist/src/cli/simple-commands/agent.js +193 -157
  14. package/dist/src/cli/simple-commands/analysis.js +446 -336
  15. package/dist/src/cli/simple-commands/automation-executor.js +1339 -1095
  16. package/dist/src/cli/simple-commands/automation.js +469 -481
  17. package/dist/src/cli/simple-commands/batch-manager.js +313 -261
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +267 -241
  19. package/dist/src/cli/simple-commands/claude-track.js +90 -68
  20. package/dist/src/cli/simple-commands/concurrent-display.js +320 -266
  21. package/dist/src/cli/simple-commands/config.js +290 -245
  22. package/dist/src/cli/simple-commands/coordination.js +234 -182
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +615 -812
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +981 -922
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +294 -274
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +457 -378
  27. package/dist/src/cli/simple-commands/github/github-api.js +574 -535
  28. package/dist/src/cli/simple-commands/github/init.js +303 -276
  29. package/dist/src/cli/simple-commands/github.js +247 -222
  30. package/dist/src/cli/simple-commands/goal.js +63 -51
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +278 -208
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +696 -601
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +979 -907
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +655 -406
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1245 -1125
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +1090 -854
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +574 -459
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +347 -263
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +768 -727
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +1049 -745
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +283 -227
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +217 -174
  43. package/dist/src/cli/simple-commands/hive-mind.js +2282 -1841
  44. package/dist/src/cli/simple-commands/hive.js +79 -90
  45. package/dist/src/cli/simple-commands/hook-safety.js +521 -431
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +254 -203
  47. package/dist/src/cli/simple-commands/hooks.js +1204 -1064
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +319 -294
  49. package/dist/src/cli/simple-commands/init/batch-init.js +562 -496
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +19 -13
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +19 -13
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +88 -61
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +150 -125
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +49 -42
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +61 -43
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +147 -141
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +44 -31
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +90 -64
  59. package/dist/src/cli/simple-commands/init/help.js +107 -104
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +528 -509
  61. package/dist/src/cli/simple-commands/init/index.js +1759 -1510
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +317 -234
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +504 -441
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +364 -289
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +728 -652
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +481 -416
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +448 -369
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +2 -1
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +99 -122
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +37 -32
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +62 -55
  72. package/dist/src/cli/simple-commands/init/template-copier.js +533 -421
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +6 -3
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +318 -344
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +218 -173
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +75 -65
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +6 -3
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +4 -2
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +230 -187
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +80 -53
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +85 -101
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +330 -283
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +561 -495
  84. package/dist/src/cli/simple-commands/init/validation/index.js +358 -302
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +359 -308
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +366 -389
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +268 -270
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +447 -427
  89. package/dist/src/cli/simple-commands/init.js +2 -1
  90. package/dist/src/cli/simple-commands/mcp-health.js +158 -131
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +634 -533
  92. package/dist/src/cli/simple-commands/mcp.js +400 -345
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +537 -426
  94. package/dist/src/cli/simple-commands/memory.js +311 -247
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +46 -39
  96. package/dist/src/cli/simple-commands/monitor.js +363 -294
  97. package/dist/src/cli/simple-commands/neural.js +65 -51
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +662 -538
  99. package/dist/src/cli/simple-commands/pair-basic.js +656 -528
  100. package/dist/src/cli/simple-commands/pair-old.js +543 -430
  101. package/dist/src/cli/simple-commands/pair-working.js +751 -615
  102. package/dist/src/cli/simple-commands/pair.js +751 -615
  103. package/dist/src/cli/simple-commands/performance-hooks.js +111 -83
  104. package/dist/src/cli/simple-commands/performance-metrics.js +433 -348
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +787 -708
  106. package/dist/src/cli/simple-commands/process-ui.js +254 -230
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +611 -525
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1530 -1704
  109. package/dist/src/cli/simple-commands/sparc/commands.js +516 -438
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1481 -1224
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +978 -913
  112. package/dist/src/cli/simple-commands/sparc/index.js +298 -241
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +390 -314
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +869 -965
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +1273 -980
  116. package/dist/src/cli/simple-commands/sparc/specification.js +645 -559
  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 +55 -47
  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 +87 -101
  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 +493 -465
  137. package/dist/src/cli/simple-commands/start-ui.js +132 -108
  138. package/dist/src/cli/simple-commands/start-wrapper.js +268 -240
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +275 -254
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +171 -128
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +82 -61
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +331 -267
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +263 -211
  145. package/dist/src/cli/simple-commands/stream-chain.js +318 -260
  146. package/dist/src/cli/simple-commands/stream-processor.js +315 -290
  147. package/dist/src/cli/simple-commands/swarm-executor.js +222 -189
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +300 -208
  149. package/dist/src/cli/simple-commands/swarm-ui.js +703 -623
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +286 -258
  151. package/dist/src/cli/simple-commands/swarm.js +1082 -887
  152. package/dist/src/cli/simple-commands/task.js +206 -161
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +89 -59
  154. package/dist/src/cli/simple-commands/token-tracker.js +316 -258
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +519 -433
  156. package/dist/src/cli/simple-commands/train-and-stream.js +331 -275
  157. package/dist/src/cli/simple-commands/training-pipeline.js +725 -619
  158. package/dist/src/cli/simple-commands/training.js +227 -170
  159. package/dist/src/cli/simple-commands/verification-hooks.js +284 -261
  160. package/dist/src/cli/simple-commands/verification-integration.js +417 -389
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +606 -486
  162. package/dist/src/cli/simple-commands/verification.js +513 -493
  163. package/dist/src/cli/simple-commands/web-server.js +836 -766
  164. package/dist/src/cli/simple-commands/webui-validator.js +124 -106
  165. package/dist/src/coordination/byzantine-memory-channels.js +25 -1
  166. package/dist/src/coordination/event-bus/demo-wasm-integration.js +251 -212
  167. package/dist/src/coordination/event-bus/qe-event-bus.js +748 -608
  168. package/dist/src/coordination/event-bus/qe-event-bus.test.js +454 -379
  169. package/dist/src/coordination/iteration-tracker.js +454 -363
  170. package/dist/src/index.js +384 -35
  171. package/dist/src/mcp/DEPRECATED.js +60 -46
  172. package/dist/src/mcp/fixes/mcp-error-fixes.js +134 -115
  173. package/dist/src/mcp/implementations/agent-tracker.js +128 -114
  174. package/dist/src/mcp/implementations/daa-tools.js +350 -292
  175. package/dist/src/mcp/implementations/workflow-tools.js +361 -329
  176. package/dist/src/mcp/mcp-config-manager.js +1331 -1183
  177. package/dist/src/mcp/mcp-server-novice-simplified.js +17 -11
  178. package/dist/src/mcp/mcp-server-novice.js +17 -11
  179. package/dist/src/mcp/mcp-server-sdk.js +17 -11
  180. package/dist/src/mcp/mcp-server.js +1484 -1620
  181. package/dist/src/mcp/ruv-swarm-wrapper.js +239 -209
  182. package/dist/src/memory/advanced-serializer.js +589 -609
  183. package/dist/src/memory/enhanced-examples.js +305 -220
  184. package/dist/src/memory/enhanced-memory.js +336 -295
  185. package/dist/src/memory/enhanced-session-serializer.js +492 -408
  186. package/dist/src/memory/fallback-memory-system.js +1021 -900
  187. package/dist/src/memory/fallback-store.js +131 -93
  188. package/dist/src/memory/high-performance-serialization.js +730 -592
  189. package/dist/src/memory/in-memory-store.js +213 -161
  190. package/dist/src/memory/index.js +157 -123
  191. package/dist/src/memory/lock-free-structures.js +764 -578
  192. package/dist/src/memory/memory-mapped-persistence.js +766 -585
  193. package/dist/src/memory/memory-pressure-manager.js +707 -569
  194. package/dist/src/memory/migration.js +445 -358
  195. package/dist/src/memory/shared-memory.js +768 -641
  196. package/dist/src/memory/sqlite-store.js +325 -245
  197. package/dist/src/memory/sqlite-wrapper.js +151 -122
  198. package/dist/src/memory/swarm-memory.js +603 -470
  199. package/dist/src/memory/test-example.js +134 -126
  200. package/dist/src/memory/ultra-fast-memory-store.js +821 -622
  201. package/dist/src/memory/unified-memory-manager.js +437 -356
  202. package/dist/src/swarm/CodeRefactoringSwarm.js +952 -777
  203. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +400 -332
  204. package/dist/src/utils/error-handler.js +2 -36
  205. package/dist/src/utils/github-cli-safe.js +64 -56
  206. package/dist/src/utils/github-cli-safety-wrapper.js +546 -451
  207. package/dist/src/utils/npx-isolated-cache.js +119 -104
  208. package/dist/src/utils/preference-manager.js +652 -622
  209. package/dist/src/utils/timezone-utils.js +105 -86
  210. package/dist/src/web/api/apm-routes.js +353 -0
  211. package/dist/src/web/api/config/api-config.js +184 -0
  212. package/dist/src/web/api/middleware/auth.js +203 -0
  213. package/dist/src/web/api/middleware/cache.js +273 -0
  214. package/dist/src/web/api/middleware/error-handler.js +257 -0
  215. package/dist/src/web/api/middleware/request-logger.js +215 -0
  216. package/dist/src/web/api/middleware/validation.js +323 -0
  217. package/dist/src/web/api/routes/events.js +463 -0
  218. package/dist/src/web/api/routes/hierarchy.js +300 -0
  219. package/dist/src/web/api/routes/index.js +12 -0
  220. package/dist/src/web/api/routes/metrics.js +559 -0
  221. package/dist/src/web/api/routes/parallel-status.js +359 -0
  222. package/dist/src/web/api/routes/status.js +448 -0
  223. package/dist/src/web/api/server.js +462 -0
  224. package/dist/src/web/dashboard/hooks/useWebSocket.js +383 -0
  225. package/dist/src/web/dashboard/index.js +85 -0
  226. package/dist/src/web/dashboard/realtime/CustomSyncManager.js +439 -0
  227. package/dist/src/web/dashboard/realtime/NativeWebSocketManager.js +323 -0
  228. package/dist/src/web/dashboard/realtime/PerformanceBenchmark.js +527 -0
  229. package/dist/src/web/dashboard/realtime/RealtimeCommunicationManager.js +474 -0
  230. package/dist/src/web/dashboard/realtime/RealtimeServer.js +666 -0
  231. package/dist/src/web/dashboard/realtime/SSEManager.js +426 -0
  232. package/dist/src/web/dashboard/types.js +4 -0
  233. package/dist/src/web/messaging/agent-status-tracker.js +453 -0
  234. package/dist/src/web/messaging/human-intervention-system.js +305 -0
  235. package/dist/src/web/messaging/message-filter.js +302 -0
  236. package/dist/src/web/messaging/swarm-message-router.js +324 -0
  237. package/dist/src/web/messaging/transparency-logger.js +421 -0
  238. package/dist/src/web/portal-server.js +460 -0
  239. package/dist/src/web/server.js +322 -0
  240. package/dist/src/web/websocket/apm-websocket-handler.js +453 -0
  241. package/dist/src/web/websocket/websocket-manager.js +780 -0
  242. package/package.json +5 -3
  243. package/dist/src/cli/minimal-main.js +0 -22
  244. package/dist/src/enterprise/analytics-manager.js +0 -1135
  245. package/dist/src/enterprise/audit-manager.js +0 -1115
  246. package/dist/src/enterprise/cloud-manager.js +0 -891
  247. package/dist/src/enterprise/deployment-manager.js +0 -966
  248. package/dist/src/enterprise/index.js +0 -6
  249. package/dist/src/enterprise/project-manager.js +0 -584
  250. package/dist/src/enterprise/security-manager.js +0 -991
  251. package/dist/src/migration/index.js +0 -92
  252. package/dist/src/migration/logger.js +0 -121
  253. package/dist/src/migration/migration-analyzer.js +0 -268
  254. package/dist/src/migration/migration-runner.js +0 -522
  255. package/dist/src/migration/migration-validator.js +0 -285
  256. package/dist/src/migration/progress-reporter.js +0 -150
  257. package/dist/src/migration/rollback-manager.js +0 -321
  258. package/dist/src/migration/tests/migration-system.test.js +0 -7
  259. package/dist/src/migration/types.js +0 -3
  260. package/dist/src/swarm/__tests__/integration.test.js +0 -227
  261. package/dist/src/swarm/__tests__/prompt-copier.test.js +0 -344
  262. package/dist/src/swarm/advanced-orchestrator.js +0 -1095
  263. package/dist/src/swarm/claude-code-interface.js +0 -961
  264. package/dist/src/swarm/claude-flow-executor.js +0 -229
  265. package/dist/src/swarm/consensus-coordinator.js +0 -475
  266. package/dist/src/swarm/coordinator.js +0 -2993
  267. package/dist/src/swarm/direct-executor.js +0 -1180
  268. package/dist/src/swarm/error-recovery/advanced-error-detection.js +0 -691
  269. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +0 -998
  270. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +0 -1197
  271. package/dist/src/swarm/error-recovery/recovery-monitoring.js +0 -772
  272. package/dist/src/swarm/error-recovery/resilience-architecture.js +0 -714
  273. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +0 -1319
  274. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +0 -808
  275. package/dist/src/swarm/executor-v2.js +0 -322
  276. package/dist/src/swarm/executor.js +0 -815
  277. package/dist/src/swarm/hive-mind-integration.js +0 -703
  278. package/dist/src/swarm/index.js +0 -41
  279. package/dist/src/swarm/json-output-aggregator.js +0 -267
  280. package/dist/src/swarm/large-scale-coordinator.js +0 -542
  281. package/dist/src/swarm/mcp-integration-wrapper.js +0 -628
  282. package/dist/src/swarm/memory.js +0 -1117
  283. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +0 -348
  284. package/dist/src/swarm/optimizations/async-file-manager.js +0 -285
  285. package/dist/src/swarm/optimizations/circular-buffer.js +0 -162
  286. package/dist/src/swarm/optimizations/connection-pool.js +0 -244
  287. package/dist/src/swarm/optimizations/index.js +0 -28
  288. package/dist/src/swarm/optimizations/optimized-executor.js +0 -320
  289. package/dist/src/swarm/optimizations/ttl-map.js +0 -234
  290. package/dist/src/swarm/prompt-cli.js +0 -200
  291. package/dist/src/swarm/prompt-copier-enhanced.js +0 -202
  292. package/dist/src/swarm/prompt-copier.js +0 -381
  293. package/dist/src/swarm/prompt-manager.js +0 -295
  294. package/dist/src/swarm/prompt-utils.js +0 -310
  295. package/dist/src/swarm/result-aggregator.js +0 -718
  296. package/dist/src/swarm/sparc-executor.js +0 -1568
  297. package/dist/src/swarm/strategies/auto.js +0 -758
  298. package/dist/src/swarm/strategies/base.js +0 -128
  299. package/dist/src/swarm/strategies/research.js +0 -914
  300. package/dist/src/swarm/strategies/strategy-metrics-patch.js +0 -2
  301. package/dist/src/swarm/types.js +0 -52
  302. package/dist/src/swarm/workers/copy-worker.js +0 -56
  303. package/dist/src/validators/epic-config-schema.js +0 -214
  304. package/dist/src/validators/index.js +0 -10
  305. package/dist/src/validators/swarm-init-validator.js +0 -259
  306. package/dist/src/validators/todowrite-batching-validator.js +0 -215
  307. package/dist/src/validators/todowrite-integration.js +0 -187
  308. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/documentSymbols/browser/documentSymbols.js +0 -23
  309. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/copyPasteContribution.js +0 -57
  310. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/copyPasteController.js +0 -401
  311. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/defaultProviders.js +0 -181
  312. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorContribution.js +0 -44
  313. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorController.js +0 -157
  314. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/dropOrPasteInto/browser/edit.js +0 -71
  315. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/editorState/browser/editorState.js +0 -112
  316. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findController.js +0 -990
  317. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findDecorations.js +0 -296
  318. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findModel.js +0 -488
  319. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findOptionsWidget.js +0 -138
  320. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findState.js +0 -243
  321. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/find/browser/findWidget.js +0 -1177
  322. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/folding/browser/folding.js +0 -1093
  323. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/folding/browser/foldingDecorations.js +0 -133
  324. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/folding/browser/foldingModel.js +0 -538
  325. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/folding/browser/foldingRanges.js +0 -351
  326. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/fontZoom/browser/fontZoom.js +0 -49
  327. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/format/browser/format.js +0 -360
  328. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/format/browser/formatActions.js +0 -263
  329. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/format/browser/formattingEdit.js +0 -54
  330. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture.js +0 -149
  331. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/hover/browser/contentHover.js +0 -874
  332. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/inlineCompletions/browser/commandIds.js +0 -7
  333. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/inlineCompletions/browser/commands.js +0 -199
  334. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/linesOperations/browser/copyLinesCommand.js +0 -70
  335. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/quickAccess/browser/commandsQuickAccess.js +0 -26
  336. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess.js +0 -153
  337. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/readOnlyMessage/browser/contribution.js +0 -33
  338. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/semanticTokens/browser/documentSemanticTokens.js +0 -354
  339. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/smartSelect/browser/bracketSelections.js +0 -146
  340. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/suggest/browser/completionModel.js +0 -224
  341. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/contrib/unicodeHighlighter/browser/bannerController.js +0 -119
  342. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/edcore.main.js +0 -14
  343. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/editor.all.js +0 -63
  344. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/editor.api.js +0 -55
  345. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/editor.main.js +0 -7
  346. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/editor.worker.js +0 -25
  347. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/editor/standalone/browser/colorizer.js +0 -118
  348. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/language/css/css.worker.js +0 -36869
  349. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/language/css/cssMode.js +0 -2035
  350. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/accessibility/browser/accessibilityService.js +0 -88
  351. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/accessibility/common/accessibility.js +0 -9
  352. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/action/common/action.js +0 -7
  353. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/action/common/actionCommonCategories.js +0 -13
  354. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/actionWidget/browser/actionList.js +0 -276
  355. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/actionWidget/browser/actionWidget.js +0 -248
  356. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/actionWidget/common/actionWidget.js +0 -5
  357. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/actions/common/actions.js +0 -409
  358. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/audioCues/browser/audioCueService.js +0 -176
  359. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/clipboard/browser/clipboardService.js +0 -141
  360. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/clipboard/common/clipboardService.js +0 -6
  361. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/commands/common/commands.js +0 -80
  362. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/configuration/common/configuration.js +0 -86
  363. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/configuration/common/configurationModels.js +0 -554
  364. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/configuration/common/configurationRegistry.js +0 -317
  365. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/configuration/common/configurations.js +0 -41
  366. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextkey/browser/contextKeyService.js +0 -432
  367. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextkey/common/contextkey.js +0 -1547
  368. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextkey/common/contextkeys.js +0 -18
  369. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextview/browser/contextMenuHandler.js +0 -124
  370. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextview/browser/contextMenuService.js +0 -101
  371. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextview/browser/contextView.js +0 -7
  372. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/contextview/browser/contextViewService.js +0 -72
  373. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/dialogs/common/dialogs.js +0 -2
  374. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/dnd/browser/dnd.js +0 -36
  375. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/editor/common/editor.js +0 -17
  376. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/environment/common/environment.js +0 -2
  377. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/extensions/common/extensions.js +0 -47
  378. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/files/common/files.js +0 -9
  379. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/history/browser/contextScopedHistoryWidget.js +0 -105
  380. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/instantiation/common/descriptors.js +0 -11
  381. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/instantiation/common/extensions.js +0 -15
  382. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/keybinding/common/abstractKeybindingService.js +0 -277
  383. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/keybinding/common/baseResolvedKeybinding.js +0 -53
  384. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/quickinput/browser/commandsQuickAccess.js +0 -354
  385. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/theme/browser/defaultStyles.js +0 -162
  386. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/esm/vs/platform/theme/common/colorRegistry.js +0 -482
  387. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/abap/abap.js +0 -10
  388. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/apex/apex.js +0 -10
  389. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/azcli/azcli.js +0 -10
  390. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/bat/bat.js +0 -10
  391. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/bicep/bicep.js +0 -11
  392. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/cameligo/cameligo.js +0 -10
  393. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/clojure/clojure.js +0 -10
  394. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/coffee/coffee.js +0 -10
  395. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/cpp/cpp.js +0 -10
  396. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/csharp/csharp.js +0 -10
  397. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/csp/csp.js +0 -10
  398. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/css/css.js +0 -12
  399. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/cypher/cypher.js +0 -10
  400. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/dart/dart.js +0 -10
  401. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/dockerfile/dockerfile.js +0 -10
  402. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/ecl/ecl.js +0 -10
  403. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/elixir/elixir.js +0 -10
  404. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/basic-languages/flow9/flow9.js +0 -10
  405. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.js +0 -745
  406. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.de.js +0 -31
  407. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.es.js +0 -31
  408. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.fr.js +0 -29
  409. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.it.js +0 -29
  410. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.ja.js +0 -31
  411. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.js +0 -29
  412. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.ko.js +0 -29
  413. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.ru.js +0 -31
  414. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.zh-cn.js +0 -31
  415. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/editor/editor.main.nls.zh-tw.js +0 -29
  416. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/language/css/cssMode.js +0 -13
  417. package/dist/src/web/frontend/node_modules/.monaco-editor-MndU045b/min/vs/language/css/cssWorker.js +0 -81
  418. package/dist/src/web/frontend/node_modules/.multicast-dns-iKseM9bB/cli.js +0 -64
  419. package/dist/src/web/frontend/node_modules/.multicast-dns-iKseM9bB/example.js +0 -36
  420. package/dist/src/web/frontend/node_modules/.multicast-dns-iKseM9bB/index.js +0 -205
  421. package/dist/src/web/frontend/node_modules/.multicast-dns-iKseM9bB/test.js +0 -260
  422. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/async/index.browser.js +0 -34
  423. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/async/index.js +0 -35
  424. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/async/index.native.js +0 -26
  425. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/index.browser.js +0 -34
  426. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/index.js +0 -45
  427. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/nanoid.js +0 -1
  428. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/non-secure/index.js +0 -21
  429. package/dist/src/web/frontend/node_modules/.nanoid-PAMEV9Hd/url-alphabet/index.js +0 -3
  430. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/bin/nodemon.js +0 -16
  431. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/cli/index.js +0 -49
  432. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/cli/parse.js +0 -230
  433. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/config/command.js +0 -43
  434. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/config/defaults.js +0 -34
  435. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/config/exec.js +0 -234
  436. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/config/index.js +0 -93
  437. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/config/load.js +0 -225
  438. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/help/index.js +0 -27
  439. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/index.js +0 -1
  440. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/monitor/index.js +0 -4
  441. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/monitor/match.js +0 -287
  442. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/monitor/run.js +0 -562
  443. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/monitor/signals.js +0 -34
  444. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/monitor/watch.js +0 -244
  445. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/nodemon.js +0 -317
  446. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/rules/add.js +0 -89
  447. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/rules/index.js +0 -53
  448. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/rules/parse.js +0 -43
  449. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/spawn.js +0 -74
  450. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/bus.js +0 -44
  451. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/clone.js +0 -40
  452. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/colour.js +0 -26
  453. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/index.js +0 -103
  454. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/log.js +0 -82
  455. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/utils/merge.js +0 -47
  456. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/lib/version.js +0 -100
  457. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/node_modules/brace-expansion/index.js +0 -201
  458. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/node_modules/has-flag/index.js +0 -8
  459. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/node_modules/minimatch/minimatch.js +0 -947
  460. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/node_modules/supports-color/browser.js +0 -5
  461. package/dist/src/web/frontend/node_modules/.nodemon-QcvNKhKT/node_modules/supports-color/index.js +0 -131
  462. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/bin/pidtree.js +0 -128
  463. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/index.js +0 -49
  464. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/lib/bin.js +0 -61
  465. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/lib/get.js +0 -45
  466. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/lib/pidtree.js +0 -104
  467. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/lib/ps.js +0 -47
  468. package/dist/src/web/frontend/node_modules/.pidtree-icfat3SQ/lib/wmic.js +0 -49
  469. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/doc.js +0 -1270
  470. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/acorn.js +0 -15
  471. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/angular.js +0 -2
  472. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/babel.js +0 -15
  473. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/estree.js +0 -36
  474. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/flow.js +0 -19
  475. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/glimmer.js +0 -29
  476. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/graphql.js +0 -29
  477. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/html.js +0 -22
  478. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/markdown.js +0 -63
  479. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/meriyah.js +0 -4
  480. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/postcss.js +0 -54
  481. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/typescript.js +0 -20
  482. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/plugins/yaml.js +0 -160
  483. package/dist/src/web/frontend/node_modules/.prettier-ApZm3b7s/standalone.js +0 -34
  484. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/bin/react-scripts.js +0 -58
  485. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/env.js +0 -112
  486. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/getHttpsConfig.js +0 -74
  487. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/jest/babelTransform.js +0 -37
  488. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/jest/cssTransform.js +0 -22
  489. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/jest/fileTransform.js +0 -40
  490. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/modules.js +0 -142
  491. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/paths.js +0 -153
  492. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/webpack/persistentCache/createEnvironmentHash.js +0 -9
  493. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/webpack.config.js +0 -796
  494. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/config/webpackDevServer.config.js +0 -135
  495. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/scripts/build.js +0 -225
  496. package/dist/src/web/frontend/node_modules/.react-scripts-OTANyoRb/scripts/eject.js +0 -340
@@ -1,25 +1,46 @@
1
1
  /**
2
2
  * Hive Mind command for Claude-Flow v2.0.0
3
3
  * Advanced swarm intelligence with collective decision-making
4
- */ import { existsSync, mkdirSync } from "fs";
5
- import { writeFile } from "node:fs/promises";
6
- import path from "path";
7
- import inquirer from "inquirer";
8
- import chalk from "chalk";
9
- import ora from "ora";
10
- import { cwd, exit, mkdirAsync } from "../node-compat.js";
11
- import { warnNonInteractive } from "../utils/interactive-detector.js";
12
- import { safeInteractive } from "../utils/safe-interactive.js";
4
+ */
5
+
6
+ import { spawn } from 'child_process';
7
+ import { existsSync, mkdirSync } from 'fs';
8
+ import { writeFile, readFile } from 'fs/promises';
9
+ import path from 'path';
10
+ import readline from 'readline';
11
+ import inquirer from 'inquirer';
12
+ import chalk from 'chalk';
13
+ import ora from 'ora';
14
+ import { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';
15
+ import {
16
+ isInteractive,
17
+ isRawModeSupported,
18
+ warnNonInteractive,
19
+ checkNonInteractiveAuth,
20
+ } from '../utils/interactive-detector.js';
21
+ import {
22
+ safeInteractive,
23
+ nonInteractiveProgress,
24
+ nonInteractiveSelect,
25
+ } from '../utils/safe-interactive.js';
26
+
13
27
  // Import SQLite for persistence
14
- import Database from "better-sqlite3";
15
- import { HiveMindCore } from "./hive-mind/core.js";
16
- import { QueenCoordinator } from "./hive-mind/queen.js";
17
- import { CollectiveMemory } from "./hive-mind/memory.js";
18
- import { SwarmCommunication } from "./hive-mind/communication.js";
19
- import { HiveMindSessionManager } from "./hive-mind/session-manager.js";
20
- import { createAutoSaveMiddleware } from "./hive-mind/auto-save-middleware.js";
28
+ import Database from 'better-sqlite3';
29
+
30
+ // Import help formatter
31
+ import { HelpFormatter } from '../help-formatter.js';
32
+
33
+ // Import MCP tool wrappers
34
+ import { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';
35
+ import { HiveMindCore } from './hive-mind/core.js';
36
+ import { QueenCoordinator } from './hive-mind/queen.js';
37
+ import { CollectiveMemory } from './hive-mind/memory.js';
38
+ import { SwarmCommunication } from './hive-mind/communication.js';
39
+ import { HiveMindSessionManager } from './hive-mind/session-manager.js';
40
+ import { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';
41
+
21
42
  function showHiveMindHelp() {
22
- console.log(`
43
+ console.log(`
23
44
  ${chalk.yellow('🧠 Claude Flow Hive Mind System')}
24
45
 
25
46
  ${chalk.bold('USAGE:')}
@@ -93,23 +114,26 @@ ${chalk.bold('For more information:')}
93
114
  ${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}
94
115
  `);
95
116
  }
117
+
96
118
  /**
97
119
  * Initialize hive mind system
98
- */ async function initHiveMind(flags) {
99
- const spinner = ora('Initializing Hive Mind system...').start();
100
- try {
101
- // Create hive mind directory structure
102
- const hiveMindDir = path.join(cwd(), '.hive-mind');
103
- if (!existsSync(hiveMindDir)) {
104
- mkdirSync(hiveMindDir, {
105
- recursive: true
106
- });
107
- }
108
- // Initialize SQLite database
109
- const dbPath = path.join(hiveMindDir, 'hive.db');
110
- const db = new Database(dbPath);
111
- // Create tables
112
- db.exec(`
120
+ */
121
+ async function initHiveMind(flags) {
122
+ const spinner = ora('Initializing Hive Mind system...').start();
123
+
124
+ try {
125
+ // Create hive mind directory structure
126
+ const hiveMindDir = path.join(cwd(), '.hive-mind');
127
+ if (!existsSync(hiveMindDir)) {
128
+ mkdirSync(hiveMindDir, { recursive: true });
129
+ }
130
+
131
+ // Initialize SQLite database
132
+ const dbPath = path.join(hiveMindDir, 'hive.db');
133
+ const db = new Database(dbPath);
134
+
135
+ // Create tables
136
+ db.exec(`
113
137
  CREATE TABLE IF NOT EXISTS swarms (
114
138
  id TEXT PRIMARY KEY,
115
139
  name TEXT NOT NULL,
@@ -174,108 +198,103 @@ ${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}
174
198
  FOREIGN KEY (swarm_id) REFERENCES swarms(id)
175
199
  );
176
200
  `);
177
- db.close();
178
- // Create configuration file
179
- const config = {
180
- version: '2.0.0',
181
- initialized: new Date().toISOString(),
182
- defaults: {
183
- queenType: 'strategic',
184
- maxWorkers: 8,
185
- consensusAlgorithm: 'majority',
186
- memorySize: 100,
187
- autoScale: true,
188
- encryption: false
189
- },
190
- mcpTools: {
191
- enabled: true,
192
- parallel: true,
193
- timeout: 60000
194
- }
195
- };
196
- await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));
197
- spinner.succeed('Hive Mind system initialized successfully!');
198
- console.log('\n' + chalk.green('✓') + ' Created .hive-mind directory');
199
- console.log(chalk.green('') + ' Initialized SQLite database');
200
- console.log(chalk.green('✓') + ' Created configuration file');
201
- console.log('\n' + chalk.yellow('Next steps:'));
202
- console.log(' 1. Run ' + chalk.cyan('claude-flow-novice hive-mind spawn') + ' to create your first swarm');
203
- console.log(' 2. Use ' + chalk.cyan('claude-flow-novice hive-mind wizard') + ' for interactive setup');
204
- } catch (error) {
205
- spinner.fail('Failed to initialize Hive Mind system');
206
- console.error(chalk.red('Error:'), error.message);
207
- exit(1);
208
- }
201
+
202
+ db.close();
203
+
204
+ // Create configuration file
205
+ const config = {
206
+ version: '2.0.0',
207
+ initialized: new Date().toISOString(),
208
+ defaults: {
209
+ queenType: 'strategic',
210
+ maxWorkers: 8,
211
+ consensusAlgorithm: 'majority',
212
+ memorySize: 100,
213
+ autoScale: true,
214
+ encryption: false,
215
+ },
216
+ mcpTools: {
217
+ enabled: true,
218
+ parallel: true,
219
+ timeout: 60000,
220
+ },
221
+ };
222
+
223
+ await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));
224
+
225
+ spinner.succeed('Hive Mind system initialized successfully!');
226
+
227
+ console.log('\n' + chalk.green('') + ' Created .hive-mind directory');
228
+ console.log(chalk.green('✓') + ' Initialized SQLite database');
229
+ console.log(chalk.green('✓') + ' Created configuration file');
230
+ console.log('\n' + chalk.yellow('Next steps:'));
231
+ console.log(
232
+ ' 1. Run ' + chalk.cyan('claude-flow-novice hive-mind spawn') + ' to create your first swarm',
233
+ );
234
+ console.log(
235
+ ' 2. Use ' + chalk.cyan('claude-flow-novice hive-mind wizard') + ' for interactive setup',
236
+ );
237
+ } catch (error) {
238
+ spinner.fail('Failed to initialize Hive Mind system');
239
+ console.error(chalk.red('Error:'), error.message);
240
+ exit(1);
241
+ }
209
242
  }
243
+
210
244
  /**
211
245
  * Interactive wizard for hive mind operations
212
- */ // Wrapped wizard function that handles non-interactive environments
213
- const hiveMindWizard = safeInteractive(// Interactive version
214
- async function(flags = {}) {
246
+ */
247
+ // Wrapped wizard function that handles non-interactive environments
248
+ const hiveMindWizard = safeInteractive(
249
+ // Interactive version
250
+ async function (flags = {}) {
215
251
  console.log(chalk.yellow('\n🧙 Hive Mind Interactive Wizard\n'));
252
+
216
253
  const { action } = await inquirer.prompt([
217
- {
218
- type: 'list',
219
- name: 'action',
220
- message: 'What would you like to do?',
221
- choices: [
222
- {
223
- name: '🐝 Create new swarm',
224
- value: 'spawn'
225
- },
226
- {
227
- name: '📊 View swarm status',
228
- value: 'status'
229
- },
230
- {
231
- name: '🧠 Manage collective memory',
232
- value: 'memory'
233
- },
234
- {
235
- name: '🤝 View consensus decisions',
236
- value: 'consensus'
237
- },
238
- {
239
- name: '📈 Performance metrics',
240
- value: 'metrics'
241
- },
242
- {
243
- name: '🔧 Configure hive mind',
244
- value: 'config'
245
- },
246
- {
247
- name: '❌ Exit',
248
- value: 'exit'
249
- }
250
- ]
251
- }
254
+ {
255
+ type: 'list',
256
+ name: 'action',
257
+ message: 'What would you like to do?',
258
+ choices: [
259
+ { name: '🐝 Create new swarm', value: 'spawn' },
260
+ { name: '📊 View swarm status', value: 'status' },
261
+ { name: '🧠 Manage collective memory', value: 'memory' },
262
+ { name: '🤝 View consensus decisions', value: 'consensus' },
263
+ { name: '📈 Performance metrics', value: 'metrics' },
264
+ { name: '🔧 Configure hive mind', value: 'config' },
265
+ { name: '❌ Exit', value: 'exit' },
266
+ ],
267
+ },
252
268
  ]);
253
- switch(action){
254
- case 'spawn':
255
- await spawnSwarmWizard();
256
- break;
257
- case 'status':
258
- await showStatus({});
259
- break;
260
- case 'memory':
261
- await manageMemoryWizard();
262
- break;
263
- case 'consensus':
264
- await showConsensus({});
265
- break;
266
- case 'metrics':
267
- await showMetrics({});
268
- break;
269
- case 'config':
270
- await configureWizard();
271
- break;
272
- case 'exit':
273
- console.log(chalk.gray('Exiting wizard...'));
274
- break;
269
+
270
+ switch (action) {
271
+ case 'spawn':
272
+ await spawnSwarmWizard();
273
+ break;
274
+ case 'status':
275
+ await showStatus({});
276
+ break;
277
+ case 'memory':
278
+ await manageMemoryWizard();
279
+ break;
280
+ case 'consensus':
281
+ await showConsensus({});
282
+ break;
283
+ case 'metrics':
284
+ await showMetrics({});
285
+ break;
286
+ case 'config':
287
+ await configureWizard();
288
+ break;
289
+ case 'exit':
290
+ console.log(chalk.gray('Exiting wizard...'));
291
+ break;
275
292
  }
276
- }, // Non-interactive fallback
277
- async function(flags = {}) {
293
+ },
294
+ // Non-interactive fallback
295
+ async function (flags = {}) {
278
296
  console.log(chalk.yellow('\n🧙 Hive Mind - Non-Interactive Mode\n'));
297
+
279
298
  // Default to creating a swarm with sensible defaults
280
299
  console.log(chalk.cyan('Creating new swarm with default settings...'));
281
300
  console.log(chalk.gray('Use command-line flags to customize:'));
@@ -283,277 +302,251 @@ async function(flags = {}) {
283
302
  console.log(chalk.gray(' --queen-type strategic Set queen type'));
284
303
  console.log(chalk.gray(' --max-workers 8 Set worker count'));
285
304
  console.log();
305
+
286
306
  const objective = flags.objective || 'General task coordination';
287
307
  const config = {
288
- name: flags.name || `swarm-${Date.now()}`,
289
- queenType: flags.queenType || flags['queen-type'] || 'strategic',
290
- maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
291
- consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
292
- autoScale: flags.autoScale || flags['auto-scale'] || false,
293
- namespace: flags.namespace || 'default',
294
- verbose: flags.verbose || false,
295
- encryption: flags.encryption || false
308
+ name: flags.name || `swarm-${Date.now()}`,
309
+ queenType: flags.queenType || flags['queen-type'] || 'strategic',
310
+ maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
311
+ consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
312
+ autoScale: flags.autoScale || flags['auto-scale'] || false,
313
+ namespace: flags.namespace || 'default',
314
+ verbose: flags.verbose || false,
315
+ encryption: flags.encryption || false,
296
316
  };
297
- await spawnSwarm([
298
- objective
299
- ], {
300
- ...flags,
301
- name: config.name,
302
- queenType: config.queenType,
303
- maxWorkers: config.maxWorkers,
304
- consensusAlgorithm: config.consensusAlgorithm,
305
- autoScale: config.autoScale,
306
- encryption: config.encryption,
307
- nonInteractive: true
317
+
318
+ await spawnSwarm([objective], {
319
+ ...flags,
320
+ name: config.name,
321
+ queenType: config.queenType,
322
+ maxWorkers: config.maxWorkers,
323
+ consensusAlgorithm: config.consensusAlgorithm,
324
+ autoScale: config.autoScale,
325
+ encryption: config.encryption,
326
+ nonInteractive: true,
308
327
  });
309
- });
328
+ },
329
+ );
330
+
310
331
  /**
311
332
  * Spawn swarm wizard
312
- */ async function spawnSwarmWizard() {
313
- const answers = await inquirer.prompt([
314
- {
315
- type: 'input',
316
- name: 'objective',
317
- message: 'What is the swarm objective?',
318
- validate: (input)=>input.trim().length > 0 || 'Please enter an objective'
319
- },
320
- {
321
- type: 'input',
322
- name: 'name',
323
- message: 'Swarm name (optional):',
324
- default: (answers)=>`swarm-${Date.now()}`
325
- },
326
- {
327
- type: 'list',
328
- name: 'queenType',
329
- message: 'Select queen coordinator type:',
330
- choices: [
331
- {
332
- name: 'Strategic - High-level planning and coordination',
333
- value: 'strategic'
334
- },
335
- {
336
- name: 'Tactical - Detailed task management',
337
- value: 'tactical'
338
- },
339
- {
340
- name: 'Adaptive - Learns and adapts strategies',
341
- value: 'adaptive'
342
- }
343
- ],
344
- default: 'strategic'
345
- },
346
- {
347
- type: 'number',
348
- name: 'maxWorkers',
349
- message: 'Maximum number of worker agents:',
350
- default: 8,
351
- validate: (input)=>input > 0 && input <= 20 || 'Please enter a number between 1 and 20'
352
- },
353
- {
354
- type: 'checkbox',
355
- name: 'workerTypes',
356
- message: 'Select worker agent types:',
357
- choices: [
358
- {
359
- name: 'Researcher',
360
- value: 'researcher',
361
- checked: true
362
- },
363
- {
364
- name: 'Coder',
365
- value: 'coder',
366
- checked: true
367
- },
368
- {
369
- name: 'Analyst',
370
- value: 'analyst',
371
- checked: true
372
- },
373
- {
374
- name: 'Tester',
375
- value: 'tester',
376
- checked: true
377
- },
378
- {
379
- name: 'Architect',
380
- value: 'architect'
381
- },
382
- {
383
- name: 'Reviewer',
384
- value: 'reviewer'
385
- },
386
- {
387
- name: 'Optimizer',
388
- value: 'optimizer'
389
- },
390
- {
391
- name: 'Documenter',
392
- value: 'documenter'
393
- }
394
- ]
395
- },
396
- {
397
- type: 'list',
398
- name: 'consensusAlgorithm',
399
- message: 'Consensus algorithm for decisions:',
400
- choices: [
401
- {
402
- name: 'Majority - Simple majority voting',
403
- value: 'majority'
404
- },
405
- {
406
- name: 'Weighted - Expertise-weighted voting',
407
- value: 'weighted'
408
- },
409
- {
410
- name: 'Byzantine - Fault-tolerant consensus',
411
- value: 'byzantine'
412
- }
413
- ],
414
- default: 'majority'
415
- },
416
- {
417
- type: 'confirm',
418
- name: 'autoScale',
419
- message: 'Enable auto-scaling?',
420
- default: true
421
- },
422
- {
423
- type: 'confirm',
424
- name: 'monitor',
425
- message: 'Launch monitoring dashboard?',
426
- default: true
427
- }
428
- ]);
429
- // Spawn the swarm with collected parameters
430
- await spawnSwarm([
431
- answers.objective
432
- ], {
433
- name: answers.name,
434
- queenType: answers.queenType,
435
- 'queen-type': answers.queenType,
436
- maxWorkers: answers.maxWorkers,
437
- 'max-workers': answers.maxWorkers,
438
- workerTypes: answers.workerTypes.join(','),
439
- consensus: answers.consensusAlgorithm,
440
- autoScale: answers.autoScale,
441
- 'auto-scale': answers.autoScale,
442
- monitor: answers.monitor,
443
- namespace: answers.namespace || 'default',
444
- verbose: answers.verbose || false
445
- });
333
+ */
334
+ async function spawnSwarmWizard() {
335
+ const answers = await inquirer.prompt([
336
+ {
337
+ type: 'input',
338
+ name: 'objective',
339
+ message: 'What is the swarm objective?',
340
+ validate: (input) => input.trim().length > 0 || 'Please enter an objective',
341
+ },
342
+ {
343
+ type: 'input',
344
+ name: 'name',
345
+ message: 'Swarm name (optional):',
346
+ default: (answers) => `swarm-${Date.now()}`,
347
+ },
348
+ {
349
+ type: 'list',
350
+ name: 'queenType',
351
+ message: 'Select queen coordinator type:',
352
+ choices: [
353
+ { name: 'Strategic - High-level planning and coordination', value: 'strategic' },
354
+ { name: 'Tactical - Detailed task management', value: 'tactical' },
355
+ { name: 'Adaptive - Learns and adapts strategies', value: 'adaptive' },
356
+ ],
357
+ default: 'strategic',
358
+ },
359
+ {
360
+ type: 'number',
361
+ name: 'maxWorkers',
362
+ message: 'Maximum number of worker agents:',
363
+ default: 8,
364
+ validate: (input) => (input > 0 && input <= 20) || 'Please enter a number between 1 and 20',
365
+ },
366
+ {
367
+ type: 'checkbox',
368
+ name: 'workerTypes',
369
+ message: 'Select worker agent types:',
370
+ choices: [
371
+ { name: 'Researcher', value: 'researcher', checked: true },
372
+ { name: 'Coder', value: 'coder', checked: true },
373
+ { name: 'Analyst', value: 'analyst', checked: true },
374
+ { name: 'Tester', value: 'tester', checked: true },
375
+ { name: 'Architect', value: 'architect' },
376
+ { name: 'Reviewer', value: 'reviewer' },
377
+ { name: 'Optimizer', value: 'optimizer' },
378
+ { name: 'Documenter', value: 'documenter' },
379
+ ],
380
+ },
381
+ {
382
+ type: 'list',
383
+ name: 'consensusAlgorithm',
384
+ message: 'Consensus algorithm for decisions:',
385
+ choices: [
386
+ { name: 'Majority - Simple majority voting', value: 'majority' },
387
+ { name: 'Weighted - Expertise-weighted voting', value: 'weighted' },
388
+ { name: 'Byzantine - Fault-tolerant consensus', value: 'byzantine' },
389
+ ],
390
+ default: 'majority',
391
+ },
392
+ {
393
+ type: 'confirm',
394
+ name: 'autoScale',
395
+ message: 'Enable auto-scaling?',
396
+ default: true,
397
+ },
398
+ {
399
+ type: 'confirm',
400
+ name: 'monitor',
401
+ message: 'Launch monitoring dashboard?',
402
+ default: true,
403
+ },
404
+ ]);
405
+
406
+ // Spawn the swarm with collected parameters
407
+ await spawnSwarm([answers.objective], {
408
+ name: answers.name,
409
+ queenType: answers.queenType,
410
+ 'queen-type': answers.queenType,
411
+ maxWorkers: answers.maxWorkers,
412
+ 'max-workers': answers.maxWorkers,
413
+ workerTypes: answers.workerTypes.join(','),
414
+ consensus: answers.consensusAlgorithm,
415
+ autoScale: answers.autoScale,
416
+ 'auto-scale': answers.autoScale,
417
+ monitor: answers.monitor,
418
+ namespace: answers.namespace || 'default',
419
+ verbose: answers.verbose || false,
420
+ });
446
421
  }
422
+
447
423
  /**
448
424
  * Spawn a hive mind swarm
449
- */ async function spawnSwarm(args, flags) {
450
- const objective = args.join(' ').trim();
451
- // Check for non-interactive mode FIRST
452
- const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
453
- if (!objective && !flags.wizard) {
454
- if (isNonInteractive) {
455
- console.error(chalk.red('Error: Objective required in non-interactive mode'));
456
- console.log('Usage: claude-flow-novice hive-mind spawn "Your objective" --non-interactive');
457
- } else {
458
- console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));
459
- console.log('Example: claude-flow-novice hive-mind spawn "Build REST API"');
460
- }
461
- return;
462
- }
463
- // Log non-interactive mode status
464
- if (isNonInteractive && flags.verbose) {
465
- console.log(chalk.cyan('🤖 Running in non-interactive mode'));
466
- }
467
- // Validate parameters
468
- if (flags.verbose) {
469
- console.log(chalk.gray('🔍 Debug: Parsed flags:'));
470
- console.log(chalk.gray(JSON.stringify(flags, null, 2)));
425
+ */
426
+ async function spawnSwarm(args, flags) {
427
+ const objective = args.join(' ').trim();
428
+
429
+ // Check for non-interactive mode FIRST
430
+ const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
431
+
432
+ if (!objective && !flags.wizard) {
433
+ if (isNonInteractive) {
434
+ console.error(chalk.red('Error: Objective required in non-interactive mode'));
435
+ console.log('Usage: claude-flow-novice hive-mind spawn "Your objective" --non-interactive');
436
+ } else {
437
+ console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));
438
+ console.log('Example: claude-flow-novice hive-mind spawn "Build REST API"');
471
439
  }
472
- // Validate queen type
473
- const validQueenTypes = [
474
- 'strategic',
475
- 'tactical',
476
- 'adaptive'
477
- ];
478
- const queenType = flags.queenType || flags['queen-type'] || 'strategic';
479
- if (!validQueenTypes.includes(queenType)) {
480
- console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));
481
- return;
482
- }
483
- // Validate max workers
484
- const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');
485
- if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {
486
- console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));
487
- return;
440
+ return;
441
+ }
442
+
443
+ // Log non-interactive mode status
444
+ if (isNonInteractive && flags.verbose) {
445
+ console.log(chalk.cyan('🤖 Running in non-interactive mode'));
446
+ }
447
+
448
+ // Validate parameters
449
+ if (flags.verbose) {
450
+ console.log(chalk.gray('🔍 Debug: Parsed flags:'));
451
+ console.log(chalk.gray(JSON.stringify(flags, null, 2)));
452
+ }
453
+
454
+ // Validate queen type
455
+ const validQueenTypes = ['strategic', 'tactical', 'adaptive'];
456
+ const queenType = flags.queenType || flags['queen-type'] || 'strategic';
457
+ if (!validQueenTypes.includes(queenType)) {
458
+ console.error(
459
+ chalk.red(
460
+ `Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`,
461
+ ),
462
+ );
463
+ return;
464
+ }
465
+
466
+ // Validate max workers
467
+ const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');
468
+ if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {
469
+ console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));
470
+ return;
471
+ }
472
+
473
+ // Validate consensus algorithm
474
+ const validConsensusTypes = ['majority', 'weighted', 'byzantine'];
475
+ const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';
476
+ if (!validConsensusTypes.includes(consensusAlgorithm)) {
477
+ console.error(
478
+ chalk.red(
479
+ `Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`,
480
+ ),
481
+ );
482
+ return;
483
+ }
484
+
485
+ const spinner = ora('Spawning Hive Mind swarm...').start();
486
+
487
+ try {
488
+ // Initialize hive mind core with error handling
489
+ let hiveMind;
490
+ try {
491
+ spinner.text = 'Initializing Hive Mind Core...';
492
+ hiveMind = new HiveMindCore({
493
+ objective,
494
+ name: flags.name || `hive-${Date.now()}`,
495
+ queenType: flags.queenType || flags['queen-type'] || 'strategic',
496
+ maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
497
+ consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
498
+ autoScale:
499
+ flags.autoScale !== undefined
500
+ ? flags.autoScale
501
+ : flags['auto-scale'] !== undefined
502
+ ? flags['auto-scale']
503
+ : true,
504
+ namespace: flags.namespace || 'default',
505
+ encryption: flags.encryption || false,
506
+ });
507
+ } catch (error) {
508
+ console.error('HiveMindCore initialization failed:', error);
509
+ throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);
488
510
  }
489
- // Validate consensus algorithm
490
- const validConsensusTypes = [
491
- 'majority',
492
- 'weighted',
493
- 'byzantine'
494
- ];
495
- const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';
496
- if (!validConsensusTypes.includes(consensusAlgorithm)) {
497
- console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));
498
- return;
511
+
512
+ spinner.text = 'Setting up database connection...';
513
+ // Initialize database connection
514
+ const dbDir = path.join(cwd(), '.hive-mind');
515
+ const dbPath = path.join(dbDir, 'hive.db');
516
+
517
+ // Ensure .hive-mind directory exists
518
+ if (!existsSync(dbDir)) {
519
+ mkdirSync(dbDir, { recursive: true });
499
520
  }
500
- const spinner = ora('Spawning Hive Mind swarm...').start();
521
+
522
+ // Check if database file exists and try to create a clean one if needed
523
+ let db;
501
524
  try {
502
- // Initialize hive mind core with error handling
503
- let hiveMind;
504
- try {
505
- spinner.text = 'Initializing Hive Mind Core...';
506
- hiveMind = new HiveMindCore({
507
- objective,
508
- name: flags.name || `hive-${Date.now()}`,
509
- queenType: flags.queenType || flags['queen-type'] || 'strategic',
510
- maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
511
- consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
512
- autoScale: flags.autoScale !== undefined ? flags.autoScale : flags['auto-scale'] !== undefined ? flags['auto-scale'] : true,
513
- namespace: flags.namespace || 'default',
514
- encryption: flags.encryption || false
515
- });
516
- } catch (error) {
517
- console.error('HiveMindCore initialization failed:', error);
518
- throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);
519
- }
520
- spinner.text = 'Setting up database connection...';
521
- // Initialize database connection
522
- const dbDir = path.join(cwd(), '.hive-mind');
523
- const dbPath = path.join(dbDir, 'hive.db');
524
- // Ensure .hive-mind directory exists
525
- if (!existsSync(dbDir)) {
526
- mkdirSync(dbDir, {
527
- recursive: true
528
- });
529
- }
530
- // Check if database file exists and try to create a clean one if needed
531
- let db;
525
+ spinner.text = 'Creating database connection...';
526
+ db = new Database(dbPath);
527
+ // Test the database with a simple query
528
+ db.prepare('SELECT 1').get();
529
+ spinner.text = 'Database connection established';
530
+ } catch (error) {
531
+ console.warn('Database issue detected, recreating...', error.message);
532
+ spinner.text = 'Recreating database...';
533
+ // Remove corrupted database
534
+ if (existsSync(dbPath)) {
532
535
  try {
533
- spinner.text = 'Creating database connection...';
534
- db = new Database(dbPath);
535
- // Test the database with a simple query
536
- db.prepare('SELECT 1').get();
537
- spinner.text = 'Database connection established';
538
- } catch (error) {
539
- console.warn('Database issue detected, recreating...', error.message);
540
- spinner.text = 'Recreating database...';
541
- // Remove corrupted database
542
- if (existsSync(dbPath)) {
543
- try {
544
- const fs = await import("fs");
545
- fs.unlinkSync(dbPath);
546
- } catch (e) {
547
- console.warn('Could not remove corrupted database:', e.message);
548
- }
549
- }
550
- // Create new database
551
- db = new Database(dbPath);
536
+ const fs = await import('fs');
537
+ fs.unlinkSync(dbPath);
538
+ } catch (e) {
539
+ console.warn('Could not remove corrupted database:', e.message);
552
540
  }
553
- // Initialize database schema if not exists
554
- spinner.text = 'Creating database schema...';
555
- try {
556
- db.exec(`
541
+ }
542
+ // Create new database
543
+ db = new Database(dbPath);
544
+ }
545
+
546
+ // Initialize database schema if not exists
547
+ spinner.text = 'Creating database schema...';
548
+ try {
549
+ db.exec(`
557
550
  CREATE TABLE IF NOT EXISTS swarms (
558
551
  id TEXT PRIMARY KEY,
559
552
  name TEXT NOT NULL,
@@ -656,326 +649,356 @@ async function(flags = {}) {
656
649
  FOREIGN KEY (session_id) REFERENCES sessions(id)
657
650
  );
658
651
  `);
659
- spinner.text = 'Database schema created successfully';
660
- } catch (error) {
661
- console.error('Database schema creation failed:', error);
662
- throw new Error(`Failed to create database schema: ${error.message}`);
663
- }
664
- // Create swarm record with safe ID generation
665
- spinner.text = 'Creating swarm record...';
666
- const timestamp = Date.now();
667
- const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr
668
- const swarmId = `swarm-${timestamp}-${randomPart}`;
669
- try {
670
- db.prepare(`
652
+ spinner.text = 'Database schema created successfully';
653
+ } catch (error) {
654
+ console.error('Database schema creation failed:', error);
655
+ throw new Error(`Failed to create database schema: ${error.message}`);
656
+ }
657
+
658
+ // Create swarm record with safe ID generation
659
+ spinner.text = 'Creating swarm record...';
660
+ const timestamp = Date.now();
661
+ const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr
662
+ const swarmId = `swarm-${timestamp}-${randomPart}`;
663
+ try {
664
+ db.prepare(
665
+ `
671
666
  INSERT INTO swarms (id, name, objective, queen_type)
672
667
  VALUES (?, ?, ?, ?)
673
- `).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);
674
- } catch (error) {
675
- console.error('Failed to create swarm record:', error);
676
- throw new Error(`Failed to create swarm record: ${error.message}`);
677
- }
678
- // Create session for this swarm
679
- spinner.text = 'Creating session tracking...';
680
- const sessionManager = new HiveMindSessionManager();
681
- const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {
682
- queenType: hiveMind.config.queenType,
683
- maxWorkers: hiveMind.config.maxWorkers,
684
- consensusAlgorithm: hiveMind.config.consensusAlgorithm,
685
- autoScale: hiveMind.config.autoScale,
686
- encryption: hiveMind.config.encryption,
687
- workerTypes: flags.workerTypes
688
- });
689
- spinner.text = 'Session tracking established...';
690
- // Initialize auto-save middleware (use the same session manager)
691
- const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {
692
- saveInterval: 30000,
693
- autoStart: true
694
- });
695
- // Close session manager after auto-save is set up
696
- // sessionManager.close(); // Don't close yet as auto-save needs it
697
- // Track initial swarm creation
698
- autoSave.trackChange('swarm_created', {
699
- swarmId,
700
- swarmName: hiveMind.config.name,
701
- objective,
702
- workerCount: hiveMind.config.maxWorkers
703
- });
704
- spinner.text = 'Initializing Queen coordinator...';
705
- // Initialize Queen
706
- const queen = new QueenCoordinator({
707
- swarmId,
708
- type: hiveMind.config.queenType,
709
- objective
710
- });
711
- // Spawn Queen agent
712
- const queenAgent = {
713
- id: `queen-${swarmId}`,
714
- swarmId,
715
- name: 'Queen Coordinator',
716
- type: 'coordinator',
717
- role: 'queen',
718
- status: 'active',
719
- capabilities: JSON.stringify([
720
- 'coordination',
721
- 'planning',
722
- 'decision-making'
723
- ])
724
- };
725
- db.prepare(`
668
+ `,
669
+ ).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);
670
+ } catch (error) {
671
+ console.error('Failed to create swarm record:', error);
672
+ throw new Error(`Failed to create swarm record: ${error.message}`);
673
+ }
674
+
675
+ // Create session for this swarm
676
+ spinner.text = 'Creating session tracking...';
677
+ const sessionManager = new HiveMindSessionManager();
678
+ const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {
679
+ queenType: hiveMind.config.queenType,
680
+ maxWorkers: hiveMind.config.maxWorkers,
681
+ consensusAlgorithm: hiveMind.config.consensusAlgorithm,
682
+ autoScale: hiveMind.config.autoScale,
683
+ encryption: hiveMind.config.encryption,
684
+ workerTypes: flags.workerTypes,
685
+ });
686
+
687
+ spinner.text = 'Session tracking established...';
688
+
689
+ // Initialize auto-save middleware (use the same session manager)
690
+ const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {
691
+ saveInterval: 30000, // Save every 30 seconds
692
+ autoStart: true,
693
+ });
694
+
695
+ // Close session manager after auto-save is set up
696
+ // sessionManager.close(); // Don't close yet as auto-save needs it
697
+
698
+ // Track initial swarm creation
699
+ autoSave.trackChange('swarm_created', {
700
+ swarmId,
701
+ swarmName: hiveMind.config.name,
702
+ objective,
703
+ workerCount: hiveMind.config.maxWorkers,
704
+ });
705
+
706
+ spinner.text = 'Initializing Queen coordinator...';
707
+
708
+ // Initialize Queen
709
+ const queen = new QueenCoordinator({
710
+ swarmId,
711
+ type: hiveMind.config.queenType,
712
+ objective,
713
+ });
714
+
715
+ // Spawn Queen agent
716
+ const queenAgent = {
717
+ id: `queen-${swarmId}`,
718
+ swarmId,
719
+ name: 'Queen Coordinator',
720
+ type: 'coordinator',
721
+ role: 'queen',
722
+ status: 'active',
723
+ capabilities: JSON.stringify(['coordination', 'planning', 'decision-making']),
724
+ };
725
+
726
+ db.prepare(
727
+ `
726
728
  INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)
727
729
  VALUES (?, ?, ?, ?, ?, ?, ?)
728
- `).run(...Object.values(queenAgent));
729
- spinner.text = 'Spawning worker agents...';
730
- // Determine worker types
731
- const workerTypes = flags.workerTypes ? flags.workerTypes.split(',') : [
732
- 'researcher',
733
- 'coder',
734
- 'analyst',
735
- 'tester'
736
- ];
737
- // Spawn worker agents
738
- const workers = [];
739
- for(let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++){
740
- const workerType = workerTypes[i % workerTypes.length];
741
- const workerId = `worker-${swarmId}-${i}`;
742
- const worker = {
743
- id: workerId,
744
- swarmId,
745
- name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,
746
- type: workerType,
747
- role: 'worker',
748
- status: 'idle',
749
- capabilities: JSON.stringify(getAgentCapabilities(workerType))
750
- };
751
- workers.push(worker);
752
- db.prepare(`
730
+ `,
731
+ ).run(...Object.values(queenAgent));
732
+
733
+ spinner.text = 'Spawning worker agents...';
734
+
735
+ // Determine worker types
736
+ const workerTypes = flags.workerTypes
737
+ ? flags.workerTypes.split(',')
738
+ : ['researcher', 'coder', 'analyst', 'tester'];
739
+
740
+ // Spawn worker agents
741
+ const workers = [];
742
+ for (let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++) {
743
+ const workerType = workerTypes[i % workerTypes.length];
744
+ const workerId = `worker-${swarmId}-${i}`;
745
+
746
+ const worker = {
747
+ id: workerId,
748
+ swarmId,
749
+ name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,
750
+ type: workerType,
751
+ role: 'worker',
752
+ status: 'idle',
753
+ capabilities: JSON.stringify(getAgentCapabilities(workerType)),
754
+ };
755
+
756
+ workers.push(worker);
757
+
758
+ db.prepare(
759
+ `
753
760
  INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)
754
761
  VALUES (?, ?, ?, ?, ?, ?, ?)
755
- `).run(...Object.values(worker));
756
- // Track agent spawning for auto-save
757
- autoSave.trackAgentActivity(workerId, 'spawned', {
758
- type: workerType,
759
- name: worker.name
760
- });
761
- }
762
- spinner.text = 'Initializing collective memory...';
763
- // Initialize collective memory
764
- const memory = new CollectiveMemory({
765
- swarmId,
766
- maxSize: flags.memorySize || 100
767
- });
768
- // Store initial context
769
- memory.store('objective', objective, 'context');
770
- memory.store('queen_type', hiveMind.config.queenType, 'config');
771
- memory.store('worker_count', workers.length, 'metrics');
772
- memory.store('session_id', sessionId, 'system');
773
- spinner.text = 'Establishing communication channels...';
774
- // Initialize communication system
775
- const communication = new SwarmCommunication({
776
- swarmId,
777
- encryption: hiveMind.config.encryption
778
- });
779
- db.close();
780
- spinner.succeed('Hive Mind swarm spawned successfully!');
781
- // Display swarm summary
782
- console.log('\n' + chalk.bold('🐝 Swarm Summary:'));
783
- console.log(chalk.gray('─'.repeat(50)));
784
- console.log(chalk.cyan('Swarm ID:'), swarmId);
785
- console.log(chalk.cyan('Session ID:'), sessionId);
786
- console.log(chalk.cyan('Name:'), hiveMind.config.name);
787
- console.log(chalk.cyan('Objective:'), objective);
788
- console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);
789
- console.log(chalk.cyan('Workers:'), workers.length);
790
- console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));
791
- console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);
792
- console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');
793
- console.log(chalk.gray('─'.repeat(50)));
794
- // Launch monitoring if requested
795
- if (flags.monitor) {
796
- console.log('\n' + chalk.yellow('Launching monitoring dashboard...'));
797
- // TODO: Implement monitoring dashboard
798
- }
799
- // Enhanced coordination instructions with MCP tools
800
- console.log('\n' + chalk.green('') + ' Swarm is ready for coordination');
801
- console.log(chalk.gray('Use "claude-flow-novice hive-mind status" to view swarm activity'));
802
- console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));
803
- console.log(chalk.blue('💡 To pause:') + ' Press Ctrl+C to safely pause and resume later');
804
- console.log(chalk.blue('💡 To resume:') + ' claude-flow-novice hive-mind resume ' + sessionId);
805
- // Set up SIGINT handler for automatic session pausing
806
- let isExiting = false;
807
- const sigintHandler = async ()=>{
808
- if (isExiting) return;
809
- isExiting = true;
810
- console.log('\n\n' + chalk.yellow('⏸️ Pausing session...'));
811
- try {
812
- // Save current checkpoint using the existing session manager
813
- // const sessionManager = new HiveMindSessionManager(); // Use existing one
814
- // Create checkpoint data
815
- const checkpointData = {
816
- timestamp: new Date().toISOString(),
817
- swarmId,
818
- objective,
819
- workerCount: workers.length,
820
- workerTypes,
821
- status: 'paused_by_user',
822
- reason: 'User pressed Ctrl+C'
823
- };
824
- // Save checkpoint
825
- await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);
826
- // Pause the session
827
- await sessionManager.pauseSession(sessionId);
828
- // Close session manager
829
- sessionManager.close();
830
- console.log(chalk.green('✓') + ' Session paused successfully');
831
- console.log(chalk.cyan('\nTo resume this session, run:'));
832
- console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
833
- console.log();
834
- // Clean up auto-save if active
835
- if (global.autoSaveInterval) {
836
- clearInterval(global.autoSaveInterval);
837
- }
838
- process.exit(0);
839
- } catch (error) {
840
- console.error(chalk.red('Error pausing session:'), error.message);
841
- process.exit(1);
842
- }
762
+ `,
763
+ ).run(...Object.values(worker));
764
+
765
+ // Track agent spawning for auto-save
766
+ autoSave.trackAgentActivity(workerId, 'spawned', {
767
+ type: workerType,
768
+ name: worker.name,
769
+ });
770
+ }
771
+
772
+ spinner.text = 'Initializing collective memory...';
773
+
774
+ // Initialize collective memory
775
+ const memory = new CollectiveMemory({
776
+ swarmId,
777
+ maxSize: flags.memorySize || 100,
778
+ });
779
+
780
+ // Store initial context
781
+ memory.store('objective', objective, 'context');
782
+ memory.store('queen_type', hiveMind.config.queenType, 'config');
783
+ memory.store('worker_count', workers.length, 'metrics');
784
+ memory.store('session_id', sessionId, 'system');
785
+
786
+ spinner.text = 'Establishing communication channels...';
787
+
788
+ // Initialize communication system
789
+ const communication = new SwarmCommunication({
790
+ swarmId,
791
+ encryption: hiveMind.config.encryption,
792
+ });
793
+
794
+ db.close();
795
+
796
+ spinner.succeed('Hive Mind swarm spawned successfully!');
797
+
798
+ // Display swarm summary
799
+ console.log('\n' + chalk.bold('🐝 Swarm Summary:'));
800
+ console.log(chalk.gray('─'.repeat(50)));
801
+ console.log(chalk.cyan('Swarm ID:'), swarmId);
802
+ console.log(chalk.cyan('Session ID:'), sessionId);
803
+ console.log(chalk.cyan('Name:'), hiveMind.config.name);
804
+ console.log(chalk.cyan('Objective:'), objective);
805
+ console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);
806
+ console.log(chalk.cyan('Workers:'), workers.length);
807
+ console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));
808
+ console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);
809
+ console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');
810
+ console.log(chalk.gray(''.repeat(50)));
811
+
812
+ // Launch monitoring if requested
813
+ if (flags.monitor) {
814
+ console.log('\n' + chalk.yellow('Launching monitoring dashboard...'));
815
+ // TODO: Implement monitoring dashboard
816
+ }
817
+
818
+ // Enhanced coordination instructions with MCP tools
819
+ console.log('\n' + chalk.green('✓') + ' Swarm is ready for coordination');
820
+ console.log(chalk.gray('Use "claude-flow-novice hive-mind status" to view swarm activity'));
821
+ console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));
822
+ console.log(chalk.blue('💡 To pause:') + ' Press Ctrl+C to safely pause and resume later');
823
+ console.log(chalk.blue('💡 To resume:') + ' claude-flow-novice hive-mind resume ' + sessionId);
824
+
825
+ // Set up SIGINT handler for automatic session pausing
826
+ let isExiting = false;
827
+ const sigintHandler = async () => {
828
+ if (isExiting) return;
829
+ isExiting = true;
830
+
831
+ console.log('\n\n' + chalk.yellow('⏸️ Pausing session...'));
832
+
833
+ try {
834
+ // Save current checkpoint using the existing session manager
835
+ // const sessionManager = new HiveMindSessionManager(); // Use existing one
836
+
837
+ // Create checkpoint data
838
+ const checkpointData = {
839
+ timestamp: new Date().toISOString(),
840
+ swarmId,
841
+ objective,
842
+ workerCount: workers.length,
843
+ workerTypes,
844
+ status: 'paused_by_user',
845
+ reason: 'User pressed Ctrl+C',
843
846
  };
844
- // Register SIGINT handler
845
- process.on('SIGINT', sigintHandler);
846
- process.on('SIGTERM', sigintHandler);
847
- // Offer to spawn Claude Code instances with coordination instructions
848
- // Spawn Claude if --claude or --spawn flag is set
849
- if (flags.claude || flags.spawn) {
850
- await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);
851
- } else {
852
- console.log('\n' + chalk.blue('💡 Pro Tip:') + ' Add --claude to spawn coordinated Claude Code instances');
853
- console.log(chalk.gray(' claude-flow-novice hive-mind spawn "objective" --claude'));
854
- }
855
- } catch (error) {
856
- spinner.fail('Failed to spawn Hive Mind swarm');
857
- console.error(chalk.red('Error:'), error.message);
858
- // If error contains "sha3", provide specific guidance
859
- if (error.message.includes('sha3') || error.message.includes('SHA3')) {
860
- console.error('\n🔍 SHA3 Function Error Detected');
861
- console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');
862
- console.error('\nPossible solutions:');
863
- console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');
864
- console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');
865
- console.error('3. Check if any SQLite extensions are conflicting');
866
- console.error('\n🚨 Detailed error:');
867
- console.error(error.stack || error.message);
847
+
848
+ // Save checkpoint
849
+ await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);
850
+
851
+ // Pause the session
852
+ await sessionManager.pauseSession(sessionId);
853
+
854
+ // Close session manager
855
+ sessionManager.close();
856
+
857
+ console.log(chalk.green('✓') + ' Session paused successfully');
858
+ console.log(chalk.cyan('\nTo resume this session, run:'));
859
+ console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
860
+ console.log();
861
+
862
+ // Clean up auto-save if active
863
+ if (global.autoSaveInterval) {
864
+ clearInterval(global.autoSaveInterval);
868
865
  }
869
- exit(1);
866
+
867
+ process.exit(0);
868
+ } catch (error) {
869
+ console.error(chalk.red('Error pausing session:'), error.message);
870
+ process.exit(1);
871
+ }
872
+ };
873
+
874
+ // Register SIGINT handler
875
+ process.on('SIGINT', sigintHandler);
876
+ process.on('SIGTERM', sigintHandler);
877
+
878
+ // Offer to spawn Claude Code instances with coordination instructions
879
+ // Spawn Claude if --claude or --spawn flag is set
880
+ if (flags.claude || flags.spawn) {
881
+ await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);
882
+ } else {
883
+ console.log(
884
+ '\n' +
885
+ chalk.blue('💡 Pro Tip:') +
886
+ ' Add --claude to spawn coordinated Claude Code instances',
887
+ );
888
+ console.log(chalk.gray(' claude-flow-novice hive-mind spawn "objective" --claude'));
870
889
  }
890
+ } catch (error) {
891
+ spinner.fail('Failed to spawn Hive Mind swarm');
892
+ console.error(chalk.red('Error:'), error.message);
893
+
894
+ // If error contains "sha3", provide specific guidance
895
+ if (error.message.includes('sha3') || error.message.includes('SHA3')) {
896
+ console.error('\n🔍 SHA3 Function Error Detected');
897
+ console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');
898
+ console.error('\nPossible solutions:');
899
+ console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');
900
+ console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');
901
+ console.error('3. Check if any SQLite extensions are conflicting');
902
+ console.error('\n🚨 Detailed error:');
903
+ console.error(error.stack || error.message);
904
+ }
905
+
906
+ exit(1);
907
+ }
871
908
  }
909
+
872
910
  /**
873
911
  * Get agent capabilities based on type
874
- */ function getAgentCapabilities(type) {
875
- const capabilities = {
876
- researcher: [
877
- 'web-search',
878
- 'data-gathering',
879
- 'analysis',
880
- 'synthesis'
881
- ],
882
- coder: [
883
- 'code-generation',
884
- 'implementation',
885
- 'refactoring',
886
- 'debugging'
887
- ],
888
- analyst: [
889
- 'data-analysis',
890
- 'pattern-recognition',
891
- 'reporting',
892
- 'visualization'
893
- ],
894
- tester: [
895
- 'test-generation',
896
- 'quality-assurance',
897
- 'bug-detection',
898
- 'validation'
899
- ],
900
- architect: [
901
- 'system-design',
902
- 'architecture',
903
- 'planning',
904
- 'documentation'
905
- ],
906
- reviewer: [
907
- 'code-review',
908
- 'quality-check',
909
- 'feedback',
910
- 'improvement'
911
- ],
912
- optimizer: [
913
- 'performance-tuning',
914
- 'optimization',
915
- 'profiling',
916
- 'enhancement'
917
- ],
918
- documenter: [
919
- 'documentation',
920
- 'explanation',
921
- 'tutorial-creation',
922
- 'knowledge-base'
923
- ]
924
- };
925
- return capabilities[type] || [
926
- 'general'
927
- ];
912
+ */
913
+ function getAgentCapabilities(type) {
914
+ const capabilities = {
915
+ researcher: ['web-search', 'data-gathering', 'analysis', 'synthesis'],
916
+ coder: ['code-generation', 'implementation', 'refactoring', 'debugging'],
917
+ analyst: ['data-analysis', 'pattern-recognition', 'reporting', 'visualization'],
918
+ tester: ['test-generation', 'quality-assurance', 'bug-detection', 'validation'],
919
+ architect: ['system-design', 'architecture', 'planning', 'documentation'],
920
+ reviewer: ['code-review', 'quality-check', 'feedback', 'improvement'],
921
+ optimizer: ['performance-tuning', 'optimization', 'profiling', 'enhancement'],
922
+ documenter: ['documentation', 'explanation', 'tutorial-creation', 'knowledge-base'],
923
+ };
924
+
925
+ return capabilities[type] || ['general'];
928
926
  }
927
+
929
928
  /**
930
929
  * Show hive mind status
931
- */ async function showStatus(flags) {
932
- try {
933
- const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
934
- if (!existsSync(dbPath)) {
935
- console.error(chalk.red('Error: Hive Mind not initialized'));
936
- console.log('Run "claude-flow-novice hive-mind init" first');
937
- return;
938
- }
939
- const db = new Database(dbPath);
940
- // Get active swarms
941
- const swarms = db.prepare(`
930
+ */
931
+ async function showStatus(flags) {
932
+ try {
933
+ const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
934
+
935
+ if (!existsSync(dbPath)) {
936
+ console.error(chalk.red('Error: Hive Mind not initialized'));
937
+ console.log('Run "claude-flow-novice hive-mind init" first');
938
+ return;
939
+ }
940
+
941
+ const db = new Database(dbPath);
942
+
943
+ // Get active swarms
944
+ const swarms = db
945
+ .prepare(
946
+ `
942
947
  SELECT * FROM swarms
943
948
  WHERE status = 'active'
944
949
  ORDER BY created_at DESC
945
- `).all();
946
- if (swarms.length === 0) {
947
- console.log(chalk.gray('No active swarms found'));
948
- db.close();
949
- return;
950
- }
951
- console.log(chalk.bold('\n🐝 Active Hive Mind Swarms\n'));
952
- for (const swarm of swarms){
953
- console.log(chalk.yellow('═'.repeat(60)));
954
- console.log(chalk.cyan('Swarm:'), swarm.name);
955
- console.log(chalk.cyan('ID:'), swarm.id);
956
- console.log(chalk.cyan('Objective:'), swarm.objective);
957
- console.log(chalk.cyan('Queen Type:'), swarm.queen_type);
958
- console.log(chalk.cyan('Status:'), chalk.green(swarm.status));
959
- console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());
960
- // Get agents
961
- const agents = db.prepare(`
950
+ `,
951
+ )
952
+ .all();
953
+
954
+ if (swarms.length === 0) {
955
+ console.log(chalk.gray('No active swarms found'));
956
+ db.close();
957
+ return;
958
+ }
959
+
960
+ console.log(chalk.bold('\n🐝 Active Hive Mind Swarms\n'));
961
+
962
+ for (const swarm of swarms) {
963
+ console.log(chalk.yellow(''.repeat(60)));
964
+ console.log(chalk.cyan('Swarm:'), swarm.name);
965
+ console.log(chalk.cyan('ID:'), swarm.id);
966
+ console.log(chalk.cyan('Objective:'), swarm.objective);
967
+ console.log(chalk.cyan('Queen Type:'), swarm.queen_type);
968
+ console.log(chalk.cyan('Status:'), chalk.green(swarm.status));
969
+ console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());
970
+
971
+ // Get agents
972
+ const agents = db
973
+ .prepare(
974
+ `
962
975
  SELECT * FROM agents
963
976
  WHERE swarm_id = ?
964
- `).all(swarm.id);
965
- console.log('\n' + chalk.bold('Agents:'));
966
- // Group by role
967
- const queen = agents.find((a)=>a.role === 'queen');
968
- const workers = agents.filter((a)=>a.role === 'worker');
969
- if (queen) {
970
- console.log(' ' + chalk.magenta('👑 Queen:'), queen.name, chalk.gray(`(${queen.status})`));
971
- }
972
- console.log(' ' + chalk.blue('🐝 Workers:'));
973
- workers.forEach((worker)=>{
974
- const statusColor = worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';
975
- console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);
976
- });
977
- // Get task statistics
978
- const taskStats = db.prepare(`
977
+ `,
978
+ )
979
+ .all(swarm.id);
980
+
981
+ console.log('\n' + chalk.bold('Agents:'));
982
+
983
+ // Group by role
984
+ const queen = agents.find((a) => a.role === 'queen');
985
+ const workers = agents.filter((a) => a.role === 'worker');
986
+
987
+ if (queen) {
988
+ console.log(' ' + chalk.magenta('👑 Queen:'), queen.name, chalk.gray(`(${queen.status})`));
989
+ }
990
+
991
+ console.log(' ' + chalk.blue('🐝 Workers:'));
992
+ workers.forEach((worker) => {
993
+ const statusColor =
994
+ worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';
995
+ console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);
996
+ });
997
+
998
+ // Get task statistics
999
+ const taskStats = db
1000
+ .prepare(
1001
+ `
979
1002
  SELECT
980
1003
  COUNT(*) as total,
981
1004
  SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
@@ -983,153 +1006,234 @@ async function(flags = {}) {
983
1006
  SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
984
1007
  FROM tasks
985
1008
  WHERE swarm_id = ?
986
- `).get(swarm.id);
987
- console.log('\n' + chalk.bold('Tasks:'));
988
- console.log(` Total: ${taskStats.total}`);
989
- console.log(` Completed: ${chalk.green(taskStats.completed)}`);
990
- console.log(` In Progress: ${chalk.yellow(taskStats.in_progress)}`);
991
- console.log(` Pending: ${chalk.gray(taskStats.pending)}`);
992
- // Get memory stats
993
- const memoryCount = db.prepare(`
1009
+ `,
1010
+ )
1011
+ .get(swarm.id);
1012
+
1013
+ console.log('\n' + chalk.bold('Tasks:'));
1014
+ console.log(` Total: ${taskStats.total}`);
1015
+ console.log(` Completed: ${chalk.green(taskStats.completed)}`);
1016
+ console.log(` In Progress: ${chalk.yellow(taskStats.in_progress)}`);
1017
+ console.log(` Pending: ${chalk.gray(taskStats.pending)}`);
1018
+
1019
+ // Get memory stats
1020
+ const memoryCount = db
1021
+ .prepare(
1022
+ `
994
1023
  SELECT COUNT(*) as count FROM collective_memory
995
1024
  WHERE swarm_id = ?
996
- `).get(swarm.id);
997
- console.log('\n' + chalk.bold('Collective Memory:'));
998
- console.log(` Entries: ${memoryCount.count}`);
999
- // Get consensus stats
1000
- const consensusCount = db.prepare(`
1025
+ `,
1026
+ )
1027
+ .get(swarm.id);
1028
+
1029
+ console.log('\n' + chalk.bold('Collective Memory:'));
1030
+ console.log(` Entries: ${memoryCount.count}`);
1031
+
1032
+ // Get consensus stats
1033
+ const consensusCount = db
1034
+ .prepare(
1035
+ `
1001
1036
  SELECT COUNT(*) as count FROM consensus_decisions
1002
1037
  WHERE swarm_id = ?
1003
- `).get(swarm.id);
1004
- console.log('\n' + chalk.bold('Consensus Decisions:'));
1005
- console.log(` Total: ${consensusCount.count}`);
1006
- }
1007
- console.log(chalk.yellow(''.repeat(60)) + '\n');
1008
- db.close();
1009
- } catch (error) {
1010
- console.error(chalk.red('Error:'), error.message);
1011
- exit(1);
1038
+ `,
1039
+ )
1040
+ .get(swarm.id);
1041
+
1042
+ console.log('\n' + chalk.bold('Consensus Decisions:'));
1043
+ console.log(` Total: ${consensusCount.count}`);
1012
1044
  }
1045
+
1046
+ console.log(chalk.yellow('═'.repeat(60)) + '\n');
1047
+
1048
+ db.close();
1049
+ } catch (error) {
1050
+ console.error(chalk.red('Error:'), error.message);
1051
+ exit(1);
1052
+ }
1013
1053
  }
1054
+
1014
1055
  /**
1015
1056
  * Show consensus decisions
1016
- */ async function showConsensus(flags) {
1017
- try {
1018
- const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1019
- const db = new Database(dbPath);
1020
- const decisions = db.prepare(`
1057
+ */
1058
+ async function showConsensus(flags) {
1059
+ try {
1060
+ const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1061
+ const db = new Database(dbPath);
1062
+
1063
+ const decisions = db
1064
+ .prepare(
1065
+ `
1021
1066
  SELECT cd.*, s.name as swarm_name
1022
1067
  FROM consensus_decisions cd
1023
1068
  JOIN swarms s ON cd.swarm_id = s.id
1024
1069
  ORDER BY cd.created_at DESC
1025
1070
  LIMIT 20
1026
- `).all();
1027
- if (decisions.length === 0) {
1028
- console.log(chalk.gray('No consensus decisions found'));
1029
- db.close();
1030
- return;
1031
- }
1032
- console.log(chalk.bold('\n🤝 Recent Consensus Decisions\n'));
1033
- decisions.forEach((decision)=>{
1034
- console.log(chalk.yellow('─'.repeat(50)));
1035
- console.log(chalk.cyan('Swarm:'), decision.swarm_name);
1036
- console.log(chalk.cyan('Topic:'), decision.topic);
1037
- console.log(chalk.cyan('Decision:'), decision.decision);
1038
- console.log(chalk.cyan('Algorithm:'), decision.algorithm);
1039
- console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);
1040
- console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());
1041
- if (decision.votes) {
1042
- const votes = JSON.parse(decision.votes);
1043
- console.log(chalk.cyan('Votes:'));
1044
- // Handle vote summary format (for/against/abstain/details)
1045
- if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {
1046
- console.log(` - for: ${votes.for || 0}`);
1047
- console.log(` - against: ${votes.against || 0}`);
1048
- console.log(` - abstain: ${votes.abstain || 0}`);
1049
- // Display vote details properly if they exist
1050
- if (votes.details && Array.isArray(votes.details)) {
1051
- console.log(' - details:');
1052
- votes.details.forEach((detail, index)=>{
1053
- if (typeof detail === 'object') {
1054
- // Extract available fields
1055
- const agent = detail.agentId || detail.agent || detail.id || detail.name || `agent-${index + 1}`;
1056
- const vote = detail.vote || detail.choice || detail.decision || 'unknown';
1057
- const reason = detail.reason || detail.justification || detail.rationale;
1058
- // Build display string
1059
- let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;
1060
- // Add reason if available
1061
- if (reason && reason !== 'N/A' && reason !== '') {
1062
- displayString += `, Reason: ${reason}`;
1063
- }
1064
- console.log(displayString);
1065
- } else {
1066
- console.log(` ${index + 1}. ${detail}`);
1067
- }
1068
- });
1069
- }
1070
- } else {
1071
- // Handle individual agent votes format
1072
- Object.entries(votes).forEach(([agent, vote])=>{
1073
- console.log(` - ${agent}: ${vote}`);
1074
- });
1075
- }
1076
- }
1077
- });
1078
- console.log(chalk.yellow('─'.repeat(50)) + '\n');
1079
- db.close();
1080
- } catch (error) {
1081
- console.error(chalk.red('Error:'), error.message);
1082
- exit(1);
1071
+ `,
1072
+ )
1073
+ .all();
1074
+
1075
+ if (decisions.length === 0) {
1076
+ console.log(chalk.gray('No consensus decisions found'));
1077
+ db.close();
1078
+ return;
1083
1079
  }
1080
+
1081
+ console.log(chalk.bold('\n🤝 Recent Consensus Decisions\n'));
1082
+
1083
+ decisions.forEach((decision) => {
1084
+ console.log(chalk.yellow('─'.repeat(50)));
1085
+ console.log(chalk.cyan('Swarm:'), decision.swarm_name);
1086
+ console.log(chalk.cyan('Topic:'), decision.topic);
1087
+ console.log(chalk.cyan('Decision:'), decision.decision);
1088
+ console.log(chalk.cyan('Algorithm:'), decision.algorithm);
1089
+ console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);
1090
+ console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());
1091
+
1092
+ if (decision.votes) {
1093
+ const votes = JSON.parse(decision.votes);
1094
+ console.log(chalk.cyan('Votes:'));
1095
+
1096
+ // Handle vote summary format (for/against/abstain/details)
1097
+ if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {
1098
+ console.log(` - for: ${votes.for || 0}`);
1099
+ console.log(` - against: ${votes.against || 0}`);
1100
+ console.log(` - abstain: ${votes.abstain || 0}`);
1101
+
1102
+ // Display vote details properly if they exist
1103
+ if (votes.details && Array.isArray(votes.details)) {
1104
+ console.log(' - details:');
1105
+ votes.details.forEach((detail, index) => {
1106
+ if (typeof detail === 'object') {
1107
+ // Extract available fields
1108
+ const agent =
1109
+ detail.agentId ||
1110
+ detail.agent ||
1111
+ detail.id ||
1112
+ detail.name ||
1113
+ `agent-${index + 1}`;
1114
+ const vote = detail.vote || detail.choice || detail.decision || 'unknown';
1115
+ const reason = detail.reason || detail.justification || detail.rationale;
1116
+
1117
+ // Build display string
1118
+ let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;
1119
+
1120
+ // Add reason if available
1121
+ if (reason && reason !== 'N/A' && reason !== '') {
1122
+ displayString += `, Reason: ${reason}`;
1123
+ }
1124
+
1125
+ console.log(displayString);
1126
+ } else {
1127
+ console.log(` ${index + 1}. ${detail}`);
1128
+ }
1129
+ });
1130
+ }
1131
+ } else {
1132
+ // Handle individual agent votes format
1133
+ Object.entries(votes).forEach(([agent, vote]) => {
1134
+ console.log(` - ${agent}: ${vote}`);
1135
+ });
1136
+ }
1137
+ }
1138
+ });
1139
+
1140
+ console.log(chalk.yellow('─'.repeat(50)) + '\n');
1141
+
1142
+ db.close();
1143
+ } catch (error) {
1144
+ console.error(chalk.red('Error:'), error.message);
1145
+ exit(1);
1146
+ }
1084
1147
  }
1148
+
1085
1149
  /**
1086
1150
  * Show performance metrics
1087
- */ async function showMetrics(flags) {
1088
- try {
1089
- const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1090
- const db = new Database(dbPath);
1091
- // Get overall metrics
1092
- const overallStats = db.prepare(`
1151
+ */
1152
+ async function showMetrics(flags) {
1153
+ try {
1154
+ const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1155
+ const db = new Database(dbPath);
1156
+
1157
+ // Get overall metrics
1158
+ const overallStats = db
1159
+ .prepare(
1160
+ `
1093
1161
  SELECT
1094
1162
  (SELECT COUNT(*) FROM swarms) as total_swarms,
1095
1163
  (SELECT COUNT(*) FROM agents) as total_agents,
1096
1164
  (SELECT COUNT(*) FROM tasks) as total_tasks,
1097
1165
  (SELECT COUNT(*) FROM tasks WHERE status = 'completed') as completed_tasks
1098
- `).get();
1099
- console.log(chalk.bold('\n📊 Hive Mind Performance Metrics\n'));
1100
- // Get task status breakdown
1101
- const taskBreakdown = db.prepare(`
1166
+ `,
1167
+ )
1168
+ .get();
1169
+
1170
+ console.log(chalk.bold('\n📊 Hive Mind Performance Metrics\n'));
1171
+
1172
+ // Get task status breakdown
1173
+ const taskBreakdown = db
1174
+ .prepare(
1175
+ `
1102
1176
  SELECT
1103
1177
  status,
1104
1178
  COUNT(*) as count
1105
1179
  FROM tasks
1106
1180
  GROUP BY status
1107
1181
  ORDER BY count DESC
1108
- `).all();
1109
- console.log(chalk.cyan('Overall Statistics:'));
1110
- console.log(` Total Swarms: ${overallStats.total_swarms}`);
1111
- console.log(` Total Agents: ${overallStats.total_agents}`);
1112
- console.log(` Total Tasks: ${overallStats.total_tasks}`);
1113
- console.log(` Completed Tasks: ${overallStats.completed_tasks}`);
1114
- console.log(` Success Rate: ${overallStats.total_tasks > 0 ? (overallStats.completed_tasks / overallStats.total_tasks * 100).toFixed(1) + '%' : 'N/A'}`);
1115
- if (taskBreakdown.length > 0) {
1116
- console.log('\n' + chalk.cyan('Task Status Breakdown:'));
1117
- taskBreakdown.forEach((status)=>{
1118
- const percentage = overallStats.total_tasks > 0 ? (status.count / overallStats.total_tasks * 100).toFixed(1) : '0';
1119
- const statusColor = status.status === 'completed' ? 'green' : status.status === 'in_progress' ? 'yellow' : status.status === 'failed' ? 'red' : 'gray';
1120
- console.log(` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`);
1121
- });
1122
- }
1123
- // Get agent performance (check for completed_at column)
1124
- let agentPerf = [];
1125
- try {
1126
- // Check if completed_at exists
1127
- const hasCompletedAt = db.prepare(`
1182
+ `,
1183
+ )
1184
+ .all();
1185
+
1186
+ console.log(chalk.cyan('Overall Statistics:'));
1187
+ console.log(` Total Swarms: ${overallStats.total_swarms}`);
1188
+ console.log(` Total Agents: ${overallStats.total_agents}`);
1189
+ console.log(` Total Tasks: ${overallStats.total_tasks}`);
1190
+ console.log(` Completed Tasks: ${overallStats.completed_tasks}`);
1191
+ console.log(
1192
+ ` Success Rate: ${
1193
+ overallStats.total_tasks > 0
1194
+ ? ((overallStats.completed_tasks / overallStats.total_tasks) * 100).toFixed(1) + '%'
1195
+ : 'N/A'
1196
+ }`,
1197
+ );
1198
+
1199
+ if (taskBreakdown.length > 0) {
1200
+ console.log('\n' + chalk.cyan('Task Status Breakdown:'));
1201
+ taskBreakdown.forEach((status) => {
1202
+ const percentage =
1203
+ overallStats.total_tasks > 0
1204
+ ? ((status.count / overallStats.total_tasks) * 100).toFixed(1)
1205
+ : '0';
1206
+ const statusColor =
1207
+ status.status === 'completed'
1208
+ ? 'green'
1209
+ : status.status === 'in_progress'
1210
+ ? 'yellow'
1211
+ : status.status === 'failed'
1212
+ ? 'red'
1213
+ : 'gray';
1214
+ console.log(
1215
+ ` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`,
1216
+ );
1217
+ });
1218
+ }
1219
+
1220
+ // Get agent performance (check for completed_at column)
1221
+ let agentPerf = [];
1222
+ try {
1223
+ // Check if completed_at exists
1224
+ const hasCompletedAt = db
1225
+ .prepare(
1226
+ `
1128
1227
  SELECT COUNT(*) as count FROM pragma_table_info('tasks')
1129
1228
  WHERE name = 'completed_at'
1130
- `).get();
1131
- if (hasCompletedAt && hasCompletedAt.count > 0) {
1132
- agentPerf = db.prepare(`
1229
+ `,
1230
+ )
1231
+ .get();
1232
+
1233
+ if (hasCompletedAt && hasCompletedAt.count > 0) {
1234
+ agentPerf = db
1235
+ .prepare(
1236
+ `
1133
1237
  SELECT
1134
1238
  a.name,
1135
1239
  a.type,
@@ -1144,10 +1248,14 @@ async function(flags = {}) {
1144
1248
  HAVING tasks_assigned > 0
1145
1249
  ORDER BY tasks_completed DESC
1146
1250
  LIMIT 10
1147
- `).all();
1148
- } else {
1149
- // Simpler query without completed_at
1150
- agentPerf = db.prepare(`
1251
+ `,
1252
+ )
1253
+ .all();
1254
+ } else {
1255
+ // Simpler query without completed_at
1256
+ agentPerf = db
1257
+ .prepare(
1258
+ `
1151
1259
  SELECT
1152
1260
  a.name,
1153
1261
  a.type,
@@ -1160,24 +1268,35 @@ async function(flags = {}) {
1160
1268
  HAVING tasks_assigned > 0
1161
1269
  ORDER BY tasks_completed DESC
1162
1270
  LIMIT 10
1163
- `).all();
1164
- }
1165
- } catch (error) {
1166
- console.warn('Could not get agent performance:', error.message);
1167
- }
1168
- if (agentPerf.length > 0) {
1169
- console.log('\n' + chalk.cyan('Top Performing Agents:'));
1170
- agentPerf.forEach((agent, index)=>{
1171
- const successRate = agent.tasks_assigned > 0 ? (agent.tasks_completed / agent.tasks_assigned * 100).toFixed(1) : '0';
1172
- console.log(` ${index + 1}. ${agent.name} (${agent.type})`);
1173
- console.log(` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`);
1174
- if (agent.avg_completion_minutes) {
1175
- console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);
1176
- }
1177
- });
1271
+ `,
1272
+ )
1273
+ .all();
1274
+ }
1275
+ } catch (error) {
1276
+ console.warn('Could not get agent performance:', error.message);
1277
+ }
1278
+
1279
+ if (agentPerf.length > 0) {
1280
+ console.log('\n' + chalk.cyan('Top Performing Agents:'));
1281
+ agentPerf.forEach((agent, index) => {
1282
+ const successRate =
1283
+ agent.tasks_assigned > 0
1284
+ ? ((agent.tasks_completed / agent.tasks_assigned) * 100).toFixed(1)
1285
+ : '0';
1286
+ console.log(` ${index + 1}. ${agent.name} (${agent.type})`);
1287
+ console.log(
1288
+ ` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`,
1289
+ );
1290
+ if (agent.avg_completion_minutes) {
1291
+ console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);
1178
1292
  }
1179
- // Get swarm performance
1180
- const swarmPerf = db.prepare(`
1293
+ });
1294
+ }
1295
+
1296
+ // Get swarm performance
1297
+ const swarmPerf = db
1298
+ .prepare(
1299
+ `
1181
1300
  SELECT
1182
1301
  s.name,
1183
1302
  s.objective,
@@ -1190,50 +1309,76 @@ async function(flags = {}) {
1190
1309
  WHERE s.status = 'active'
1191
1310
  ORDER BY s.created_at DESC
1192
1311
  LIMIT 5
1193
- `).all();
1194
- if (swarmPerf.length > 0) {
1195
- console.log('\n' + chalk.cyan('Active Swarm Performance:'));
1196
- swarmPerf.forEach((swarm)=>{
1197
- const successRate = swarm.task_count > 0 ? (swarm.completed_count / swarm.task_count * 100).toFixed(1) : '0';
1198
- console.log(`\n ${chalk.yellow(swarm.name)}`);
1199
- console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);
1200
- console.log(` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`);
1201
- console.log(` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`);
1202
- });
1203
- }
1204
- // Get performance insights
1205
- let avgTaskTime = {
1206
- avg_minutes: null
1207
- };
1208
- try {
1209
- // Check if completed_at exists
1210
- const hasCompletedAt = db.prepare(`
1312
+ `,
1313
+ )
1314
+ .all();
1315
+
1316
+ if (swarmPerf.length > 0) {
1317
+ console.log('\n' + chalk.cyan('Active Swarm Performance:'));
1318
+ swarmPerf.forEach((swarm) => {
1319
+ const successRate =
1320
+ swarm.task_count > 0
1321
+ ? ((swarm.completed_count / swarm.task_count) * 100).toFixed(1)
1322
+ : '0';
1323
+ console.log(`\n ${chalk.yellow(swarm.name)}`);
1324
+ console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);
1325
+ console.log(
1326
+ ` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`,
1327
+ );
1328
+ console.log(
1329
+ ` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`,
1330
+ );
1331
+ });
1332
+ }
1333
+
1334
+ // Get performance insights
1335
+ let avgTaskTime = { avg_minutes: null };
1336
+ try {
1337
+ // Check if completed_at exists
1338
+ const hasCompletedAt = db
1339
+ .prepare(
1340
+ `
1211
1341
  SELECT COUNT(*) as count FROM pragma_table_info('tasks')
1212
1342
  WHERE name = 'completed_at'
1213
- `).get();
1214
- if (hasCompletedAt && hasCompletedAt.count > 0) {
1215
- avgTaskTime = db.prepare(`
1343
+ `,
1344
+ )
1345
+ .get();
1346
+
1347
+ if (hasCompletedAt && hasCompletedAt.count > 0) {
1348
+ avgTaskTime = db
1349
+ .prepare(
1350
+ `
1216
1351
  SELECT
1217
1352
  AVG(CASE WHEN completed_at IS NOT NULL
1218
1353
  THEN (julianday(completed_at) - julianday(created_at)) * 24 * 60
1219
1354
  ELSE NULL END) as avg_minutes
1220
1355
  FROM tasks
1221
1356
  WHERE status = 'completed'
1222
- `).get();
1223
- }
1224
- } catch (error) {
1225
- console.warn('Could not calculate average task time:', error.message);
1226
- }
1227
- // Get agent type performance
1228
- let agentTypePerf = [];
1229
- try {
1230
- // Check if completed_at exists
1231
- const hasCompletedAt = db.prepare(`
1357
+ `,
1358
+ )
1359
+ .get();
1360
+ }
1361
+ } catch (error) {
1362
+ console.warn('Could not calculate average task time:', error.message);
1363
+ }
1364
+
1365
+ // Get agent type performance
1366
+ let agentTypePerf = [];
1367
+ try {
1368
+ // Check if completed_at exists
1369
+ const hasCompletedAt = db
1370
+ .prepare(
1371
+ `
1232
1372
  SELECT COUNT(*) as count FROM pragma_table_info('tasks')
1233
1373
  WHERE name = 'completed_at'
1234
- `).get();
1235
- if (hasCompletedAt && hasCompletedAt.count > 0) {
1236
- agentTypePerf = db.prepare(`
1374
+ `,
1375
+ )
1376
+ .get();
1377
+
1378
+ if (hasCompletedAt && hasCompletedAt.count > 0) {
1379
+ agentTypePerf = db
1380
+ .prepare(
1381
+ `
1237
1382
  SELECT
1238
1383
  a.type,
1239
1384
  COUNT(t.id) as total_tasks,
@@ -1246,10 +1391,14 @@ async function(flags = {}) {
1246
1391
  GROUP BY a.type
1247
1392
  HAVING total_tasks > 0
1248
1393
  ORDER BY completed_tasks DESC
1249
- `).all();
1250
- } else {
1251
- // Simpler query without completed_at
1252
- agentTypePerf = db.prepare(`
1394
+ `,
1395
+ )
1396
+ .all();
1397
+ } else {
1398
+ // Simpler query without completed_at
1399
+ agentTypePerf = db
1400
+ .prepare(
1401
+ `
1253
1402
  SELECT
1254
1403
  a.type,
1255
1404
  COUNT(t.id) as total_tasks,
@@ -1260,686 +1409,824 @@ async function(flags = {}) {
1260
1409
  GROUP BY a.type
1261
1410
  HAVING total_tasks > 0
1262
1411
  ORDER BY completed_tasks DESC
1263
- `).all();
1264
- }
1265
- } catch (error) {
1266
- console.warn('Could not get agent type performance:', error.message);
1267
- }
1268
- if (avgTaskTime.avg_minutes) {
1269
- console.log('\n' + chalk.cyan('Performance Insights:'));
1270
- console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);
1271
- if (agentTypePerf.length > 0) {
1272
- console.log('\n' + chalk.cyan('Agent Type Performance:'));
1273
- agentTypePerf.forEach((type)=>{
1274
- const successRate = type.total_tasks > 0 ? (type.completed_tasks / type.total_tasks * 100).toFixed(1) : '0';
1275
- console.log(` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`);
1276
- if (type.avg_completion_minutes) {
1277
- console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);
1278
- }
1279
- });
1280
- }
1281
- }
1282
- console.log('\n');
1283
- db.close();
1412
+ `,
1413
+ )
1414
+ .all();
1415
+ }
1284
1416
  } catch (error) {
1285
- console.error(chalk.red('Error:'), error.message);
1286
- exit(1);
1417
+ console.warn('Could not get agent type performance:', error.message);
1418
+ }
1419
+
1420
+ if (avgTaskTime.avg_minutes) {
1421
+ console.log('\n' + chalk.cyan('Performance Insights:'));
1422
+ console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);
1423
+
1424
+ if (agentTypePerf.length > 0) {
1425
+ console.log('\n' + chalk.cyan('Agent Type Performance:'));
1426
+ agentTypePerf.forEach((type) => {
1427
+ const successRate =
1428
+ type.total_tasks > 0
1429
+ ? ((type.completed_tasks / type.total_tasks) * 100).toFixed(1)
1430
+ : '0';
1431
+ console.log(
1432
+ ` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`,
1433
+ );
1434
+ if (type.avg_completion_minutes) {
1435
+ console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);
1436
+ }
1437
+ });
1438
+ }
1287
1439
  }
1440
+
1441
+ console.log('\n');
1442
+ db.close();
1443
+ } catch (error) {
1444
+ console.error(chalk.red('Error:'), error.message);
1445
+ exit(1);
1446
+ }
1288
1447
  }
1448
+
1289
1449
  /**
1290
1450
  * Manage collective memory wizard
1291
- */ async function manageMemoryWizard() {
1292
- console.log(chalk.blue('\n🧠 Collective Memory Management\n'));
1293
- const { action } = await inquirer.prompt([
1294
- {
1295
- type: 'list',
1296
- name: 'action',
1297
- message: 'What would you like to do with collective memory?',
1298
- choices: [
1299
- {
1300
- name: '📋 View all memories',
1301
- value: 'list'
1302
- },
1303
- {
1304
- name: '🔍 Search memories',
1305
- value: 'search'
1306
- },
1307
- {
1308
- name: '💾 Store new memory',
1309
- value: 'store'
1310
- },
1311
- {
1312
- name: '📊 Memory statistics',
1313
- value: 'stats'
1314
- },
1315
- {
1316
- name: '🗑️ Clean old memories',
1317
- value: 'clean'
1318
- },
1319
- {
1320
- name: '📤 Export memory backup',
1321
- value: 'export'
1322
- },
1323
- {
1324
- name: '⬅️ Back to main menu',
1325
- value: 'back'
1326
- }
1327
- ]
1328
- }
1329
- ]);
1330
- switch(action){
1331
- case 'list':
1332
- await listMemories();
1333
- break;
1334
- case 'search':
1335
- await searchMemories();
1336
- break;
1337
- case 'store':
1338
- await storeMemoryWizard();
1339
- break;
1340
- case 'stats':
1341
- await showMemoryStats();
1342
- break;
1343
- case 'clean':
1344
- await cleanMemories();
1345
- break;
1346
- case 'export':
1347
- await exportMemoryBackup();
1348
- break;
1349
- case 'back':
1350
- await hiveMindWizard();
1351
- return;
1352
- }
1353
- // Ask if user wants to continue
1354
- const { continue: continueAction } = await inquirer.prompt([
1355
- {
1356
- type: 'confirm',
1357
- name: 'continue',
1358
- message: 'Would you like to perform another memory operation?',
1359
- default: true
1360
- }
1361
- ]);
1362
- if (continueAction) {
1363
- await manageMemoryWizard();
1364
- }
1451
+ */
1452
+ async function manageMemoryWizard() {
1453
+ console.log(chalk.blue('\n🧠 Collective Memory Management\n'));
1454
+
1455
+ const { action } = await inquirer.prompt([
1456
+ {
1457
+ type: 'list',
1458
+ name: 'action',
1459
+ message: 'What would you like to do with collective memory?',
1460
+ choices: [
1461
+ { name: '📋 View all memories', value: 'list' },
1462
+ { name: '🔍 Search memories', value: 'search' },
1463
+ { name: '💾 Store new memory', value: 'store' },
1464
+ { name: '📊 Memory statistics', value: 'stats' },
1465
+ { name: '🗑️ Clean old memories', value: 'clean' },
1466
+ { name: '📤 Export memory backup', value: 'export' },
1467
+ { name: '⬅️ Back to main menu', value: 'back' },
1468
+ ],
1469
+ },
1470
+ ]);
1471
+
1472
+ switch (action) {
1473
+ case 'list':
1474
+ await listMemories();
1475
+ break;
1476
+ case 'search':
1477
+ await searchMemories();
1478
+ break;
1479
+ case 'store':
1480
+ await storeMemoryWizard();
1481
+ break;
1482
+ case 'stats':
1483
+ await showMemoryStats();
1484
+ break;
1485
+ case 'clean':
1486
+ await cleanMemories();
1487
+ break;
1488
+ case 'export':
1489
+ await exportMemoryBackup();
1490
+ break;
1491
+ case 'back':
1492
+ await hiveMindWizard();
1493
+ return;
1494
+ }
1495
+
1496
+ // Ask if user wants to continue
1497
+ const { continue: continueAction } = await inquirer.prompt([
1498
+ {
1499
+ type: 'confirm',
1500
+ name: 'continue',
1501
+ message: 'Would you like to perform another memory operation?',
1502
+ default: true,
1503
+ },
1504
+ ]);
1505
+
1506
+ if (continueAction) {
1507
+ await manageMemoryWizard();
1508
+ }
1365
1509
  }
1510
+
1366
1511
  /**
1367
1512
  * Configure hive mind wizard
1368
- */ async function configureWizard() {
1369
- // TODO: Implement configuration wizard
1370
- console.log(chalk.yellow('Configuration wizard coming soon...'));
1513
+ */
1514
+ async function configureWizard() {
1515
+ // TODO: Implement configuration wizard
1516
+ console.log(chalk.yellow('Configuration wizard coming soon...'));
1371
1517
  }
1518
+
1372
1519
  /**
1373
1520
  * Main hive mind command handler
1374
- */ export async function hiveMindCommand(args, flags) {
1375
- const subcommand = args[0];
1376
- const subArgs = args.slice(1);
1377
- // Handle help flags
1378
- if (!subcommand || subcommand === '--help' || subcommand === '-h' || subcommand === 'help' || flags.help) {
1379
- showHiveMindHelp();
1380
- return;
1381
- }
1382
- // Warn about non-interactive environments for certain commands
1383
- if (subcommand === 'spawn' && (flags.claude || flags.spawn) || subcommand === 'wizard') {
1384
- warnNonInteractive('hive-mind ' + subcommand);
1385
- }
1386
- switch(subcommand){
1387
- case 'init':
1388
- await initHiveMind(flags);
1389
- break;
1390
- case 'spawn':
1391
- // Check for non-interactive mode FIRST (like alpha.83)
1392
- if (flags['non-interactive'] || flags.nonInteractive) {
1393
- // In non-interactive mode, skip wizard and use defaults
1394
- if (subArgs.length === 0) {
1395
- console.error(chalk.red('Error: Objective required in non-interactive mode'));
1396
- console.log('Usage: claude-flow-novice hive-mind spawn "Your objective" --non-interactive');
1397
- return;
1398
- }
1399
- await spawnSwarm(subArgs, flags);
1400
- } else if (flags.wizard || subArgs.length === 0) {
1401
- await spawnSwarmWizard();
1402
- } else {
1403
- await spawnSwarm(subArgs, flags);
1404
- }
1405
- break;
1406
- case 'status':
1407
- await showStatus(flags);
1408
- break;
1409
- case 'sessions':
1410
- await showSessions(flags);
1411
- break;
1412
- case 'resume':
1413
- await resumeSession(subArgs, flags);
1414
- break;
1415
- case 'stop':
1416
- await stopSession(subArgs, flags);
1417
- break;
1418
- case 'consensus':
1419
- await showConsensus(flags);
1420
- break;
1421
- case 'memory':
1422
- await manageMemoryWizard();
1423
- break;
1424
- case 'metrics':
1425
- await showMetrics(flags);
1426
- break;
1427
- case 'wizard':
1428
- await hiveMindWizard(flags);
1429
- break;
1430
- case 'help':
1431
- case '--help':
1432
- case '-h':
1433
- showHiveMindHelp();
1434
- break;
1435
- default:
1436
- console.error(chalk.red(`Unknown subcommand: ${subcommand}`));
1437
- console.log('Run "claude-flow-novice hive-mind help" for usage information');
1438
- exit(1);
1439
- }
1521
+ */
1522
+ export async function hiveMindCommand(args, flags) {
1523
+ const subcommand = args[0];
1524
+ const subArgs = args.slice(1);
1525
+
1526
+ // Handle help flags
1527
+ if (
1528
+ !subcommand ||
1529
+ subcommand === '--help' ||
1530
+ subcommand === '-h' ||
1531
+ subcommand === 'help' ||
1532
+ flags.help
1533
+ ) {
1534
+ showHiveMindHelp();
1535
+ return;
1536
+ }
1537
+
1538
+ // Warn about non-interactive environments for certain commands
1539
+ if ((subcommand === 'spawn' && (flags.claude || flags.spawn)) || subcommand === 'wizard') {
1540
+ warnNonInteractive('hive-mind ' + subcommand);
1541
+ }
1542
+
1543
+ switch (subcommand) {
1544
+ case 'init':
1545
+ await initHiveMind(flags);
1546
+ break;
1547
+
1548
+ case 'spawn':
1549
+ // Check for non-interactive mode FIRST (like alpha.83)
1550
+ if (flags['non-interactive'] || flags.nonInteractive) {
1551
+ // In non-interactive mode, skip wizard and use defaults
1552
+ if (subArgs.length === 0) {
1553
+ console.error(chalk.red('Error: Objective required in non-interactive mode'));
1554
+ console.log('Usage: claude-flow-novice hive-mind spawn "Your objective" --non-interactive');
1555
+ return;
1556
+ }
1557
+ await spawnSwarm(subArgs, flags);
1558
+ } else if (flags.wizard || subArgs.length === 0) {
1559
+ await spawnSwarmWizard();
1560
+ } else {
1561
+ await spawnSwarm(subArgs, flags);
1562
+ }
1563
+ break;
1564
+
1565
+ case 'status':
1566
+ await showStatus(flags);
1567
+ break;
1568
+
1569
+ case 'sessions':
1570
+ await showSessions(flags);
1571
+ break;
1572
+
1573
+ case 'resume':
1574
+ await resumeSession(subArgs, flags);
1575
+ break;
1576
+
1577
+ case 'stop':
1578
+ await stopSession(subArgs, flags);
1579
+ break;
1580
+
1581
+ case 'consensus':
1582
+ await showConsensus(flags);
1583
+ break;
1584
+
1585
+ case 'memory':
1586
+ await manageMemoryWizard();
1587
+ break;
1588
+
1589
+ case 'metrics':
1590
+ await showMetrics(flags);
1591
+ break;
1592
+
1593
+ case 'wizard':
1594
+ await hiveMindWizard(flags);
1595
+ break;
1596
+
1597
+ case 'help':
1598
+ case '--help':
1599
+ case '-h':
1600
+ showHiveMindHelp();
1601
+ break;
1602
+
1603
+ default:
1604
+ console.error(chalk.red(`Unknown subcommand: ${subcommand}`));
1605
+ console.log('Run "claude-flow-novice hive-mind help" for usage information');
1606
+ exit(1);
1607
+ }
1440
1608
  }
1609
+
1441
1610
  /**
1442
1611
  * List all memories in the collective memory store
1443
- */ async function listMemories() {
1444
- try {
1445
- console.log(chalk.blue('\n📋 Collective Memory Store\n'));
1446
- // Read directly from hive.db collective_memory table
1447
- const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1448
- const db = new Database(dbPath);
1449
- const memories = db.prepare(`
1612
+ */
1613
+ async function listMemories() {
1614
+ try {
1615
+ console.log(chalk.blue('\n📋 Collective Memory Store\n'));
1616
+
1617
+ // Read directly from hive.db collective_memory table
1618
+ const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1619
+ const db = new Database(dbPath);
1620
+
1621
+ const memories = db
1622
+ .prepare(
1623
+ `
1450
1624
  SELECT cm.*, s.name as swarm_name
1451
1625
  FROM collective_memory cm
1452
1626
  LEFT JOIN swarms s ON cm.swarm_id = s.id
1453
1627
  ORDER BY cm.created_at DESC
1454
1628
  LIMIT 50
1455
- `).all();
1456
- db.close();
1457
- if (!memories || memories.length === 0) {
1458
- console.log(chalk.yellow('No memories found in the collective store.'));
1459
- console.log(chalk.gray('Try storing some memories first using the "💾 Store new memory" option.'));
1460
- return;
1461
- }
1462
- console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\n`));
1463
- memories.forEach((memory, index)=>{
1464
- console.log(chalk.cyan(`${index + 1}. ${memory.key}`));
1465
- console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);
1466
- console.log(` Type: ${memory.type || 'knowledge'}`);
1467
- console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);
1468
- console.log(` Created by: ${memory.created_by || 'system'}`);
1469
- // Parse and display value
1470
- let displayValue = memory.value;
1471
- try {
1472
- const parsed = JSON.parse(memory.value);
1473
- displayValue = JSON.stringify(parsed);
1474
- } catch {
1475
- // Keep as string
1476
- }
1477
- if (displayValue.length > 100) {
1478
- console.log(` Value: ${displayValue.substring(0, 100)}...`);
1479
- } else {
1480
- console.log(` Value: ${displayValue}`);
1481
- }
1482
- if (memory.confidence !== null && memory.confidence !== 1) {
1483
- console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);
1484
- }
1485
- console.log('');
1486
- });
1487
- } catch (error) {
1488
- console.error(chalk.red('Error listing memories:'), error.message);
1489
- console.log(chalk.gray('This might be because no memories have been stored yet.'));
1629
+ `,
1630
+ )
1631
+ .all();
1632
+
1633
+ db.close();
1634
+
1635
+ if (!memories || memories.length === 0) {
1636
+ console.log(chalk.yellow('No memories found in the collective store.'));
1637
+ console.log(
1638
+ chalk.gray('Try storing some memories first using the "💾 Store new memory" option.'),
1639
+ );
1640
+ return;
1490
1641
  }
1642
+
1643
+ console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\n`));
1644
+
1645
+ memories.forEach((memory, index) => {
1646
+ console.log(chalk.cyan(`${index + 1}. ${memory.key}`));
1647
+ console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);
1648
+ console.log(` Type: ${memory.type || 'knowledge'}`);
1649
+ console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);
1650
+ console.log(` Created by: ${memory.created_by || 'system'}`);
1651
+
1652
+ // Parse and display value
1653
+ let displayValue = memory.value;
1654
+ try {
1655
+ const parsed = JSON.parse(memory.value);
1656
+ displayValue = JSON.stringify(parsed);
1657
+ } catch {
1658
+ // Keep as string
1659
+ }
1660
+
1661
+ if (displayValue.length > 100) {
1662
+ console.log(` Value: ${displayValue.substring(0, 100)}...`);
1663
+ } else {
1664
+ console.log(` Value: ${displayValue}`);
1665
+ }
1666
+
1667
+ if (memory.confidence !== null && memory.confidence !== 1) {
1668
+ console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);
1669
+ }
1670
+
1671
+ console.log('');
1672
+ });
1673
+ } catch (error) {
1674
+ console.error(chalk.red('Error listing memories:'), error.message);
1675
+ console.log(chalk.gray('This might be because no memories have been stored yet.'));
1676
+ }
1491
1677
  }
1678
+
1492
1679
  /**
1493
1680
  * Search memories by keyword
1494
- */ async function searchMemories() {
1495
- try {
1496
- const { searchTerm } = await inquirer.prompt([
1497
- {
1498
- type: 'input',
1499
- name: 'searchTerm',
1500
- message: 'Enter search term:',
1501
- validate: (input)=>input.length > 0
1502
- }
1503
- ]);
1504
- console.log(chalk.blue(`\n🔍 Searching for: "${searchTerm}"\n`));
1505
- // Search directly in hive.db collective_memory table
1506
- const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1507
- const db = new Database(dbPath);
1508
- const searchPattern = `%${searchTerm}%`;
1509
- const memories = db.prepare(`
1681
+ */
1682
+ async function searchMemories() {
1683
+ try {
1684
+ const { searchTerm } = await inquirer.prompt([
1685
+ {
1686
+ type: 'input',
1687
+ name: 'searchTerm',
1688
+ message: 'Enter search term:',
1689
+ validate: (input) => input.length > 0,
1690
+ },
1691
+ ]);
1692
+
1693
+ console.log(chalk.blue(`\n🔍 Searching for: "${searchTerm}"\n`));
1694
+
1695
+ // Search directly in hive.db collective_memory table
1696
+ const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
1697
+ const db = new Database(dbPath);
1698
+
1699
+ const searchPattern = `%${searchTerm}%`;
1700
+ const memories = db
1701
+ .prepare(
1702
+ `
1510
1703
  SELECT cm.*, s.name as swarm_name
1511
1704
  FROM collective_memory cm
1512
1705
  LEFT JOIN swarms s ON cm.swarm_id = s.id
1513
1706
  WHERE cm.key LIKE ? OR cm.value LIKE ? OR cm.type LIKE ?
1514
1707
  ORDER BY cm.created_at DESC
1515
1708
  LIMIT 50
1516
- `).all(searchPattern, searchPattern, searchPattern);
1517
- db.close();
1518
- if (!memories || memories.length === 0) {
1519
- console.log(chalk.yellow('No memories found matching your search.'));
1520
- return;
1521
- }
1522
- console.log(chalk.gray(`Found ${memories.length} memories matching "${searchTerm}":\n`));
1523
- memories.forEach((memory, index)=>{
1524
- console.log(chalk.green(`${index + 1}. ${memory.key}`));
1525
- console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);
1526
- console.log(` Type: ${memory.type || 'knowledge'}`);
1527
- console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);
1528
- // Parse and display value with highlighting
1529
- let displayValue = memory.value;
1530
- try {
1531
- const parsed = JSON.parse(memory.value);
1532
- displayValue = JSON.stringify(parsed, null, 2);
1533
- } catch {
1534
- // Keep as string
1535
- }
1536
- console.log(` Value: ${displayValue}`);
1537
- console.log('');
1538
- });
1539
- } catch (error) {
1540
- console.error(chalk.red('Error searching memories:'), error.message);
1709
+ `,
1710
+ )
1711
+ .all(searchPattern, searchPattern, searchPattern);
1712
+
1713
+ db.close();
1714
+
1715
+ if (!memories || memories.length === 0) {
1716
+ console.log(chalk.yellow('No memories found matching your search.'));
1717
+ return;
1541
1718
  }
1719
+
1720
+ console.log(chalk.gray(`Found ${memories.length} memories matching "${searchTerm}":\n`));
1721
+
1722
+ memories.forEach((memory, index) => {
1723
+ console.log(chalk.green(`${index + 1}. ${memory.key}`));
1724
+ console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);
1725
+ console.log(` Type: ${memory.type || 'knowledge'}`);
1726
+ console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);
1727
+
1728
+ // Parse and display value with highlighting
1729
+ let displayValue = memory.value;
1730
+ try {
1731
+ const parsed = JSON.parse(memory.value);
1732
+ displayValue = JSON.stringify(parsed, null, 2);
1733
+ } catch {
1734
+ // Keep as string
1735
+ }
1736
+
1737
+ console.log(` Value: ${displayValue}`);
1738
+ console.log('');
1739
+ });
1740
+ } catch (error) {
1741
+ console.error(chalk.red('Error searching memories:'), error.message);
1742
+ }
1542
1743
  }
1744
+
1543
1745
  /**
1544
1746
  * Store new memory wizard
1545
- */ async function storeMemoryWizard() {
1747
+ */
1748
+ async function storeMemoryWizard() {
1749
+ try {
1750
+ const answers = await inquirer.prompt([
1751
+ {
1752
+ type: 'input',
1753
+ name: 'key',
1754
+ message: 'Memory key (identifier):',
1755
+ validate: (input) => input.length > 0,
1756
+ },
1757
+ {
1758
+ type: 'list',
1759
+ name: 'category',
1760
+ message: 'Memory category:',
1761
+ choices: [
1762
+ 'consensus',
1763
+ 'decision',
1764
+ 'pattern',
1765
+ 'learning',
1766
+ 'coordination',
1767
+ 'performance',
1768
+ 'configuration',
1769
+ 'general',
1770
+ ],
1771
+ },
1772
+ {
1773
+ type: 'editor',
1774
+ name: 'value',
1775
+ message: 'Memory content (JSON or text):',
1776
+ },
1777
+ ]);
1778
+
1779
+ const mcpWrapper = await getMcpWrapper();
1780
+ let memoryValue;
1781
+
1782
+ // Try to parse as JSON, fall back to string
1546
1783
  try {
1547
- const answers = await inquirer.prompt([
1548
- {
1549
- type: 'input',
1550
- name: 'key',
1551
- message: 'Memory key (identifier):',
1552
- validate: (input)=>input.length > 0
1553
- },
1554
- {
1555
- type: 'list',
1556
- name: 'category',
1557
- message: 'Memory category:',
1558
- choices: [
1559
- 'consensus',
1560
- 'decision',
1561
- 'pattern',
1562
- 'learning',
1563
- 'coordination',
1564
- 'performance',
1565
- 'configuration',
1566
- 'general'
1567
- ]
1568
- },
1569
- {
1570
- type: 'editor',
1571
- name: 'value',
1572
- message: 'Memory content (JSON or text):'
1573
- }
1574
- ]);
1575
- const mcpWrapper = await getMcpWrapper();
1576
- let memoryValue;
1577
- // Try to parse as JSON, fall back to string
1578
- try {
1579
- memoryValue = JSON.parse(answers.value);
1580
- } catch {
1581
- memoryValue = answers.value;
1582
- }
1583
- await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);
1584
- console.log(chalk.green(`\n✅ Memory stored successfully!`));
1585
- console.log(`Key: ${answers.key}`);
1586
- console.log(`Category: ${answers.category}`);
1587
- } catch (error) {
1588
- console.error(chalk.red('Error storing memory:'), error.message);
1784
+ memoryValue = JSON.parse(answers.value);
1785
+ } catch {
1786
+ memoryValue = answers.value;
1589
1787
  }
1788
+
1789
+ await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);
1790
+
1791
+ console.log(chalk.green(`\n✅ Memory stored successfully!`));
1792
+ console.log(`Key: ${answers.key}`);
1793
+ console.log(`Category: ${answers.category}`);
1794
+ } catch (error) {
1795
+ console.error(chalk.red('Error storing memory:'), error.message);
1796
+ }
1590
1797
  }
1798
+
1591
1799
  /**
1592
1800
  * Show memory statistics
1593
- */ async function showMemoryStats() {
1594
- try {
1595
- console.log(chalk.blue('\n📊 Memory Statistics\n'));
1596
- const mcpWrapper = await getMcpWrapper();
1597
- // Search for all memories with an empty pattern to get everything
1598
- const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1599
- // Handle different possible response structures
1600
- let memories = [];
1601
- if (searchResult && Array.isArray(searchResult.results)) {
1602
- memories = searchResult.results;
1603
- } else if (searchResult && Array.isArray(searchResult)) {
1604
- memories = searchResult;
1605
- } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1606
- memories = searchResult.data;
1607
- }
1608
- if (!memories || memories.length === 0) {
1609
- console.log(chalk.yellow('No memories found.'));
1610
- console.log(chalk.gray('Use "Store new memory" to create your first memory.'));
1611
- return;
1612
- }
1613
- // Calculate statistics
1614
- const stats = {
1615
- total: memories.length,
1616
- categories: {},
1617
- oldestDate: null,
1618
- newestDate: null,
1619
- totalSize: 0
1620
- };
1621
- memories.forEach((memory)=>{
1622
- // Count by category
1623
- const category = memory.category || memory.type || 'general';
1624
- stats.categories[category] = (stats.categories[category] || 0) + 1;
1625
- // Track dates
1626
- const date = new Date(memory.timestamp || Date.now());
1627
- if (!stats.oldestDate || date < stats.oldestDate) {
1628
- stats.oldestDate = date;
1629
- }
1630
- if (!stats.newestDate || date > stats.newestDate) {
1631
- stats.newestDate = date;
1632
- }
1633
- // Estimate size
1634
- stats.totalSize += JSON.stringify(memory).length;
1635
- });
1636
- console.log(chalk.cyan('Total memories:'), stats.total);
1637
- console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);
1638
- console.log(chalk.cyan('Date range:'), `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`);
1639
- console.log(chalk.cyan('\nBy category:'));
1640
- Object.entries(stats.categories).forEach(([category, count])=>{
1641
- console.log(` ${category}: ${count}`);
1642
- });
1643
- } catch (error) {
1644
- console.error(chalk.red('Error getting memory stats:'), error.message);
1801
+ */
1802
+ async function showMemoryStats() {
1803
+ try {
1804
+ console.log(chalk.blue('\n📊 Memory Statistics\n'));
1805
+
1806
+ const mcpWrapper = await getMcpWrapper();
1807
+
1808
+ // Search for all memories with an empty pattern to get everything
1809
+ const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1810
+
1811
+ // Handle different possible response structures
1812
+ let memories = [];
1813
+ if (searchResult && Array.isArray(searchResult.results)) {
1814
+ memories = searchResult.results;
1815
+ } else if (searchResult && Array.isArray(searchResult)) {
1816
+ memories = searchResult;
1817
+ } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1818
+ memories = searchResult.data;
1645
1819
  }
1820
+
1821
+ if (!memories || memories.length === 0) {
1822
+ console.log(chalk.yellow('No memories found.'));
1823
+ console.log(chalk.gray('Use "Store new memory" to create your first memory.'));
1824
+ return;
1825
+ }
1826
+
1827
+ // Calculate statistics
1828
+ const stats = {
1829
+ total: memories.length,
1830
+ categories: {},
1831
+ oldestDate: null,
1832
+ newestDate: null,
1833
+ totalSize: 0,
1834
+ };
1835
+
1836
+ memories.forEach((memory) => {
1837
+ // Count by category
1838
+ const category = memory.category || memory.type || 'general';
1839
+ stats.categories[category] = (stats.categories[category] || 0) + 1;
1840
+
1841
+ // Track dates
1842
+ const date = new Date(memory.timestamp || Date.now());
1843
+ if (!stats.oldestDate || date < stats.oldestDate) {
1844
+ stats.oldestDate = date;
1845
+ }
1846
+ if (!stats.newestDate || date > stats.newestDate) {
1847
+ stats.newestDate = date;
1848
+ }
1849
+
1850
+ // Estimate size
1851
+ stats.totalSize += JSON.stringify(memory).length;
1852
+ });
1853
+
1854
+ console.log(chalk.cyan('Total memories:'), stats.total);
1855
+ console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);
1856
+ console.log(
1857
+ chalk.cyan('Date range:'),
1858
+ `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`,
1859
+ );
1860
+
1861
+ console.log(chalk.cyan('\nBy category:'));
1862
+ Object.entries(stats.categories).forEach(([category, count]) => {
1863
+ console.log(` ${category}: ${count}`);
1864
+ });
1865
+ } catch (error) {
1866
+ console.error(chalk.red('Error getting memory stats:'), error.message);
1867
+ }
1646
1868
  }
1869
+
1647
1870
  /**
1648
1871
  * Clean old memories
1649
- */ async function cleanMemories() {
1650
- try {
1651
- const { days } = await inquirer.prompt([
1652
- {
1653
- type: 'number',
1654
- name: 'days',
1655
- message: 'Remove memories older than how many days?',
1656
- default: 30,
1657
- validate: (input)=>input > 0
1658
- }
1659
- ]);
1660
- const { confirm } = await inquirer.prompt([
1661
- {
1662
- type: 'confirm',
1663
- name: 'confirm',
1664
- message: `Are you sure you want to delete memories older than ${days} days?`,
1665
- default: false
1666
- }
1667
- ]);
1668
- if (!confirm) {
1669
- console.log(chalk.yellow('Operation cancelled.'));
1670
- return;
1671
- }
1672
- const mcpWrapper = await getMcpWrapper();
1673
- // Get all memories first
1674
- const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1675
- // Handle different possible response structures
1676
- let memories = [];
1677
- if (searchResult && Array.isArray(searchResult.results)) {
1678
- memories = searchResult.results;
1679
- } else if (searchResult && Array.isArray(searchResult)) {
1680
- memories = searchResult;
1681
- } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1682
- memories = searchResult.data;
1683
- }
1684
- const cutoffDate = new Date();
1685
- cutoffDate.setDate(cutoffDate.getDate() - days);
1686
- // Filter memories older than cutoff date
1687
- const oldMemories = memories.filter((memory)=>{
1688
- const memoryDate = new Date(memory.timestamp || 0);
1689
- return memoryDate < cutoffDate;
1690
- });
1691
- if (oldMemories.length === 0) {
1692
- console.log(chalk.yellow('\n🎉 No old memories found to clean.'));
1693
- return;
1694
- }
1695
- console.log(chalk.green(`\n✅ Found ${oldMemories.length} old memories to clean.`));
1696
- console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));
1697
- console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));
1698
- } catch (error) {
1699
- console.error(chalk.red('Error cleaning memories:'), error.message);
1872
+ */
1873
+ async function cleanMemories() {
1874
+ try {
1875
+ const { days } = await inquirer.prompt([
1876
+ {
1877
+ type: 'number',
1878
+ name: 'days',
1879
+ message: 'Remove memories older than how many days?',
1880
+ default: 30,
1881
+ validate: (input) => input > 0,
1882
+ },
1883
+ ]);
1884
+
1885
+ const { confirm } = await inquirer.prompt([
1886
+ {
1887
+ type: 'confirm',
1888
+ name: 'confirm',
1889
+ message: `Are you sure you want to delete memories older than ${days} days?`,
1890
+ default: false,
1891
+ },
1892
+ ]);
1893
+
1894
+ if (!confirm) {
1895
+ console.log(chalk.yellow('Operation cancelled.'));
1896
+ return;
1897
+ }
1898
+
1899
+ const mcpWrapper = await getMcpWrapper();
1900
+
1901
+ // Get all memories first
1902
+ const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1903
+
1904
+ // Handle different possible response structures
1905
+ let memories = [];
1906
+ if (searchResult && Array.isArray(searchResult.results)) {
1907
+ memories = searchResult.results;
1908
+ } else if (searchResult && Array.isArray(searchResult)) {
1909
+ memories = searchResult;
1910
+ } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1911
+ memories = searchResult.data;
1912
+ }
1913
+
1914
+ const cutoffDate = new Date();
1915
+ cutoffDate.setDate(cutoffDate.getDate() - days);
1916
+
1917
+ // Filter memories older than cutoff date
1918
+ const oldMemories = memories.filter((memory) => {
1919
+ const memoryDate = new Date(memory.timestamp || 0);
1920
+ return memoryDate < cutoffDate;
1921
+ });
1922
+
1923
+ if (oldMemories.length === 0) {
1924
+ console.log(chalk.yellow('\n🎉 No old memories found to clean.'));
1925
+ return;
1700
1926
  }
1927
+
1928
+ console.log(chalk.green(`\n✅ Found ${oldMemories.length} old memories to clean.`));
1929
+ console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));
1930
+ console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));
1931
+ } catch (error) {
1932
+ console.error(chalk.red('Error cleaning memories:'), error.message);
1933
+ }
1701
1934
  }
1935
+
1702
1936
  /**
1703
1937
  * Export memory backup
1704
- */ async function exportMemoryBackup() {
1705
- try {
1706
- const { filename } = await inquirer.prompt([
1707
- {
1708
- type: 'input',
1709
- name: 'filename',
1710
- message: 'Export filename:',
1711
- default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`
1712
- }
1713
- ]);
1714
- const mcpWrapper = await getMcpWrapper();
1715
- // Get all memories using search
1716
- const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1717
- // Handle different possible response structures
1718
- let memories = [];
1719
- if (searchResult && Array.isArray(searchResult.results)) {
1720
- memories = searchResult.results;
1721
- } else if (searchResult && Array.isArray(searchResult)) {
1722
- memories = searchResult;
1723
- } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1724
- memories = searchResult.data;
1725
- }
1726
- const backup = {
1727
- exportDate: new Date().toISOString(),
1728
- version: '1.0',
1729
- totalMemories: memories.length,
1730
- namespace: 'hive-mind',
1731
- memories: memories
1732
- };
1733
- const fs = await import("fs");
1734
- fs.writeFileSync(filename, JSON.stringify(backup, null, 2));
1735
- console.log(chalk.green(`\n✅ Memory backup exported to: ${filename}`));
1736
- console.log(chalk.cyan(`Exported ${memories.length} memories`));
1737
- } catch (error) {
1738
- console.error(chalk.red('Error exporting memory backup:'), error.message);
1938
+ */
1939
+ async function exportMemoryBackup() {
1940
+ try {
1941
+ const { filename } = await inquirer.prompt([
1942
+ {
1943
+ type: 'input',
1944
+ name: 'filename',
1945
+ message: 'Export filename:',
1946
+ default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`,
1947
+ },
1948
+ ]);
1949
+
1950
+ const mcpWrapper = await getMcpWrapper();
1951
+
1952
+ // Get all memories using search
1953
+ const searchResult = await mcpWrapper.searchMemory('hive-mind', '');
1954
+
1955
+ // Handle different possible response structures
1956
+ let memories = [];
1957
+ if (searchResult && Array.isArray(searchResult.results)) {
1958
+ memories = searchResult.results;
1959
+ } else if (searchResult && Array.isArray(searchResult)) {
1960
+ memories = searchResult;
1961
+ } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {
1962
+ memories = searchResult.data;
1739
1963
  }
1964
+
1965
+ const backup = {
1966
+ exportDate: new Date().toISOString(),
1967
+ version: '1.0',
1968
+ totalMemories: memories.length,
1969
+ namespace: 'hive-mind',
1970
+ memories: memories,
1971
+ };
1972
+
1973
+ const fs = await import('fs');
1974
+ fs.writeFileSync(filename, JSON.stringify(backup, null, 2));
1975
+
1976
+ console.log(chalk.green(`\n✅ Memory backup exported to: ${filename}`));
1977
+ console.log(chalk.cyan(`Exported ${memories.length} memories`));
1978
+ } catch (error) {
1979
+ console.error(chalk.red('Error exporting memory backup:'), error.message);
1980
+ }
1740
1981
  }
1982
+
1741
1983
  /**
1742
1984
  * Get active session ID for a swarm
1743
- */ async function getActiveSessionId(swarmId) {
1744
- const sessionManager = new HiveMindSessionManager();
1745
- try {
1746
- const sessions = await sessionManager.getActiveSessions();
1747
- const activeSession = sessions.find((s)=>s.swarm_id === swarmId && s.status === 'active');
1748
- return activeSession ? activeSession.id : null;
1749
- } finally{
1750
- sessionManager.close();
1751
- }
1985
+ */
1986
+ async function getActiveSessionId(swarmId) {
1987
+ const sessionManager = new HiveMindSessionManager();
1988
+ try {
1989
+ const sessions = await sessionManager.getActiveSessions();
1990
+ const activeSession = sessions.find((s) => s.swarm_id === swarmId && s.status === 'active');
1991
+ return activeSession ? activeSession.id : null;
1992
+ } finally {
1993
+ sessionManager.close();
1994
+ }
1752
1995
  }
1996
+
1753
1997
  /**
1754
1998
  * Spawn Claude Code with Hive Mind coordination instructions
1755
- */ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {
1756
- console.log('\n' + chalk.bold('🚀 Launching Claude Code with Hive Mind Coordination'));
1999
+ */
2000
+ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {
2001
+ console.log('\n' + chalk.bold('🚀 Launching Claude Code with Hive Mind Coordination'));
2002
+ console.log(chalk.gray('─'.repeat(60)));
2003
+
2004
+ const spinner = ora('Preparing Hive Mind coordination prompt...').start();
2005
+
2006
+ try {
2007
+ // Generate comprehensive Hive Mind prompt
2008
+ const workerGroups = groupWorkersByType(workers);
2009
+ const hiveMindPrompt = generateHiveMindPrompt(
2010
+ swarmId,
2011
+ swarmName,
2012
+ objective,
2013
+ workers,
2014
+ workerGroups,
2015
+ flags,
2016
+ );
2017
+
2018
+ spinner.succeed('Hive Mind coordination prompt ready!');
2019
+
2020
+ // Display coordination summary
2021
+ console.log('\n' + chalk.bold('🧠 Hive Mind Configuration'));
1757
2022
  console.log(chalk.gray('─'.repeat(60)));
1758
- const spinner = ora('Preparing Hive Mind coordination prompt...').start();
2023
+ console.log(chalk.cyan('Swarm ID:'), swarmId);
2024
+ console.log(chalk.cyan('Objective:'), objective);
2025
+ console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');
2026
+ console.log(chalk.cyan('Worker Count:'), workers.length);
2027
+ console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));
2028
+ console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');
2029
+ console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');
2030
+
1759
2031
  try {
1760
- // Generate comprehensive Hive Mind prompt
1761
- const workerGroups = groupWorkersByType(workers);
1762
- const hiveMindPrompt = generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags);
1763
- spinner.succeed('Hive Mind coordination prompt ready!');
1764
- // Display coordination summary
1765
- console.log('\n' + chalk.bold('🧠 Hive Mind Configuration'));
1766
- console.log(chalk.gray(''.repeat(60)));
1767
- console.log(chalk.cyan('Swarm ID:'), swarmId);
1768
- console.log(chalk.cyan('Objective:'), objective);
1769
- console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');
1770
- console.log(chalk.cyan('Worker Count:'), workers.length);
1771
- console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));
1772
- console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');
1773
- console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');
1774
- try {
1775
- // ALWAYS save the prompt file first (fix for issue #330)
1776
- // Ensure sessions directory exists
1777
- const sessionsDir = path.join('.hive-mind', 'sessions');
1778
- await mkdirAsync(sessionsDir, {
1779
- recursive: true
1780
- });
1781
- const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);
1782
- await writeFile(promptFile, hiveMindPrompt, 'utf8');
1783
- console.log(chalk.green(`\n✓ Hive Mind prompt saved to: ${promptFile}`));
1784
- // Check if claude command exists
1785
- const { spawn: childSpawn, execSync } = await import("child_process");
1786
- let claudeAvailable = false;
1787
- try {
1788
- execSync('which claude', {
1789
- stdio: 'ignore'
1790
- });
1791
- claudeAvailable = true;
1792
- } catch {
1793
- console.log(chalk.yellow('\n⚠️ Claude Code CLI not found in PATH'));
1794
- console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));
1795
- console.log(chalk.gray('\nFalling back to displaying instructions...'));
2032
+ // ALWAYS save the prompt file first (fix for issue #330)
2033
+ // Ensure sessions directory exists
2034
+ const sessionsDir = path.join('.hive-mind', 'sessions');
2035
+ await mkdirAsync(sessionsDir, { recursive: true });
2036
+
2037
+ const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);
2038
+ await writeFile(promptFile, hiveMindPrompt, 'utf8');
2039
+ console.log(chalk.green(`\n✓ Hive Mind prompt saved to: ${promptFile}`));
2040
+
2041
+ // Check if claude command exists
2042
+ const { spawn: childSpawn, execSync } = await import('child_process');
2043
+ let claudeAvailable = false;
2044
+
2045
+ try {
2046
+ execSync('which claude', { stdio: 'ignore' });
2047
+ claudeAvailable = true;
2048
+ } catch {
2049
+ console.log(chalk.yellow('\n⚠️ Claude Code CLI not found in PATH'));
2050
+ console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));
2051
+ console.log(chalk.gray('\nFalling back to displaying instructions...'));
2052
+ }
2053
+
2054
+ if (claudeAvailable && !flags.dryRun) {
2055
+ // Check if we should run in non-interactive mode
2056
+ // Respect --non-interactive flag regardless of --claude
2057
+ const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
2058
+
2059
+ // Build arguments in correct order: flags first, then prompt
2060
+ const claudeArgs = [];
2061
+
2062
+ // Add non-interactive flags FIRST if needed
2063
+ if (isNonInteractive) {
2064
+ claudeArgs.push('-p'); // Print mode
2065
+ claudeArgs.push('--output-format', 'stream-json'); // JSON streaming
2066
+ claudeArgs.push('--verbose'); // Verbose output
2067
+ console.log(chalk.cyan('🤖 Running in non-interactive mode'));
2068
+ }
2069
+
2070
+ // Add auto-permission flag BEFORE the prompt
2071
+ if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
2072
+ claudeArgs.push('--dangerously-skip-permissions');
2073
+ if (!isNonInteractive) {
2074
+ console.log(
2075
+ chalk.yellow(
2076
+ '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',
2077
+ ),
2078
+ );
2079
+ }
2080
+ }
2081
+
2082
+ // Add the prompt as the LAST argument
2083
+ claudeArgs.push(hiveMindPrompt);
2084
+
2085
+ // Spawn claude with properly ordered arguments
2086
+ const claudeProcess = childSpawn('claude', claudeArgs, {
2087
+ stdio: 'inherit',
2088
+ shell: false,
2089
+ });
2090
+
2091
+ // Track child process PID in session
2092
+ const sessionManager = new HiveMindSessionManager();
2093
+ const sessionId = await getActiveSessionId(swarmId);
2094
+ if (sessionId && claudeProcess.pid) {
2095
+ sessionManager.addChildPid(sessionId, claudeProcess.pid);
2096
+ }
2097
+
2098
+ // Set up SIGINT handler for automatic session pausing
2099
+ let isExiting = false;
2100
+ const sigintHandler = async () => {
2101
+ if (isExiting) return;
2102
+ isExiting = true;
2103
+
2104
+ console.log('\n\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));
2105
+
2106
+ try {
2107
+ // Terminate Claude Code process
2108
+ if (claudeProcess && !claudeProcess.killed) {
2109
+ claudeProcess.kill('SIGTERM');
1796
2110
  }
1797
- if (claudeAvailable && !flags.dryRun) {
1798
- // Check if we should run in non-interactive mode
1799
- // Respect --non-interactive flag regardless of --claude
1800
- const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
1801
- // Build arguments in correct order: flags first, then prompt
1802
- const claudeArgs = [];
1803
- // Add non-interactive flags FIRST if needed
1804
- if (isNonInteractive) {
1805
- claudeArgs.push('-p'); // Print mode
1806
- claudeArgs.push('--output-format', 'stream-json'); // JSON streaming
1807
- claudeArgs.push('--verbose'); // Verbose output
1808
- console.log(chalk.cyan('🤖 Running in non-interactive mode'));
1809
- }
1810
- // Add auto-permission flag BEFORE the prompt
1811
- if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
1812
- claudeArgs.push('--dangerously-skip-permissions');
1813
- if (!isNonInteractive) {
1814
- console.log(chalk.yellow('🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution'));
1815
- }
1816
- }
1817
- // Add the prompt as the LAST argument
1818
- claudeArgs.push(hiveMindPrompt);
1819
- // Spawn claude with properly ordered arguments
1820
- const claudeProcess = childSpawn('claude', claudeArgs, {
1821
- stdio: 'inherit',
1822
- shell: false
1823
- });
1824
- // Track child process PID in session
1825
- const sessionManager = new HiveMindSessionManager();
1826
- const sessionId = await getActiveSessionId(swarmId);
1827
- if (sessionId && claudeProcess.pid) {
1828
- sessionManager.addChildPid(sessionId, claudeProcess.pid);
1829
- }
1830
- // Set up SIGINT handler for automatic session pausing
1831
- let isExiting = false;
1832
- const sigintHandler = async ()=>{
1833
- if (isExiting) return;
1834
- isExiting = true;
1835
- console.log('\n\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));
1836
- try {
1837
- // Terminate Claude Code process
1838
- if (claudeProcess && !claudeProcess.killed) {
1839
- claudeProcess.kill('SIGTERM');
1840
- }
1841
- // Save checkpoint and pause session
1842
- if (sessionId) {
1843
- const checkpointData = {
1844
- timestamp: new Date().toISOString(),
1845
- swarmId,
1846
- objective,
1847
- status: 'paused_by_user',
1848
- reason: 'User pressed Ctrl+C during Claude Code execution',
1849
- claudePid: claudeProcess.pid
1850
- };
1851
- await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);
1852
- await sessionManager.pauseSession(sessionId);
1853
- console.log(chalk.green('✓') + ' Session paused successfully');
1854
- console.log(chalk.cyan('\nTo resume this session, run:'));
1855
- console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
1856
- }
1857
- sessionManager.close();
1858
- process.exit(0);
1859
- } catch (error) {
1860
- console.error(chalk.red('Error pausing session:'), error.message);
1861
- sessionManager.close();
1862
- process.exit(1);
1863
- }
1864
- };
1865
- // Register SIGINT handler
1866
- process.on('SIGINT', sigintHandler);
1867
- process.on('SIGTERM', sigintHandler);
1868
- // Handle stdout
1869
- if (claudeProcess.stdout) {
1870
- claudeProcess.stdout.on('data', (data)=>{
1871
- console.log(data.toString());
1872
- });
1873
- }
1874
- // Handle stderr
1875
- if (claudeProcess.stderr) {
1876
- claudeProcess.stderr.on('data', (data)=>{
1877
- console.error(chalk.red(data.toString()));
1878
- });
1879
- }
1880
- // Handle process exit
1881
- claudeProcess.on('exit', (code)=>{
1882
- // Remove child PID from session
1883
- if (sessionId && claudeProcess.pid) {
1884
- sessionManager.removeChildPid(sessionId, claudeProcess.pid);
1885
- sessionManager.close();
1886
- }
1887
- if (code === 0) {
1888
- console.log(chalk.green('\n✓ Claude Code completed successfully'));
1889
- } else if (code !== null) {
1890
- console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
1891
- }
1892
- });
1893
- console.log(chalk.green('\n✓ Claude Code launched with Hive Mind coordination'));
1894
- console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));
1895
- console.log(chalk.blue(' Use MCP tools for collective intelligence and task distribution'));
1896
- console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
1897
- } else if (flags.dryRun) {
1898
- console.log(chalk.blue('\nDry run - would execute Claude Code with prompt:'));
1899
- console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');
1900
- console.log(chalk.gray('\nFirst 500 characters of prompt:'));
1901
- console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));
1902
- console.log(chalk.gray(`\nFull prompt saved to: ${promptFile}`));
1903
- } else {
1904
- // Claude not available - show instructions with already saved prompt
1905
- console.log(chalk.yellow('\n📋 Manual Execution Instructions:'));
1906
- console.log(chalk.gray('─'.repeat(50)));
1907
- console.log(chalk.gray('1. Install Claude Code:'));
1908
- console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));
1909
- console.log(chalk.gray('\n2. Run with the saved prompt:'));
1910
- console.log(chalk.green(` claude < ${promptFile}`));
1911
- console.log(chalk.gray('\n3. Or copy the prompt manually:'));
1912
- console.log(chalk.green(` cat ${promptFile} | claude`));
1913
- console.log(chalk.gray('\n4. With auto-permissions:'));
1914
- console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));
2111
+
2112
+ // Save checkpoint and pause session
2113
+ if (sessionId) {
2114
+ const checkpointData = {
2115
+ timestamp: new Date().toISOString(),
2116
+ swarmId,
2117
+ objective,
2118
+ status: 'paused_by_user',
2119
+ reason: 'User pressed Ctrl+C during Claude Code execution',
2120
+ claudePid: claudeProcess.pid,
2121
+ };
2122
+
2123
+ await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);
2124
+ await sessionManager.pauseSession(sessionId);
2125
+
2126
+ console.log(chalk.green('') + ' Session paused successfully');
2127
+ console.log(chalk.cyan('\nTo resume this session, run:'));
2128
+ console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
1915
2129
  }
1916
- } catch (error) {
1917
- console.error(chalk.red('\nFailed to launch Claude Code:'), error.message);
1918
- // Save prompt as fallback
1919
- const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;
1920
- await writeFile(promptFile, hiveMindPrompt, 'utf8');
1921
- console.log(chalk.green(`\n✓ Prompt saved to: ${promptFile}`));
1922
- console.log(chalk.yellow('\nYou can run Claude Code manually with the saved prompt'));
2130
+
2131
+ sessionManager.close();
2132
+ process.exit(0);
2133
+ } catch (error) {
2134
+ console.error(chalk.red('Error pausing session:'), error.message);
2135
+ sessionManager.close();
2136
+ process.exit(1);
2137
+ }
2138
+ };
2139
+
2140
+ // Register SIGINT handler
2141
+ process.on('SIGINT', sigintHandler);
2142
+ process.on('SIGTERM', sigintHandler);
2143
+
2144
+ // Handle stdout
2145
+ if (claudeProcess.stdout) {
2146
+ claudeProcess.stdout.on('data', (data) => {
2147
+ console.log(data.toString());
2148
+ });
1923
2149
  }
1924
- console.log('\n' + chalk.bold('💡 Pro Tips:'));
1925
- console.log(chalk.gray('─'.repeat(30)));
1926
- console.log('• Use --auto-spawn to launch instances automatically');
1927
- console.log(' Add --verbose for detailed coordination context');
1928
- console.log('• Monitor with: claude-flow-novice hive-mind status');
1929
- console.log('• Share memories: mcp__ruv-swarm__memory_usage');
2150
+
2151
+ // Handle stderr
2152
+ if (claudeProcess.stderr) {
2153
+ claudeProcess.stderr.on('data', (data) => {
2154
+ console.error(chalk.red(data.toString()));
2155
+ });
2156
+ }
2157
+
2158
+ // Handle process exit
2159
+ claudeProcess.on('exit', (code) => {
2160
+ // Remove child PID from session
2161
+ if (sessionId && claudeProcess.pid) {
2162
+ sessionManager.removeChildPid(sessionId, claudeProcess.pid);
2163
+ sessionManager.close();
2164
+ }
2165
+
2166
+ if (code === 0) {
2167
+ console.log(chalk.green('\n✓ Claude Code completed successfully'));
2168
+ } else if (code !== null) {
2169
+ console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
2170
+ }
2171
+ });
2172
+
2173
+ console.log(chalk.green('\n✓ Claude Code launched with Hive Mind coordination'));
2174
+ console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));
2175
+ console.log(
2176
+ chalk.blue(' Use MCP tools for collective intelligence and task distribution'),
2177
+ );
2178
+ console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
2179
+ } else if (flags.dryRun) {
2180
+ console.log(chalk.blue('\nDry run - would execute Claude Code with prompt:'));
2181
+ console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');
2182
+ console.log(chalk.gray('\nFirst 500 characters of prompt:'));
2183
+ console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));
2184
+ console.log(chalk.gray(`\nFull prompt saved to: ${promptFile}`));
2185
+ } else {
2186
+ // Claude not available - show instructions with already saved prompt
2187
+ console.log(chalk.yellow('\n📋 Manual Execution Instructions:'));
2188
+ console.log(chalk.gray('─'.repeat(50)));
2189
+ console.log(chalk.gray('1. Install Claude Code:'));
2190
+ console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));
2191
+ console.log(chalk.gray('\n2. Run with the saved prompt:'));
2192
+ console.log(chalk.green(` claude < ${promptFile}`));
2193
+ console.log(chalk.gray('\n3. Or copy the prompt manually:'));
2194
+ console.log(chalk.green(` cat ${promptFile} | claude`));
2195
+ console.log(chalk.gray('\n4. With auto-permissions:'));
2196
+ console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));
2197
+ }
1930
2198
  } catch (error) {
1931
- spinner.fail('Failed to prepare Claude Code coordination');
1932
- console.error(chalk.red('Error:'), error.message);
2199
+ console.error(chalk.red('\nFailed to launch Claude Code:'), error.message);
2200
+
2201
+ // Save prompt as fallback
2202
+ const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;
2203
+ await writeFile(promptFile, hiveMindPrompt, 'utf8');
2204
+ console.log(chalk.green(`\n✓ Prompt saved to: ${promptFile}`));
2205
+ console.log(chalk.yellow('\nYou can run Claude Code manually with the saved prompt'));
1933
2206
  }
2207
+
2208
+ console.log('\n' + chalk.bold('💡 Pro Tips:'));
2209
+ console.log(chalk.gray('─'.repeat(30)));
2210
+ console.log('• Use --auto-spawn to launch instances automatically');
2211
+ console.log('• Add --verbose for detailed coordination context');
2212
+ console.log('• Monitor with: claude-flow-novice hive-mind status');
2213
+ console.log('• Share memories: mcp__ruv-swarm__memory_usage');
2214
+ } catch (error) {
2215
+ spinner.fail('Failed to prepare Claude Code coordination');
2216
+ console.error(chalk.red('Error:'), error.message);
2217
+ }
1934
2218
  }
2219
+
1935
2220
  /**
1936
2221
  * Generate comprehensive Hive Mind prompt for Claude Code
1937
- */ function generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {
1938
- const currentTime = new Date().toISOString();
1939
- const workerTypes = Object.keys(workerGroups);
1940
- const queenType = flags.queenType || 'strategic';
1941
- const consensusAlgorithm = flags.consensus || 'majority';
1942
- return `🧠 HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM
2222
+ */
2223
+ function generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {
2224
+ const currentTime = new Date().toISOString();
2225
+ const workerTypes = Object.keys(workerGroups);
2226
+ const queenType = flags.queenType || 'strategic';
2227
+ const consensusAlgorithm = flags.consensus || 'majority';
2228
+
2229
+ return `🧠 HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM
1943
2230
  ═══════════════════════════════════════════════
1944
2231
 
1945
2232
  You are the Queen coordinator of a Hive Mind swarm with collective intelligence capabilities.
@@ -1954,7 +2241,7 @@ HIVE MIND CONFIGURATION:
1954
2241
  ⏰ Initialized: ${currentTime}
1955
2242
 
1956
2243
  WORKER DISTRIBUTION:
1957
- ${workerTypes.map((type)=>`• ${type}: ${workerGroups[type].length} agents`).join('\n')}
2244
+ ${workerTypes.map((type) => `• ${type}: ${workerGroups[type].length} agents`).join('\n')}
1958
2245
 
1959
2246
  🔧 AVAILABLE MCP TOOLS FOR HIVE MIND COORDINATION:
1960
2247
 
@@ -1996,14 +2283,14 @@ As the Queen coordinator, you must:
1996
2283
 
1997
2284
  Step 1: Optional MCP Coordination Setup (Single Message):
1998
2285
  [MCP Tools - Coordination Only]:
1999
- ${workerTypes.map((type)=>` mcp__claude-flow__agent_spawn { "type": "${type}", "count": ${workerGroups[type].length} }`).join('\n')}
2286
+ ${workerTypes.map((type) => ` mcp__claude-flow__agent_spawn { "type": "${type}", "count": ${workerGroups[type].length} }`).join('\n')}
2000
2287
  mcp__claude-flow__memory_store { "key": "hive/objective", "value": "${objective}" }
2001
2288
  mcp__claude-flow__memory_store { "key": "hive/queen", "value": "${queenType}" }
2002
2289
  mcp__claude-flow__swarm_think { "topic": "initial_strategy" }
2003
2290
 
2004
2291
  Step 2: REQUIRED - Spawn ACTUAL Agents with Claude Code's Task Tool (Single Message):
2005
2292
  [Claude Code Task Tool - CONCURRENT Agent Execution]:
2006
- ${workerTypes.map((type)=>` Task("${type.charAt(0).toUpperCase() + type.slice(1)} Agent", "You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\n')[0]}", "${type}")`).join('\n')}
2293
+ ${workerTypes.map((type) => ` Task("${type.charAt(0).toUpperCase() + type.slice(1)} Agent", "You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\n')[0]}", "${type}")`).join('\n')}
2007
2294
 
2008
2295
  Step 3: Batch ALL Todos Together (Single TodoWrite Call):
2009
2296
  TodoWrite { "todos": [
@@ -2024,21 +2311,33 @@ As the Queen coordinator, you must:
2024
2311
  - Coordinate strategy with swarm_think
2025
2312
 
2026
2313
  3. **QUEEN LEADERSHIP PATTERNS**:
2027
- ${queenType === 'strategic' ? `
2314
+ ${
2315
+ queenType === 'strategic'
2316
+ ? `
2028
2317
  - Focus on high-level planning and coordination
2029
2318
  - Delegate implementation details to workers
2030
2319
  - Monitor overall progress and adjust strategy
2031
- - Make executive decisions when consensus fails` : ''}
2032
- ${queenType === 'tactical' ? `
2320
+ - Make executive decisions when consensus fails`
2321
+ : ''
2322
+ }
2323
+ ${
2324
+ queenType === 'tactical'
2325
+ ? `
2033
2326
  - Manage detailed task breakdowns and assignments
2034
2327
  - Closely monitor worker progress and efficiency
2035
2328
  - Optimize resource allocation and load balancing
2036
- - Intervene directly when workers need guidance` : ''}
2037
- ${queenType === 'adaptive' ? `
2329
+ - Intervene directly when workers need guidance`
2330
+ : ''
2331
+ }
2332
+ ${
2333
+ queenType === 'adaptive'
2334
+ ? `
2038
2335
  - Learn from swarm performance and adapt strategies
2039
2336
  - Experiment with different coordination patterns
2040
2337
  - Use neural training to improve over time
2041
- - Balance between strategic and tactical approaches` : ''}
2338
+ - Balance between strategic and tactical approaches`
2339
+ : ''
2340
+ }
2042
2341
 
2043
2342
  4. **WORKER COORDINATION**:
2044
2343
  - Spawn workers based on task requirements
@@ -2122,51 +2421,64 @@ Initialize the swarm now with the configuration above. Use your collective intel
2122
2421
 
2123
2422
  Remember: You are not just coordinating agents - you are orchestrating a collective intelligence that is greater than the sum of its parts.`;
2124
2423
  }
2424
+
2125
2425
  /**
2126
2426
  * Generate comprehensive coordination instructions for Claude Code instances
2127
- */ function generateCoordinationInstructions(swarmId, swarmName, objective, workers) {
2128
- return {
2129
- swarmId,
2130
- swarmName,
2131
- objective,
2132
- hiveMindEndpoint: 'ws://localhost:3000/hive-mind',
2133
- mcpTools: [
2134
- 'mcp__ruv-swarm__memory_usage',
2135
- 'mcp__ruv-swarm__swarm_monitor',
2136
- 'mcp__ruv-swarm__task_orchestrate',
2137
- 'mcp__ruv-swarm__neural_train',
2138
- 'mcp__ruv-swarm__consensus_vote',
2139
- 'mcp__ruv-swarm__agent_spawn',
2140
- 'mcp__ruv-swarm__swarm_status'
2141
- ],
2142
- coordinationProtocol: {
2143
- memoryNamespace: `hive-mind-${swarmId}`,
2144
- consensusThreshold: 0.7,
2145
- taskUpdateInterval: 30000,
2146
- healthCheckInterval: 60000
2147
- },
2148
- workerCapabilities: workers.map((w)=>({
2149
- id: w.id,
2150
- type: w.type,
2151
- capabilities: JSON.parse(w.capabilities)
2152
- }))
2153
- };
2427
+ */
2428
+ function generateCoordinationInstructions(swarmId, swarmName, objective, workers) {
2429
+ return {
2430
+ swarmId,
2431
+ swarmName,
2432
+ objective,
2433
+ hiveMindEndpoint: 'ws://localhost:3000/hive-mind',
2434
+ mcpTools: [
2435
+ 'mcp__ruv-swarm__memory_usage',
2436
+ 'mcp__ruv-swarm__swarm_monitor',
2437
+ 'mcp__ruv-swarm__task_orchestrate',
2438
+ 'mcp__ruv-swarm__neural_train',
2439
+ 'mcp__ruv-swarm__consensus_vote',
2440
+ 'mcp__ruv-swarm__agent_spawn',
2441
+ 'mcp__ruv-swarm__swarm_status',
2442
+ ],
2443
+ coordinationProtocol: {
2444
+ memoryNamespace: `hive-mind-${swarmId}`,
2445
+ consensusThreshold: 0.7,
2446
+ taskUpdateInterval: 30000,
2447
+ healthCheckInterval: 60000,
2448
+ },
2449
+ workerCapabilities: workers.map((w) => ({
2450
+ id: w.id,
2451
+ type: w.type,
2452
+ capabilities: JSON.parse(w.capabilities),
2453
+ })),
2454
+ };
2154
2455
  }
2456
+
2155
2457
  /**
2156
2458
  * Group workers by type for specialized spawning
2157
- */ function groupWorkersByType(workers) {
2158
- return workers.reduce((groups, worker)=>{
2159
- if (!groups[worker.type]) {
2160
- groups[worker.type] = [];
2161
- }
2162
- groups[worker.type].push(worker);
2163
- return groups;
2164
- }, {});
2459
+ */
2460
+ function groupWorkersByType(workers) {
2461
+ return workers.reduce((groups, worker) => {
2462
+ if (!groups[worker.type]) {
2463
+ groups[worker.type] = [];
2464
+ }
2465
+ groups[worker.type].push(worker);
2466
+ return groups;
2467
+ }, {});
2165
2468
  }
2469
+
2166
2470
  /**
2167
2471
  * Create Claude Code spawn command with coordination context
2168
- */ function createClaudeCodeSpawnCommand(swarmId, swarmName, objective, workerType, typeWorkers, instructions) {
2169
- const context = `You are a ${workerType} agent in the "${swarmName}" Hive Mind swarm.
2472
+ */
2473
+ function createClaudeCodeSpawnCommand(
2474
+ swarmId,
2475
+ swarmName,
2476
+ objective,
2477
+ workerType,
2478
+ typeWorkers,
2479
+ instructions,
2480
+ ) {
2481
+ const context = `You are a ${workerType} agent in the "${swarmName}" Hive Mind swarm.
2170
2482
 
2171
2483
  🎯 MISSION: ${objective}
2172
2484
 
@@ -2205,274 +2517,376 @@ ${getWorkerTypeInstructions(workerType)}
2205
2517
  - Learn from patterns via neural_train
2206
2518
 
2207
2519
  Remember: You are part of a COLLECTIVE INTELLIGENCE. Your individual success depends on swarm coordination!`;
2208
- const command = `claude code --context "${context.replace(/"/g, '\\"')}"`;
2209
- return {
2210
- title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,
2211
- command,
2212
- context,
2213
- workerType,
2214
- count: typeWorkers.length
2215
- };
2520
+
2521
+ const command = `claude code --context "${context.replace(/"/g, '\\"')}"`;
2522
+
2523
+ return {
2524
+ title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,
2525
+ command,
2526
+ context,
2527
+ workerType,
2528
+ count: typeWorkers.length,
2529
+ };
2216
2530
  }
2531
+
2217
2532
  /**
2218
2533
  * Get specialized instructions for each worker type
2219
- */ function getWorkerTypeInstructions(workerType) {
2220
- const instructions = {
2221
- researcher: `- Conduct thorough research using WebSearch and WebFetch
2534
+ */
2535
+ function getWorkerTypeInstructions(workerType) {
2536
+ const instructions = {
2537
+ researcher: `- Conduct thorough research using WebSearch and WebFetch
2222
2538
  - Document findings in structured formats
2223
2539
  - Validate source credibility and relevance
2224
2540
  - Synthesize insights from multiple sources
2225
2541
  - Share research methodology and results`,
2226
- coder: `- Write clean, maintainable, well-documented code
2542
+
2543
+ coder: `- Write clean, maintainable, well-documented code
2227
2544
  - Follow project conventions and best practices
2228
2545
  - Test implementations thoroughly
2229
2546
  - Document code changes and decisions
2230
2547
  - Review and optimize existing code`,
2231
- analyst: `- Analyze data patterns and trends
2548
+
2549
+ analyst: `- Analyze data patterns and trends
2232
2550
  - Create comprehensive reports and visualizations
2233
2551
  - Identify key insights and recommendations
2234
2552
  - Validate analytical methodologies
2235
2553
  - Correlate findings across data sources`,
2236
- tester: `- Design comprehensive test strategies
2554
+
2555
+ tester: `- Design comprehensive test strategies
2237
2556
  - Execute functional, integration, and performance tests
2238
2557
  - Document test results and issues
2239
2558
  - Verify bug fixes and improvements
2240
2559
  - Ensure quality standards and coverage`,
2241
- coordinator: `- Monitor overall progress and coordination
2560
+
2561
+ coordinator: `- Monitor overall progress and coordination
2242
2562
  - Facilitate communication between agents
2243
2563
  - Resolve conflicts and blockers
2244
2564
  - Optimize resource allocation
2245
2565
  - Ensure alignment with objectives`,
2246
- architect: `- Design system architecture and components
2566
+
2567
+ architect: `- Design system architecture and components
2247
2568
  - Define technical standards and patterns
2248
2569
  - Create implementation guidelines
2249
2570
  - Review and approve design decisions
2250
- - Ensure scalability and maintainability`
2251
- };
2252
- return instructions[workerType] || `- Execute tasks according to ${workerType} best practices
2571
+ - Ensure scalability and maintainability`,
2572
+ };
2573
+
2574
+ return (
2575
+ instructions[workerType] ||
2576
+ `- Execute tasks according to ${workerType} best practices
2253
2577
  - Collaborate effectively with team members
2254
2578
  - Document work and share insights
2255
2579
  - Maintain quality standards
2256
- - Contribute to collective objectives`;
2580
+ - Contribute to collective objectives`
2581
+ );
2257
2582
  }
2583
+
2258
2584
  /**
2259
2585
  * Show all hive mind sessions
2260
- */ async function showSessions(flags) {
2261
- try {
2262
- const sessionManager = new HiveMindSessionManager();
2263
- const sessions = await sessionManager.getActiveSessions();
2264
- if (sessions.length === 0) {
2265
- console.log(chalk.gray('No active or paused sessions found'));
2266
- sessionManager.close();
2267
- return;
2268
- }
2269
- console.log(chalk.bold('\n🗂️ Hive Mind Sessions\n'));
2270
- sessions.forEach((session, index)=>{
2271
- const statusColor = session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';
2272
- const statusIcon = session.status === 'active' ? '🟢' : session.status === 'paused' ? '🟡' : '⚫';
2273
- console.log(chalk.yellow('═'.repeat(60)));
2274
- console.log(`${statusIcon} ${chalk.bold(session.swarm_name)}`);
2275
- console.log(chalk.cyan('Session ID:'), session.id);
2276
- console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));
2277
- console.log(chalk.cyan('Objective:'), session.objective);
2278
- console.log(chalk.cyan('Progress:'), `${session.completion_percentage}%`);
2279
- console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());
2280
- console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());
2281
- if (session.paused_at) {
2282
- console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());
2283
- }
2284
- console.log('\n' + chalk.bold('Progress:'));
2285
- console.log(` Agents: ${session.agent_count || 0}`);
2286
- console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);
2287
- if (session.checkpoint_data) {
2288
- console.log('\n' + chalk.bold('Last Checkpoint:'));
2289
- console.log(chalk.gray(JSON.stringify(session.checkpoint_data, null, 2).substring(0, 200) + '...'));
2290
- }
2291
- });
2292
- console.log(chalk.yellow('═'.repeat(60)) + '\n');
2293
- console.log(chalk.blue('💡 Tips:'));
2294
- console.log(' • Resume a session: claude-flow-novice hive-mind resume <session-id>');
2295
- console.log(' • View session details: claude-flow-novice hive-mind status');
2296
- sessionManager.close();
2297
- } catch (error) {
2298
- console.error(chalk.red('Error:'), error.message);
2299
- exit(1);
2586
+ */
2587
+ async function showSessions(flags) {
2588
+ try {
2589
+ const sessionManager = new HiveMindSessionManager();
2590
+ const sessions = await sessionManager.getActiveSessions();
2591
+
2592
+ if (sessions.length === 0) {
2593
+ console.log(chalk.gray('No active or paused sessions found'));
2594
+ sessionManager.close();
2595
+ return;
2300
2596
  }
2597
+
2598
+ console.log(chalk.bold('\n🗂️ Hive Mind Sessions\n'));
2599
+
2600
+ sessions.forEach((session, index) => {
2601
+ const statusColor =
2602
+ session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';
2603
+ const statusIcon =
2604
+ session.status === 'active' ? '🟢' : session.status === 'paused' ? '🟡' : '⚫';
2605
+
2606
+ console.log(chalk.yellow('═'.repeat(60)));
2607
+ console.log(`${statusIcon} ${chalk.bold(session.swarm_name)}`);
2608
+ console.log(chalk.cyan('Session ID:'), session.id);
2609
+ console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));
2610
+ console.log(chalk.cyan('Objective:'), session.objective);
2611
+ console.log(chalk.cyan('Progress:'), `${session.completion_percentage}%`);
2612
+ console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());
2613
+ console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());
2614
+
2615
+ if (session.paused_at) {
2616
+ console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());
2617
+ }
2618
+
2619
+ console.log('\n' + chalk.bold('Progress:'));
2620
+ console.log(` Agents: ${session.agent_count || 0}`);
2621
+ console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);
2622
+
2623
+ if (session.checkpoint_data) {
2624
+ console.log('\n' + chalk.bold('Last Checkpoint:'));
2625
+ console.log(
2626
+ chalk.gray(JSON.stringify(session.checkpoint_data, null, 2).substring(0, 200) + '...'),
2627
+ );
2628
+ }
2629
+ });
2630
+
2631
+ console.log(chalk.yellow('═'.repeat(60)) + '\n');
2632
+
2633
+ console.log(chalk.blue('💡 Tips:'));
2634
+ console.log(' • Resume a session: claude-flow-novice hive-mind resume <session-id>');
2635
+ console.log(' • View session details: claude-flow-novice hive-mind status');
2636
+
2637
+ sessionManager.close();
2638
+ } catch (error) {
2639
+ console.error(chalk.red('Error:'), error.message);
2640
+ exit(1);
2641
+ }
2301
2642
  }
2643
+
2302
2644
  /**
2303
2645
  * Resume a paused hive mind session
2304
- */ async function resumeSession(args, flags) {
2305
- const sessionId = args[0];
2306
- if (!sessionId) {
2307
- console.error(chalk.red('Error: Please provide a session ID'));
2308
- console.log('Usage: claude-flow-novice hive-mind resume <session-id>');
2309
- console.log('Run "claude-flow-novice hive-mind sessions" to see available sessions');
2310
- return;
2646
+ */
2647
+ async function resumeSession(args, flags) {
2648
+ const sessionId = args[0];
2649
+
2650
+ if (!sessionId) {
2651
+ console.error(chalk.red('Error: Please provide a session ID'));
2652
+ console.log('Usage: claude-flow-novice hive-mind resume <session-id>');
2653
+ console.log('Run "claude-flow-novice hive-mind sessions" to see available sessions');
2654
+ return;
2655
+ }
2656
+
2657
+ const spinner = ora('Resuming Hive Mind session...').start();
2658
+
2659
+ try {
2660
+ const sessionManager = new HiveMindSessionManager();
2661
+
2662
+ // Get session details
2663
+ const session = await sessionManager.getSession(sessionId);
2664
+
2665
+ if (!session) {
2666
+ spinner.fail(`Session ${sessionId} not found`);
2667
+ console.log('\nRun "claude-flow-novice hive-mind sessions" to see available sessions');
2668
+ sessionManager.close();
2669
+ return;
2311
2670
  }
2312
- const spinner = ora('Resuming Hive Mind session...').start();
2313
- try {
2314
- const sessionManager = new HiveMindSessionManager();
2315
- // Get session details
2316
- const session = await sessionManager.getSession(sessionId);
2317
- if (!session) {
2318
- spinner.fail(`Session ${sessionId} not found`);
2319
- console.log('\nRun "claude-flow-novice hive-mind sessions" to see available sessions');
2320
- sessionManager.close();
2321
- return;
2322
- }
2323
- // Allow resuming any session regardless of status
2324
- spinner.text = `Resuming session from status: ${session.status}...`;
2325
- if (session.status === 'stopped') {
2326
- spinner.text = 'Restarting stopped session with original configuration...';
2327
- }
2328
- // Resume the session
2329
- const resumedSession = await sessionManager.resumeSession(sessionId);
2330
- spinner.succeed('Session resumed successfully!');
2331
- // Display session summary
2332
- console.log('\n' + chalk.bold('📋 Resumed Session Summary:'));
2333
- console.log(chalk.gray(''.repeat(50)));
2334
- console.log(chalk.cyan('Session ID:'), sessionId);
2335
- console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);
2336
- console.log(chalk.cyan('Objective:'), resumedSession.objective);
2337
- console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);
2338
- console.log(chalk.cyan('Active Agents:'), `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`);
2339
- console.log(chalk.cyan('Tasks:'), `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`);
2340
- console.log(chalk.gray('─'.repeat(50)));
2341
- // Show task breakdown
2342
- console.log('\n' + chalk.bold('📊 Task Status:'));
2343
- console.log(` ✅ Completed: ${resumedSession.statistics.completedTasks}`);
2344
- console.log(` 🔄 In Progress: ${resumedSession.statistics.inProgressTasks}`);
2345
- console.log(` Pending: ${resumedSession.statistics.pendingTasks}`);
2346
- // Show recent activity
2347
- if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {
2348
- console.log('\n' + chalk.bold('📜 Recent Activity:'));
2349
- resumedSession.recentLogs.slice(0, 5).forEach((log)=>{
2350
- const timestamp = new Date(log.timestamp).toLocaleTimeString();
2351
- console.log(` [${timestamp}] ${log.message}`);
2352
- });
2353
- }
2354
- // Restore checkpoint if available
2355
- if (resumedSession.checkpoint_data) {
2356
- console.log('\n' + chalk.bold('♻️ Restoring from checkpoint...'));
2357
- console.log(chalk.gray('Checkpoint data available for restoration'));
2358
- }
2359
- sessionManager.close();
2360
- // Offer to spawn Claude Code with restored context
2361
- if (flags.claude || flags.spawn) {
2362
- console.log('\n' + chalk.yellow('🚀 Launching Claude Code with restored context...'));
2363
- // Generate prompt with session context
2364
- const restoredPrompt = generateRestoredSessionPrompt(resumedSession);
2365
- // Launch Claude Code with restored context
2366
- await launchClaudeWithContext(restoredPrompt, flags, sessionId);
2367
- } else {
2368
- console.log('\n' + chalk.blue('💡 Pro Tip:') + ' Add --claude to spawn Claude Code with restored context');
2369
- console.log(chalk.gray(' claude-flow-novice hive-mind resume ' + sessionId + ' --claude'));
2370
- }
2371
- } catch (error) {
2372
- spinner.fail('Failed to resume session');
2373
- console.error(chalk.red('Error:'), error.message);
2374
- exit(1);
2671
+
2672
+ // Allow resuming any session regardless of status
2673
+ spinner.text = `Resuming session from status: ${session.status}...`;
2674
+
2675
+ if (session.status === 'stopped') {
2676
+ spinner.text = 'Restarting stopped session with original configuration...';
2677
+ }
2678
+
2679
+ // Resume the session
2680
+ const resumedSession = await sessionManager.resumeSession(sessionId);
2681
+
2682
+ spinner.succeed('Session resumed successfully!');
2683
+
2684
+ // Display session summary
2685
+ console.log('\n' + chalk.bold('📋 Resumed Session Summary:'));
2686
+ console.log(chalk.gray('─'.repeat(50)));
2687
+ console.log(chalk.cyan('Session ID:'), sessionId);
2688
+ console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);
2689
+ console.log(chalk.cyan('Objective:'), resumedSession.objective);
2690
+ console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);
2691
+ console.log(
2692
+ chalk.cyan('Active Agents:'),
2693
+ `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`,
2694
+ );
2695
+ console.log(
2696
+ chalk.cyan('Tasks:'),
2697
+ `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`,
2698
+ );
2699
+ console.log(chalk.gray('─'.repeat(50)));
2700
+
2701
+ // Show task breakdown
2702
+ console.log('\n' + chalk.bold('📊 Task Status:'));
2703
+ console.log(` Completed: ${resumedSession.statistics.completedTasks}`);
2704
+ console.log(` 🔄 In Progress: ${resumedSession.statistics.inProgressTasks}`);
2705
+ console.log(` ⏳ Pending: ${resumedSession.statistics.pendingTasks}`);
2706
+
2707
+ // Show recent activity
2708
+ if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {
2709
+ console.log('\n' + chalk.bold('📜 Recent Activity:'));
2710
+ resumedSession.recentLogs.slice(0, 5).forEach((log) => {
2711
+ const timestamp = new Date(log.timestamp).toLocaleTimeString();
2712
+ console.log(` [${timestamp}] ${log.message}`);
2713
+ });
2714
+ }
2715
+
2716
+ // Restore checkpoint if available
2717
+ if (resumedSession.checkpoint_data) {
2718
+ console.log('\n' + chalk.bold('♻️ Restoring from checkpoint...'));
2719
+ console.log(chalk.gray('Checkpoint data available for restoration'));
2720
+ }
2721
+
2722
+ sessionManager.close();
2723
+
2724
+ // Offer to spawn Claude Code with restored context
2725
+ if (flags.claude || flags.spawn) {
2726
+ console.log('\n' + chalk.yellow('🚀 Launching Claude Code with restored context...'));
2727
+
2728
+ // Generate prompt with session context
2729
+ const restoredPrompt = generateRestoredSessionPrompt(resumedSession);
2730
+
2731
+ // Launch Claude Code with restored context
2732
+ await launchClaudeWithContext(restoredPrompt, flags, sessionId);
2733
+ } else {
2734
+ console.log(
2735
+ '\n' +
2736
+ chalk.blue('💡 Pro Tip:') +
2737
+ ' Add --claude to spawn Claude Code with restored context',
2738
+ );
2739
+ console.log(chalk.gray(' claude-flow-novice hive-mind resume ' + sessionId + ' --claude'));
2375
2740
  }
2741
+ } catch (error) {
2742
+ spinner.fail('Failed to resume session');
2743
+ console.error(chalk.red('Error:'), error.message);
2744
+ exit(1);
2745
+ }
2376
2746
  }
2747
+
2377
2748
  /**
2378
2749
  * Stop a hive mind session
2379
- */ async function stopSession(args, flags) {
2380
- const sessionId = args[0];
2381
- if (!sessionId) {
2382
- console.error(chalk.red('Error: Please provide a session ID'));
2383
- console.log('Usage: claude-flow-novice hive-mind stop <session-id>');
2384
- console.log('Run "claude-flow-novice hive-mind sessions" to see available sessions');
2385
- return;
2386
- }
2387
- const spinner = ora('Stopping Hive Mind session...').start();
2388
- try {
2389
- const sessionManager = new HiveMindSessionManager();
2390
- // Get session details
2391
- const session = await sessionManager.getSession(sessionId);
2392
- if (!session) {
2393
- spinner.fail(`Session ${sessionId} not found`);
2394
- console.log('\nRun "claude-flow-novice hive-mind sessions" to see available sessions');
2395
- sessionManager.close();
2396
- return;
2397
- }
2398
- // Stop the session
2399
- await sessionManager.stopSession(sessionId);
2400
- spinner.succeed('Session stopped successfully!');
2401
- // Display session summary
2402
- console.log('\n' + chalk.bold('🛑 Stopped Session Summary:'));
2403
- console.log(chalk.gray('─'.repeat(50)));
2404
- console.log(chalk.cyan('Session ID:'), sessionId);
2405
- console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');
2406
- console.log(chalk.cyan('Final Status:'), 'Stopped');
2407
- console.log(chalk.cyan('Active Agents:'), session.statistics ? session.statistics.activeAgents : 0);
2408
- console.log(chalk.gray('─'.repeat(50)));
2409
- console.log('\n' + chalk.yellow('💡 Session has been stopped and all processes cleaned up.'));
2410
- console.log(chalk.gray('To resume this session later, use: claude-flow-novice hive-mind resume ' + sessionId));
2411
- sessionManager.close();
2412
- } catch (error) {
2413
- spinner.fail('Failed to stop session');
2414
- console.error(chalk.red('Error:'), error.message);
2415
- exit(1);
2750
+ */
2751
+ async function stopSession(args, flags) {
2752
+ const sessionId = args[0];
2753
+
2754
+ if (!sessionId) {
2755
+ console.error(chalk.red('Error: Please provide a session ID'));
2756
+ console.log('Usage: claude-flow-novice hive-mind stop <session-id>');
2757
+ console.log('Run "claude-flow-novice hive-mind sessions" to see available sessions');
2758
+ return;
2759
+ }
2760
+
2761
+ const spinner = ora('Stopping Hive Mind session...').start();
2762
+
2763
+ try {
2764
+ const sessionManager = new HiveMindSessionManager();
2765
+
2766
+ // Get session details
2767
+ const session = await sessionManager.getSession(sessionId);
2768
+
2769
+ if (!session) {
2770
+ spinner.fail(`Session ${sessionId} not found`);
2771
+ console.log('\nRun "claude-flow-novice hive-mind sessions" to see available sessions');
2772
+ sessionManager.close();
2773
+ return;
2416
2774
  }
2775
+
2776
+ // Stop the session
2777
+ await sessionManager.stopSession(sessionId);
2778
+
2779
+ spinner.succeed('Session stopped successfully!');
2780
+
2781
+ // Display session summary
2782
+ console.log('\n' + chalk.bold('🛑 Stopped Session Summary:'));
2783
+ console.log(chalk.gray('─'.repeat(50)));
2784
+ console.log(chalk.cyan('Session ID:'), sessionId);
2785
+ console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');
2786
+ console.log(chalk.cyan('Final Status:'), 'Stopped');
2787
+ console.log(
2788
+ chalk.cyan('Active Agents:'),
2789
+ session.statistics ? session.statistics.activeAgents : 0,
2790
+ );
2791
+ console.log(chalk.gray('─'.repeat(50)));
2792
+
2793
+ console.log('\n' + chalk.yellow('💡 Session has been stopped and all processes cleaned up.'));
2794
+ console.log(
2795
+ chalk.gray('To resume this session later, use: claude-flow-novice hive-mind resume ' + sessionId),
2796
+ );
2797
+
2798
+ sessionManager.close();
2799
+ } catch (error) {
2800
+ spinner.fail('Failed to stop session');
2801
+ console.error(chalk.red('Error:'), error.message);
2802
+ exit(1);
2803
+ }
2417
2804
  }
2805
+
2418
2806
  /**
2419
2807
  * Generate prompt for restored session
2420
- */ function generateRestoredSessionPrompt(session) {
2421
- // Get all agents, not just active ones
2422
- const allAgents = session.agents || [];
2423
- const activeAgents = allAgents.filter((a)=>a.status === 'active' || a.status === 'busy');
2424
- const idleAgents = allAgents.filter((a)=>a.status === 'idle');
2425
- // Get all tasks categorized by status
2426
- const allTasks = session.tasks || [];
2427
- const completedTasks = allTasks.filter((t)=>t.status === 'completed');
2428
- const inProgressTasks = allTasks.filter((t)=>t.status === 'in_progress');
2429
- const pendingTasks = allTasks.filter((t)=>t.status === 'pending');
2430
- // Calculate session duration
2431
- const sessionStart = new Date(session.created_at);
2432
- const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();
2433
- const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes
2434
- // Get more checkpoint history
2435
- const checkpointHistory = session.checkpoints || [];
2436
- // Get more activity logs
2437
- const activityLogs = session.recentLogs || [];
2438
- // Format agent details with their current tasks
2439
- const formatAgentDetails = (agents)=>{
2440
- if (!agents.length) return 'No agents found';
2441
- return agents.map((agent)=>{
2442
- const agentTasks = allTasks.filter((t)=>t.agent_id === agent.id);
2443
- const currentTask = agentTasks.find((t)=>t.status === 'in_progress');
2444
- return `• ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\n └─ Working on: ${currentTask.description}` : ''}`;
2445
- }).join('\n');
2446
- };
2447
- // Format task details with more information
2448
- const formatTaskDetails = (tasks, limit = 15)=>{
2449
- if (!tasks.length) return 'No tasks found';
2450
- const displayTasks = tasks.slice(0, limit);
2451
- return displayTasks.map((task)=>{
2452
- const agent = allAgents.find((a)=>a.id === task.agent_id);
2453
- return `• [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;
2454
- }).join('\n') + (tasks.length > limit ? `\n... and ${tasks.length - limit} more tasks` : '');
2455
- };
2456
- // Format checkpoint details
2457
- const formatCheckpoints = (checkpoints, limit = 5)=>{
2458
- if (!checkpoints.length) return 'No checkpoints found';
2459
- const displayCheckpoints = checkpoints.slice(0, limit);
2460
- return displayCheckpoints.map((cp)=>`• ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`).join('\n');
2461
- };
2462
- // Format activity logs with more detail
2463
- const formatActivityLogs = (logs, limit = 20)=>{
2464
- if (!logs.length) return 'No activity logs found';
2465
- const displayLogs = logs.slice(0, limit);
2466
- return displayLogs.map((log)=>{
2467
- const timestamp = new Date(log.timestamp).toLocaleTimeString();
2468
- const agent = log.agent_id ? allAgents.find((a)=>a.id === log.agent_id) : null;
2469
- return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;
2470
- }).join('\n');
2471
- };
2472
- // Extract metadata if available
2473
- const metadata = session.metadata || {};
2474
- const metadataStr = Object.keys(metadata).length > 0 ? Object.entries(metadata).map(([k, v])=>`• ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`).join('\n') : 'No metadata available';
2475
- return `🔄 RESUMING HIVE MIND SESSION
2808
+ */
2809
+ function generateRestoredSessionPrompt(session) {
2810
+ // Get all agents, not just active ones
2811
+ const allAgents = session.agents || [];
2812
+ const activeAgents = allAgents.filter((a) => a.status === 'active' || a.status === 'busy');
2813
+ const idleAgents = allAgents.filter((a) => a.status === 'idle');
2814
+
2815
+ // Get all tasks categorized by status
2816
+ const allTasks = session.tasks || [];
2817
+ const completedTasks = allTasks.filter((t) => t.status === 'completed');
2818
+ const inProgressTasks = allTasks.filter((t) => t.status === 'in_progress');
2819
+ const pendingTasks = allTasks.filter((t) => t.status === 'pending');
2820
+
2821
+ // Calculate session duration
2822
+ const sessionStart = new Date(session.created_at);
2823
+ const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();
2824
+ const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes
2825
+
2826
+ // Get more checkpoint history
2827
+ const checkpointHistory = session.checkpoints || [];
2828
+
2829
+ // Get more activity logs
2830
+ const activityLogs = session.recentLogs || [];
2831
+
2832
+ // Format agent details with their current tasks
2833
+ const formatAgentDetails = (agents) => {
2834
+ if (!agents.length) return 'No agents found';
2835
+ return agents
2836
+ .map((agent) => {
2837
+ const agentTasks = allTasks.filter((t) => t.agent_id === agent.id);
2838
+ const currentTask = agentTasks.find((t) => t.status === 'in_progress');
2839
+ return `• ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\n └─ Working on: ${currentTask.description}` : ''}`;
2840
+ })
2841
+ .join('\n');
2842
+ };
2843
+
2844
+ // Format task details with more information
2845
+ const formatTaskDetails = (tasks, limit = 15) => {
2846
+ if (!tasks.length) return 'No tasks found';
2847
+ const displayTasks = tasks.slice(0, limit);
2848
+ return (
2849
+ displayTasks
2850
+ .map((task) => {
2851
+ const agent = allAgents.find((a) => a.id === task.agent_id);
2852
+ return `• [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;
2853
+ })
2854
+ .join('\n') + (tasks.length > limit ? `\n... and ${tasks.length - limit} more tasks` : '')
2855
+ );
2856
+ };
2857
+
2858
+ // Format checkpoint details
2859
+ const formatCheckpoints = (checkpoints, limit = 5) => {
2860
+ if (!checkpoints.length) return 'No checkpoints found';
2861
+ const displayCheckpoints = checkpoints.slice(0, limit);
2862
+ return displayCheckpoints
2863
+ .map((cp) => `• ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`)
2864
+ .join('\n');
2865
+ };
2866
+
2867
+ // Format activity logs with more detail
2868
+ const formatActivityLogs = (logs, limit = 20) => {
2869
+ if (!logs.length) return 'No activity logs found';
2870
+ const displayLogs = logs.slice(0, limit);
2871
+ return displayLogs
2872
+ .map((log) => {
2873
+ const timestamp = new Date(log.timestamp).toLocaleTimeString();
2874
+ const agent = log.agent_id ? allAgents.find((a) => a.id === log.agent_id) : null;
2875
+ return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;
2876
+ })
2877
+ .join('\n');
2878
+ };
2879
+
2880
+ // Extract metadata if available
2881
+ const metadata = session.metadata || {};
2882
+ const metadataStr =
2883
+ Object.keys(metadata).length > 0
2884
+ ? Object.entries(metadata)
2885
+ .map(([k, v]) => `• ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`)
2886
+ .join('\n')
2887
+ : 'No metadata available';
2888
+
2889
+ return `🔄 RESUMING HIVE MIND SESSION
2476
2890
  ═══════════════════════════════════
2477
2891
 
2478
2892
  You are resuming a Hive Mind session with comprehensive context:
@@ -2493,7 +2907,7 @@ You are resuming a Hive Mind session with comprehensive context:
2493
2907
  📊 TASK STATISTICS:
2494
2908
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2495
2909
  • Total Tasks: ${session.statistics.totalTasks}
2496
- • Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round(completedTasks.length / session.statistics.totalTasks * 100) : 0}%)
2910
+ • Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round((completedTasks.length / session.statistics.totalTasks) * 100) : 0}%)
2497
2911
  • In Progress: ${inProgressTasks.length}
2498
2912
  • Pending: ${pendingTasks.length}
2499
2913
 
@@ -2560,112 +2974,139 @@ ${formatActivityLogs(activityLogs, 20)}
2560
2974
 
2561
2975
  Resume the hive mind operation with full context awareness and continue working towards the objective.`;
2562
2976
  }
2977
+
2563
2978
  /**
2564
2979
  * Launch Claude Code with context
2565
- */ async function launchClaudeWithContext(prompt, flags, sessionId) {
2980
+ */
2981
+ async function launchClaudeWithContext(prompt, flags, sessionId) {
2982
+ try {
2983
+ // ALWAYS save the prompt file first (fix for issue #330)
2984
+ // Ensure sessions directory exists
2985
+ const sessionsDir = path.join('.hive-mind', 'sessions');
2986
+ await mkdirAsync(sessionsDir, { recursive: true });
2987
+ const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);
2988
+ await writeFile(promptFile, prompt);
2989
+ console.log(chalk.green(`\n✓ Session context saved to: ${promptFile}`));
2990
+
2991
+ const { spawn: childSpawn, execSync } = await import('child_process');
2992
+ let claudeAvailable = false;
2993
+
2566
2994
  try {
2567
- // ALWAYS save the prompt file first (fix for issue #330)
2568
- // Ensure sessions directory exists
2569
- const sessionsDir = path.join('.hive-mind', 'sessions');
2570
- await mkdirAsync(sessionsDir, {
2571
- recursive: true
2572
- });
2573
- const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);
2574
- await writeFile(promptFile, prompt);
2575
- console.log(chalk.green(`\n✓ Session context saved to: ${promptFile}`));
2576
- const { spawn: childSpawn, execSync } = await import("child_process");
2577
- let claudeAvailable = false;
2995
+ execSync('which claude', { stdio: 'ignore' });
2996
+ claudeAvailable = true;
2997
+ } catch {
2998
+ console.log(chalk.yellow('\n⚠️ Claude Code CLI not found'));
2999
+ console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));
3000
+ console.log(chalk.gray(`Run with: claude < ${promptFile}`));
3001
+ return;
3002
+ }
3003
+
3004
+ if (claudeAvailable && !flags.dryRun) {
3005
+ // Debug logging to track spawn calls
3006
+ console.log(chalk.blue('\n🔍 Debug: About to spawn Claude Code process...'));
3007
+ console.log(chalk.gray(` Session ID: ${sessionId}`));
3008
+ console.log(chalk.gray(` Process ID: ${process.pid}`));
3009
+
3010
+ // Remove --print to allow interactive session (same as initial spawn)
3011
+ const claudeArgs = [prompt];
3012
+
3013
+ // Add --dangerously-skip-permissions by default for hive-mind operations
3014
+ // unless explicitly disabled with --no-auto-permissions
3015
+ if (!flags['no-auto-permissions']) {
3016
+ claudeArgs.push('--dangerously-skip-permissions');
3017
+ console.log(
3018
+ chalk.yellow(
3019
+ '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',
3020
+ ),
3021
+ );
3022
+ }
3023
+
3024
+ console.log(
3025
+ chalk.blue('🔍 Debug: Spawning with args:'),
3026
+ claudeArgs.slice(0, 1).map((a) => a.substring(0, 50) + '...'),
3027
+ );
3028
+
3029
+ // Use 'inherit' for interactive session (same as initial spawn)
3030
+ const claudeProcess = childSpawn('claude', claudeArgs, {
3031
+ stdio: 'inherit',
3032
+ shell: false,
3033
+ });
3034
+
3035
+ console.log(chalk.blue('🔍 Debug: Claude process spawned with PID:'), claudeProcess.pid);
3036
+
3037
+ // Track child process PID in session (same as initial spawn)
3038
+ const sessionManager = new HiveMindSessionManager();
3039
+ if (claudeProcess.pid) {
3040
+ const sessions = await sessionManager.getActiveSessions();
3041
+ const currentSession = sessions.find((s) => s.id === sessionId);
3042
+ if (currentSession) {
3043
+ await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);
3044
+ }
3045
+ }
3046
+
3047
+ // Set up SIGINT handler for automatic session pausing (same as initial spawn)
3048
+ let isExiting = false;
3049
+ const sigintHandler = async () => {
3050
+ if (isExiting) return;
3051
+ isExiting = true;
3052
+
3053
+ console.log('\n\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));
3054
+
2578
3055
  try {
2579
- execSync('which claude', {
2580
- stdio: 'ignore'
2581
- });
2582
- claudeAvailable = true;
2583
- } catch {
2584
- console.log(chalk.yellow('\n⚠️ Claude Code CLI not found'));
2585
- console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));
2586
- console.log(chalk.gray(`Run with: claude < ${promptFile}`));
2587
- return;
3056
+ // Terminate Claude Code process if still running
3057
+ if (claudeProcess && !claudeProcess.killed) {
3058
+ claudeProcess.kill('SIGTERM');
3059
+ }
3060
+
3061
+ // Clean up and close session manager
3062
+ sessionManager.close();
3063
+
3064
+ console.log(chalk.green('✓') + ' Session paused successfully');
3065
+ console.log(chalk.cyan('\nTo resume this session, run:'));
3066
+ console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
3067
+ console.log();
3068
+
3069
+ process.exit(0);
3070
+ } catch (error) {
3071
+ console.error(chalk.red('Error during shutdown:'), error.message);
3072
+ process.exit(1);
2588
3073
  }
2589
- if (claudeAvailable && !flags.dryRun) {
2590
- // Debug logging to track spawn calls
2591
- console.log(chalk.blue('\n🔍 Debug: About to spawn Claude Code process...'));
2592
- console.log(chalk.gray(` Session ID: ${sessionId}`));
2593
- console.log(chalk.gray(` Process ID: ${process.pid}`));
2594
- // Remove --print to allow interactive session (same as initial spawn)
2595
- const claudeArgs = [
2596
- prompt
2597
- ];
2598
- // Add --dangerously-skip-permissions by default for hive-mind operations
2599
- // unless explicitly disabled with --no-auto-permissions
2600
- if (!flags['no-auto-permissions']) {
2601
- claudeArgs.push('--dangerously-skip-permissions');
2602
- console.log(chalk.yellow('🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution'));
2603
- }
2604
- console.log(chalk.blue('🔍 Debug: Spawning with args:'), claudeArgs.slice(0, 1).map((a)=>a.substring(0, 50) + '...'));
2605
- // Use 'inherit' for interactive session (same as initial spawn)
2606
- const claudeProcess = childSpawn('claude', claudeArgs, {
2607
- stdio: 'inherit',
2608
- shell: false
2609
- });
2610
- console.log(chalk.blue('🔍 Debug: Claude process spawned with PID:'), claudeProcess.pid);
2611
- // Track child process PID in session (same as initial spawn)
2612
- const sessionManager = new HiveMindSessionManager();
2613
- if (claudeProcess.pid) {
2614
- const sessions = await sessionManager.getActiveSessions();
2615
- const currentSession = sessions.find((s)=>s.id === sessionId);
2616
- if (currentSession) {
2617
- await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);
2618
- }
2619
- }
2620
- // Set up SIGINT handler for automatic session pausing (same as initial spawn)
2621
- let isExiting = false;
2622
- const sigintHandler = async ()=>{
2623
- if (isExiting) return;
2624
- isExiting = true;
2625
- console.log('\n\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));
2626
- try {
2627
- // Terminate Claude Code process if still running
2628
- if (claudeProcess && !claudeProcess.killed) {
2629
- claudeProcess.kill('SIGTERM');
2630
- }
2631
- // Clean up and close session manager
2632
- sessionManager.close();
2633
- console.log(chalk.green('✓') + ' Session paused successfully');
2634
- console.log(chalk.cyan('\nTo resume this session, run:'));
2635
- console.log(chalk.bold(` claude-flow-novice hive-mind resume ${sessionId}`));
2636
- console.log();
2637
- process.exit(0);
2638
- } catch (error) {
2639
- console.error(chalk.red('Error during shutdown:'), error.message);
2640
- process.exit(1);
2641
- }
2642
- };
2643
- process.on('SIGINT', sigintHandler);
2644
- process.on('SIGTERM', sigintHandler);
2645
- // Handle process exit (same as initial spawn)
2646
- claudeProcess.on('exit', async (code, signal)=>{
2647
- if (!isExiting) {
2648
- console.log('\n' + chalk.yellow('Claude Code has exited'));
2649
- // Clean up signal handlers
2650
- process.removeListener('SIGINT', sigintHandler);
2651
- process.removeListener('SIGTERM', sigintHandler);
2652
- // Close session manager
2653
- sessionManager.close();
2654
- process.exit(code || 0);
2655
- }
2656
- });
2657
- console.log(chalk.green('\n✓ Claude Code launched with restored session context'));
2658
- console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
3074
+ };
3075
+
3076
+ process.on('SIGINT', sigintHandler);
3077
+ process.on('SIGTERM', sigintHandler);
3078
+
3079
+ // Handle process exit (same as initial spawn)
3080
+ claudeProcess.on('exit', async (code, signal) => {
3081
+ if (!isExiting) {
3082
+ console.log('\n' + chalk.yellow('Claude Code has exited'));
3083
+
3084
+ // Clean up signal handlers
3085
+ process.removeListener('SIGINT', sigintHandler);
3086
+ process.removeListener('SIGTERM', sigintHandler);
3087
+
3088
+ // Close session manager
3089
+ sessionManager.close();
3090
+
3091
+ process.exit(code || 0);
2659
3092
  }
2660
- } catch (error) {
2661
- console.error(chalk.red('Failed to launch Claude Code:'), error.message);
3093
+ });
3094
+
3095
+ console.log(chalk.green('\n✓ Claude Code launched with restored session context'));
3096
+ console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
2662
3097
  }
3098
+ } catch (error) {
3099
+ console.error(chalk.red('Failed to launch Claude Code:'), error.message);
3100
+ }
2663
3101
  }
3102
+
2664
3103
  /**
2665
3104
  * Get MCP wrapper instance
2666
- */ async function getMcpWrapper() {
2667
- const { MCPToolWrapper } = await import("./hive-mind/mcp-wrapper.js");
2668
- return new MCPToolWrapper();
3105
+ */
3106
+ async function getMcpWrapper() {
3107
+ const { MCPToolWrapper } = await import('./hive-mind/mcp-wrapper.js');
3108
+ return new MCPToolWrapper();
2669
3109
  }
3110
+
2670
3111
  // Export for testing
2671
3112
  export { showHiveMindHelp, initHiveMind, spawnSwarm, showStatus };