claude-flow-novice 1.3.0 → 1.3.2

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 (305) hide show
  1. package/.claude-flow-novice/preferences/generation.json +147 -0
  2. package/.claude-flow-novice/preferences/language-configs/javascript.json +51 -0
  3. package/.claude-flow-novice/preferences/language-configs/python.json +50 -0
  4. package/.claude-flow-novice/preferences/language-configs/rust.json +237 -0
  5. package/.claude-flow-novice/preferences/language-configs/typescript.json +54 -0
  6. package/.claude-flow-novice/preferences/project-local.json +91 -0
  7. package/.claude-flow-novice/preferences/resource-delegation.json +120 -0
  8. package/.claude-flow-novice/preferences/team-shared.json +195 -0
  9. package/.claude-flow-novice/preferences/user-global.json +247 -0
  10. package/.claude-flow-novice/templates/claude-md-templates/CLAUDE-JAVASCRIPT.md +769 -0
  11. package/.claude-flow-novice/templates/claude-md-templates/CLAUDE-PYTHON.md +1214 -0
  12. package/.claude-flow-novice/templates/claude-md-templates/CLAUDE-RUST.md +475 -0
  13. package/.claude-flow-novice/templates/claude-md-templates/CLAUDE-TYPESCRIPT.md +851 -0
  14. package/.claude-flow-novice/templates/claude-md-templates/README.md +263 -0
  15. package/CLAUDE.md +81 -0
  16. package/README-NPM.md +0 -0
  17. package/package.json +11 -7
  18. package/scripts/build/README.md +167 -0
  19. package/scripts/build/build-config.js +27 -0
  20. package/scripts/build/build-prompt-copier.sh +30 -0
  21. package/scripts/build/performance-monitor.js +869 -0
  22. package/scripts/build/prepare-publish.js +150 -0
  23. package/scripts/build/typescript-fixer.js +621 -0
  24. package/scripts/build/unified-builder.sh +428 -0
  25. package/scripts/build/update-bin-version.js +32 -0
  26. package/scripts/dev/README.md +264 -0
  27. package/scripts/dev/claude-flow-wrapper.sh +35 -0
  28. package/scripts/dev/claude-monitor.py +419 -0
  29. package/scripts/dev/claude-sparc.sh +562 -0
  30. package/scripts/dev/claude-wrapper.sh +17 -0
  31. package/scripts/dev/demo-phase3-compliance.js +172 -0
  32. package/scripts/dev/demo-task-system.ts +224 -0
  33. package/scripts/dev/deployment-validator.js +315 -0
  34. package/scripts/dev/spawn-claude-terminal.sh +32 -0
  35. package/scripts/dev/start-portal.sh +506 -0
  36. package/scripts/dev/start-web-ui.js +15 -0
  37. package/scripts/dev/stop-portal.sh +311 -0
  38. package/scripts/dev/validate-examples.ts +288 -0
  39. package/scripts/dev/validate-phase2.cjs +451 -0
  40. package/scripts/dev/validate-phase2.js +785 -0
  41. package/scripts/dev/validate-phase3.cjs +208 -0
  42. package/scripts/dev/validate-security-remediation.js +1 -0
  43. package/scripts/legacy/README.md +272 -0
  44. package/scripts/legacy/batch-fix-ts.sh +54 -0
  45. package/scripts/legacy/build-migration.sh +105 -0
  46. package/scripts/legacy/build-monitor.js +209 -0
  47. package/scripts/legacy/build-with-filter.sh +84 -0
  48. package/scripts/legacy/build-workaround.sh +71 -0
  49. package/scripts/legacy/fix-ts-advanced.js +358 -0
  50. package/scripts/legacy/fix-ts-final.sh +50 -0
  51. package/scripts/legacy/fix-ts-targeted.sh +49 -0
  52. package/scripts/legacy/fix-typescript-errors.js +305 -0
  53. package/scripts/legacy/force-build.sh +63 -0
  54. package/scripts/legacy/optimize-performance.js +400 -0
  55. package/scripts/legacy/performance-monitor.js +263 -0
  56. package/scripts/legacy/performance-monitoring.js +532 -0
  57. package/scripts/legacy/performance-test-runner.js +645 -0
  58. package/scripts/legacy/quick-fix-ts.js +281 -0
  59. package/scripts/legacy/safe-build.sh +63 -0
  60. package/scripts/migration/README.md +434 -0
  61. package/scripts/migration/install-arm64.js +78 -0
  62. package/scripts/migration/install.js +83 -0
  63. package/scripts/migration/migrate-hooks.js +173 -0
  64. package/scripts/migration/migration-examples.ts +318 -0
  65. package/scripts/optimization/build-optimizer.js +438 -0
  66. package/scripts/optimization/config-validator.js +761 -0
  67. package/scripts/optimization/test-optimization.js +432 -0
  68. package/scripts/optimization/unified-activation.js +839 -0
  69. package/scripts/performance/ACTIVATION_COMMANDS.md +292 -0
  70. package/scripts/performance/sqlite-enhanced-activation.sh +583 -0
  71. package/scripts/performance/test-enhanced-backend.sh +504 -0
  72. package/scripts/performance-test-runner.js +698 -0
  73. package/scripts/security/README.md +339 -0
  74. package/scripts/security/install-git-hooks.sh +132 -0
  75. package/scripts/security/ruv-swarm-safe.js +74 -0
  76. package/scripts/test/README.md +236 -0
  77. package/scripts/test/check-links.ts +274 -0
  78. package/scripts/test/check-performance-regression.ts +168 -0
  79. package/scripts/test/coverage-report.ts +692 -0
  80. package/scripts/test/generate-swarm-tests.js +633 -0
  81. package/scripts/test/integration-test-validation.cjs +253 -0
  82. package/scripts/test/load-test-swarm.js +576 -0
  83. package/scripts/test/run-phase3-compliance-tests.js +427 -0
  84. package/scripts/test/test-batch-tasks.ts +29 -0
  85. package/scripts/test/test-byzantine-resolution.js +246 -0
  86. package/scripts/test/test-claude-spawn-options.sh +63 -0
  87. package/scripts/test/test-cli-wizard.js +331 -0
  88. package/scripts/test/test-comprehensive.js +401 -0
  89. package/scripts/test/test-coordination-features.ts +238 -0
  90. package/scripts/test/test-fallback-systems.js +276 -0
  91. package/scripts/test/test-init-command.ts +302 -0
  92. package/scripts/test/test-mcp.ts +251 -0
  93. package/scripts/test/test-runner.ts +568 -0
  94. package/scripts/test/test-swarm-integration.sh +92 -0
  95. package/scripts/test/test-swarm.ts +142 -0
  96. package/scripts/test/validation-summary.ts +408 -0
  97. package/scripts/utils/README.md +261 -0
  98. package/scripts/utils/clean-build-artifacts.sh +94 -0
  99. package/scripts/utils/cleanup-root.sh +69 -0
  100. package/scripts/utils/fix-cliffy-imports.js +307 -0
  101. package/scripts/utils/fix-duplicate-imports.js +114 -0
  102. package/scripts/utils/fix-error-handling.cjs +70 -0
  103. package/scripts/utils/fix-import-paths.js +104 -0
  104. package/scripts/utils/fix-imports.js +116 -0
  105. package/scripts/utils/fix-shebang.js +78 -0
  106. package/scripts/utils/fix-test-modules.js +27 -0
  107. package/scripts/utils/fix-timezone-issue-246.js +200 -0
  108. package/scripts/utils/fix-ts-comprehensive.py +182 -0
  109. package/scripts/utils/fix-ts-targeted-batch.js +250 -0
  110. package/scripts/utils/remove-benchmark-conflicts.sh +140 -0
  111. package/scripts/utils/simple-test-fixer.js +190 -0
  112. package/scripts/utils/validate-metrics-structure.cjs +144 -0
  113. package/scripts/verify-mcp-server.js +86 -0
  114. package/src/cli/simple-commands/__tests__/agent.test.js +291 -0
  115. package/src/cli/simple-commands/__tests__/memory.test.js +8 -0
  116. package/src/cli/simple-commands/__tests__/swarm.test.js +371 -0
  117. package/src/cli/simple-commands/__tests__/task.test.js +8 -0
  118. package/src/cli/simple-commands/agent.js +216 -0
  119. package/src/cli/simple-commands/analysis.js +570 -0
  120. package/src/cli/simple-commands/automation-executor.js +1603 -0
  121. package/src/cli/simple-commands/automation.js +627 -0
  122. package/src/cli/simple-commands/batch-manager.js +338 -0
  123. package/src/cli/simple-commands/claude-telemetry.js +311 -0
  124. package/src/cli/simple-commands/claude-track.js +102 -0
  125. package/src/cli/simple-commands/concurrent-display.js +348 -0
  126. package/src/cli/simple-commands/config.js +319 -0
  127. package/src/cli/simple-commands/coordination.js +307 -0
  128. package/src/cli/simple-commands/enhanced-ui-views.js +654 -0
  129. package/src/cli/simple-commands/enhanced-webui-complete.js +1038 -0
  130. package/src/cli/simple-commands/fix-hook-variables.js +363 -0
  131. package/src/cli/simple-commands/github/gh-coordinator.js +605 -0
  132. package/src/cli/simple-commands/github/github-api.js +624 -0
  133. package/src/cli/simple-commands/github/init.js +543 -0
  134. package/src/cli/simple-commands/github.js +377 -0
  135. package/src/cli/simple-commands/goal.js +145 -0
  136. package/src/cli/simple-commands/hive-mind/auto-save-middleware.js +311 -0
  137. package/src/cli/simple-commands/hive-mind/communication.js +740 -0
  138. package/src/cli/simple-commands/hive-mind/core.js +1031 -0
  139. package/src/cli/simple-commands/hive-mind/db-optimizer.js +872 -0
  140. package/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1364 -0
  141. package/src/cli/simple-commands/hive-mind/memory.js +1292 -0
  142. package/src/cli/simple-commands/hive-mind/performance-optimizer.js +618 -0
  143. package/src/cli/simple-commands/hive-mind/performance-test.js +373 -0
  144. package/src/cli/simple-commands/hive-mind/queen.js +809 -0
  145. package/src/cli/simple-commands/hive-mind/session-manager.js +1223 -0
  146. package/src/cli/simple-commands/hive-mind-optimize.js +361 -0
  147. package/src/cli/simple-commands/hive-mind-wizard.js +281 -0
  148. package/src/cli/simple-commands/hive-mind.js +3112 -0
  149. package/src/cli/simple-commands/hive.js +140 -0
  150. package/src/cli/simple-commands/hook-safety.js +671 -0
  151. package/src/cli/simple-commands/hooks.js +1268 -0
  152. package/src/cli/simple-commands/init/.claude/checkpoints/1756224542.json +7 -0
  153. package/src/cli/simple-commands/init/.claude/checkpoints/1756224544.json +8 -0
  154. package/src/cli/simple-commands/init/README.md +106 -0
  155. package/src/cli/simple-commands/init/VALIDATION_ROLLBACK.md +488 -0
  156. package/src/cli/simple-commands/init/agent-copier.js +347 -0
  157. package/src/cli/simple-commands/init/batch-init.js +663 -0
  158. package/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +438 -0
  159. package/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +876 -0
  160. package/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +356 -0
  161. package/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +501 -0
  162. package/src/cli/simple-commands/init/claude-commands/slash-commands.js +57 -0
  163. package/src/cli/simple-commands/init/claude-commands/sparc-commands.js +296 -0
  164. package/src/cli/simple-commands/init/copy-revised-templates.js +175 -0
  165. package/src/cli/simple-commands/init/executable-wrapper.js +122 -0
  166. package/src/cli/simple-commands/init/gitignore-updater.js +137 -0
  167. package/src/cli/simple-commands/init/help.js +110 -0
  168. package/src/cli/simple-commands/init/hive-mind-init.js +749 -0
  169. package/src/cli/simple-commands/init/index.js +1953 -0
  170. package/src/cli/simple-commands/init/performance-monitor.js +344 -0
  171. package/src/cli/simple-commands/init/rollback/backup-manager.js +542 -0
  172. package/src/cli/simple-commands/init/rollback/index.js +399 -0
  173. package/src/cli/simple-commands/init/rollback/recovery-manager.js +778 -0
  174. package/src/cli/simple-commands/init/rollback/rollback-executor.js +521 -0
  175. package/src/cli/simple-commands/init/rollback/state-tracker.js +486 -0
  176. package/src/cli/simple-commands/init/sparc/roo-readme.js +61 -0
  177. package/src/cli/simple-commands/init/sparc/roomodes-config.js +102 -0
  178. package/src/cli/simple-commands/init/sparc/workflows.js +40 -0
  179. package/src/cli/simple-commands/init/sparc-structure.js +68 -0
  180. package/src/cli/simple-commands/init/template-copier.js +640 -0
  181. package/src/cli/simple-commands/init/templates/CLAUDE.md +1185 -0
  182. package/src/cli/simple-commands/init/templates/CLAUDE.md.optimized +265 -0
  183. package/src/cli/simple-commands/init/templates/claude-flow-universal +81 -0
  184. package/src/cli/simple-commands/init/templates/claude-flow.bat +18 -0
  185. package/src/cli/simple-commands/init/templates/claude-flow.ps1 +24 -0
  186. package/src/cli/simple-commands/init/templates/claude-md.js +1101 -0
  187. package/src/cli/simple-commands/init/templates/commands/analysis/bottleneck-detect.md +162 -0
  188. package/src/cli/simple-commands/init/templates/commands/automation/auto-agent.md +122 -0
  189. package/src/cli/simple-commands/init/templates/commands/coordination/swarm-init.md +85 -0
  190. package/src/cli/simple-commands/init/templates/commands/github/github-swarm.md +121 -0
  191. package/src/cli/simple-commands/init/templates/commands/helpers/standard-checkpoint-hooks.sh +179 -0
  192. package/src/cli/simple-commands/init/templates/commands/hooks/notification.md +113 -0
  193. package/src/cli/simple-commands/init/templates/commands/hooks/post-command.md +116 -0
  194. package/src/cli/simple-commands/init/templates/commands/hooks/post-edit.md +117 -0
  195. package/src/cli/simple-commands/init/templates/commands/hooks/post-task.md +112 -0
  196. package/src/cli/simple-commands/init/templates/commands/hooks/pre-command.md +113 -0
  197. package/src/cli/simple-commands/init/templates/commands/hooks/pre-edit.md +113 -0
  198. package/src/cli/simple-commands/init/templates/commands/hooks/pre-search.md +112 -0
  199. package/src/cli/simple-commands/init/templates/commands/hooks/pre-task.md +111 -0
  200. package/src/cli/simple-commands/init/templates/commands/hooks/session-end.md +118 -0
  201. package/src/cli/simple-commands/init/templates/commands/hooks/session-restore.md +118 -0
  202. package/src/cli/simple-commands/init/templates/commands/hooks/session-start.md +117 -0
  203. package/src/cli/simple-commands/init/templates/coordination-md.js +340 -0
  204. package/src/cli/simple-commands/init/templates/coordination.md +16 -0
  205. package/src/cli/simple-commands/init/templates/enhanced-templates.js +2347 -0
  206. package/src/cli/simple-commands/init/templates/github-safe-enhanced.js +331 -0
  207. package/src/cli/simple-commands/init/templates/github-safe.js +106 -0
  208. package/src/cli/simple-commands/init/templates/memory-bank-md.js +259 -0
  209. package/src/cli/simple-commands/init/templates/memory-bank.md +16 -0
  210. package/src/cli/simple-commands/init/templates/readme-files.js +72 -0
  211. package/src/cli/simple-commands/init/templates/safe-hook-patterns.js +430 -0
  212. package/src/cli/simple-commands/init/templates/settings.json +109 -0
  213. package/src/cli/simple-commands/init/templates/settings.json.enhanced +35 -0
  214. package/src/cli/simple-commands/init/templates/sparc-modes.js +1401 -0
  215. package/src/cli/simple-commands/init/templates/verification-claude-md.js +432 -0
  216. package/src/cli/simple-commands/init/validation/config-validator.js +354 -0
  217. package/src/cli/simple-commands/init/validation/health-checker.js +599 -0
  218. package/src/cli/simple-commands/init/validation/index.js +388 -0
  219. package/src/cli/simple-commands/init/validation/mode-validator.js +387 -0
  220. package/src/cli/simple-commands/init/validation/post-init-validator.js +390 -0
  221. package/src/cli/simple-commands/init/validation/pre-init-validator.js +290 -0
  222. package/src/cli/simple-commands/init/validation/test-runner.js +488 -0
  223. package/src/cli/simple-commands/init.js +4 -0
  224. package/src/cli/simple-commands/mcp-health.js +163 -0
  225. package/src/cli/simple-commands/mcp-integration-layer.js +689 -0
  226. package/src/cli/simple-commands/mcp.js +420 -0
  227. package/src/cli/simple-commands/memory-consolidation.js +631 -0
  228. package/src/cli/simple-commands/memory.js +345 -0
  229. package/src/cli/simple-commands/migrate-hooks.js +63 -0
  230. package/src/cli/simple-commands/monitor.js +417 -0
  231. package/src/cli/simple-commands/neural.js +148 -0
  232. package/src/cli/simple-commands/pair-autofix-only.js +755 -0
  233. package/src/cli/simple-commands/pair-basic.js +751 -0
  234. package/src/cli/simple-commands/pair-old.js +623 -0
  235. package/src/cli/simple-commands/pair-working.js +849 -0
  236. package/src/cli/simple-commands/pair.js +849 -0
  237. package/src/cli/simple-commands/performance-hooks.js +149 -0
  238. package/src/cli/simple-commands/performance-metrics.js +601 -0
  239. package/src/cli/simple-commands/process-ui-enhanced.js +821 -0
  240. package/src/cli/simple-commands/process-ui.js +274 -0
  241. package/src/cli/simple-commands/realtime-update-system.js +659 -0
  242. package/src/cli/simple-commands/sparc/architecture.js +1750 -0
  243. package/src/cli/simple-commands/sparc/commands.js +575 -0
  244. package/src/cli/simple-commands/sparc/completion.js +1831 -0
  245. package/src/cli/simple-commands/sparc/coordinator.js +1045 -0
  246. package/src/cli/simple-commands/sparc/index.js +321 -0
  247. package/src/cli/simple-commands/sparc/phase-base.js +430 -0
  248. package/src/cli/simple-commands/sparc/pseudocode.js +984 -0
  249. package/src/cli/simple-commands/sparc/refinement.js +1856 -0
  250. package/src/cli/simple-commands/sparc/specification.js +736 -0
  251. package/src/cli/simple-commands/sparc-modes/architect.js +125 -0
  252. package/src/cli/simple-commands/sparc-modes/ask.js +126 -0
  253. package/src/cli/simple-commands/sparc-modes/code.js +148 -0
  254. package/src/cli/simple-commands/sparc-modes/debug.js +112 -0
  255. package/src/cli/simple-commands/sparc-modes/devops.js +137 -0
  256. package/src/cli/simple-commands/sparc-modes/docs-writer.js +38 -0
  257. package/src/cli/simple-commands/sparc-modes/generic.js +34 -0
  258. package/src/cli/simple-commands/sparc-modes/index.js +201 -0
  259. package/src/cli/simple-commands/sparc-modes/integration.js +55 -0
  260. package/src/cli/simple-commands/sparc-modes/mcp.js +38 -0
  261. package/src/cli/simple-commands/sparc-modes/monitoring.js +38 -0
  262. package/src/cli/simple-commands/sparc-modes/optimization.js +38 -0
  263. package/src/cli/simple-commands/sparc-modes/security-review.js +130 -0
  264. package/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +167 -0
  265. package/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +38 -0
  266. package/src/cli/simple-commands/sparc-modes/supabase-admin.js +149 -0
  267. package/src/cli/simple-commands/sparc-modes/swarm.js +436 -0
  268. package/src/cli/simple-commands/sparc-modes/tdd.js +112 -0
  269. package/src/cli/simple-commands/sparc-modes/tutorial.js +277 -0
  270. package/src/cli/simple-commands/sparc.js +530 -0
  271. package/src/cli/simple-commands/start-ui.js +147 -0
  272. package/src/cli/simple-commands/start-wrapper.js +285 -0
  273. package/src/cli/simple-commands/start.js +2 -0
  274. package/src/cli/simple-commands/status.js +303 -0
  275. package/src/cli/simple-commands/stream-chain-clean.js +221 -0
  276. package/src/cli/simple-commands/stream-chain-fixed.js +89 -0
  277. package/src/cli/simple-commands/stream-chain-real.js +408 -0
  278. package/src/cli/simple-commands/stream-chain-working.js +323 -0
  279. package/src/cli/simple-commands/stream-chain.js +491 -0
  280. package/src/cli/simple-commands/stream-processor.js +340 -0
  281. package/src/cli/simple-commands/swarm-executor.js +253 -0
  282. package/src/cli/simple-commands/swarm-metrics-integration.js +371 -0
  283. package/src/cli/simple-commands/swarm-ui.js +741 -0
  284. package/src/cli/simple-commands/swarm-webui-integration.js +311 -0
  285. package/src/cli/simple-commands/swarm.js +2277 -0
  286. package/src/cli/simple-commands/task.js +228 -0
  287. package/src/cli/simple-commands/templates/mle-star-workflow.json +294 -0
  288. package/src/cli/simple-commands/timestamp-fix.js +104 -0
  289. package/src/cli/simple-commands/token-tracker.js +372 -0
  290. package/src/cli/simple-commands/tool-execution-framework.js +555 -0
  291. package/src/cli/simple-commands/train-and-stream.js +354 -0
  292. package/src/cli/simple-commands/training-pipeline.js +874 -0
  293. package/src/cli/simple-commands/training.js +288 -0
  294. package/src/cli/simple-commands/verification-hooks.js +336 -0
  295. package/src/cli/simple-commands/verification-integration.js +464 -0
  296. package/src/cli/simple-commands/verification-training-integration.js +646 -0
  297. package/src/cli/simple-commands/verification.js +551 -0
  298. package/src/cli/simple-commands/web-server.js +929 -0
  299. package/src/cli/simple-commands/webui-validator.js +136 -0
  300. package/src/language/README.md +503 -0
  301. package/src/language/claude-md-generator.js +618 -0
  302. package/src/language/cli.js +422 -0
  303. package/src/language/example.js +347 -0
  304. package/src/language/integration-system.js +619 -0
  305. package/src/language/language-detector.js +581 -0
@@ -0,0 +1,1031 @@
1
+ /**
2
+ * Hive Mind Core System
3
+ * Central orchestration and coordination logic
4
+ */
5
+
6
+ import EventEmitter from 'events';
7
+ import { MCPToolWrapper } from './mcp-wrapper.js';
8
+ import { PerformanceOptimizer } from './performance-optimizer.js';
9
+
10
+ /**
11
+ * HiveMindCore - Main orchestration class
12
+ */
13
+ export class HiveMindCore extends EventEmitter {
14
+ constructor(config = {}) {
15
+ super();
16
+
17
+ this.config = {
18
+ objective: '',
19
+ name: `hive-${Date.now()}`,
20
+ queenType: 'strategic',
21
+ maxWorkers: 8,
22
+ consensusAlgorithm: 'majority',
23
+ autoScale: true,
24
+ encryption: false,
25
+ memorySize: 100, // MB
26
+ taskTimeout: 60, // minutes
27
+ ...config,
28
+ };
29
+
30
+ this.state = {
31
+ status: 'initializing',
32
+ swarmId: null,
33
+ queen: null,
34
+ workers: new Map(),
35
+ tasks: new Map(),
36
+ memory: new Map(),
37
+ decisions: new Map(),
38
+ metrics: {
39
+ tasksCreated: 0,
40
+ tasksCompleted: 0,
41
+ decisionsReached: 0,
42
+ memoryUsage: 0,
43
+ },
44
+ };
45
+
46
+ this.mcpWrapper = new MCPToolWrapper({
47
+ parallel: true,
48
+ timeout: this.config.taskTimeout * 60 * 1000,
49
+ });
50
+
51
+ // Initialize performance optimizer
52
+ this.performanceOptimizer = new PerformanceOptimizer({
53
+ enableAsyncQueue: true,
54
+ enableBatchProcessing: true,
55
+ enableAutoTuning: true,
56
+ asyncQueueConcurrency: Math.min(this.config.maxWorkers * 2, 20),
57
+ batchMaxSize: 50,
58
+ metricsInterval: 30000,
59
+ });
60
+
61
+ this._initializeEventHandlers();
62
+ this._initializePerformanceMonitoring();
63
+ }
64
+
65
+ /**
66
+ * Initialize event handlers
67
+ */
68
+ _initializeEventHandlers() {
69
+ this.on('task:created', (task) => {
70
+ this.state.metrics.tasksCreated++;
71
+ this._checkAutoScale();
72
+ });
73
+
74
+ this.on('task:completed', (task) => {
75
+ this.state.metrics.tasksCompleted++;
76
+ this._updatePerformanceMetrics();
77
+ });
78
+
79
+ this.on('task:failed', (data) => {
80
+ console.warn(`Task failed: ${data.task.id}`, data.error);
81
+ this._handleTaskFailure(data.task, data.error);
82
+ });
83
+
84
+ this.on('decision:reached', (decision) => {
85
+ this.state.metrics.decisionsReached++;
86
+ });
87
+
88
+ this.on('worker:idle', (workerId) => {
89
+ this._assignNextTask(workerId);
90
+ });
91
+
92
+ this.on('error', (error) => {
93
+ console.error('Hive Mind Error:', error);
94
+ this._handleError(error);
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Initialize performance monitoring
100
+ */
101
+ _initializePerformanceMonitoring() {
102
+ // Listen to performance optimizer events
103
+ this.performanceOptimizer.on('auto_tune', (data) => {
104
+ console.log(`Performance auto-tuned: ${data.type} = ${data.newValue}`);
105
+ this.emit('performance:auto_tuned', data);
106
+ });
107
+
108
+ this.performanceOptimizer.on('error', (error) => {
109
+ console.error('Performance optimizer error:', error);
110
+ this.emit('error', { type: 'performance_optimizer_error', error });
111
+ });
112
+
113
+ // Periodic performance reporting
114
+ setInterval(() => {
115
+ const stats = this.performanceOptimizer.getPerformanceStats();
116
+ this.emit('performance:stats', stats);
117
+
118
+ // Log performance warnings
119
+ if (parseFloat(stats.asyncQueue.utilization) > 90) {
120
+ console.warn('High async queue utilization:', stats.asyncQueue.utilization + '%');
121
+ }
122
+
123
+ if (parseFloat(stats.asyncQueue.successRate) < 95) {
124
+ console.warn('Low async operation success rate:', stats.asyncQueue.successRate + '%');
125
+ }
126
+ }, 60000); // Every minute
127
+ }
128
+
129
+ /**
130
+ * Handle task failure with recovery logic
131
+ */
132
+ _handleTaskFailure(task, error) {
133
+ // Update metrics
134
+ this.state.metrics.tasksFailed = (this.state.metrics.tasksFailed || 0) + 1;
135
+
136
+ // Attempt task retry for recoverable failures
137
+ if (task.retryCount < 2 && this._isRecoverableError(error)) {
138
+ task.retryCount = (task.retryCount || 0) + 1;
139
+ task.status = 'pending';
140
+
141
+ // Find another worker for retry
142
+ setTimeout(() => {
143
+ const worker = this._findBestWorker(task);
144
+ if (worker) {
145
+ this._assignTask(worker.id, task.id);
146
+ }
147
+ }, 5000); // Wait 5 seconds before retry
148
+
149
+ console.log(`Retrying task ${task.id} (attempt ${task.retryCount})`);
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Check if error is recoverable
155
+ */
156
+ _isRecoverableError(error) {
157
+ const recoverableErrors = ['timeout', 'network', 'temporary', 'connection'];
158
+
159
+ return recoverableErrors.some((type) => error.message.toLowerCase().includes(type));
160
+ }
161
+
162
+ /**
163
+ * Initialize the hive mind swarm
164
+ */
165
+ async initialize() {
166
+ try {
167
+ this.state.status = 'initializing';
168
+
169
+ // Initialize swarm with MCP tools
170
+ const [swarmInit, memoryInit, neuralInit] = await this.mcpWrapper.initializeSwarm({
171
+ topology: this._determineTopology(),
172
+ maxAgents: this.config.maxWorkers + 1, // +1 for queen
173
+ swarmId: this.config.name,
174
+ });
175
+
176
+ this.state.swarmId = swarmInit.swarmId;
177
+
178
+ // Store initial configuration in memory
179
+ await this.mcpWrapper.storeMemory(this.state.swarmId, 'config', this.config, 'system');
180
+
181
+ this.state.status = 'ready';
182
+ this.emit('initialized', { swarmId: this.state.swarmId });
183
+
184
+ return this.state.swarmId;
185
+ } catch (error) {
186
+ this.state.status = 'error';
187
+ this.emit('error', error);
188
+ throw error;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Determine optimal topology based on objective
194
+ */
195
+ _determineTopology() {
196
+ const objective = this.config.objective.toLowerCase();
197
+
198
+ // Heuristic topology selection
199
+ if (objective.includes('research') || objective.includes('analysis')) {
200
+ return 'mesh'; // Peer-to-peer for collaborative research
201
+ } else if (objective.includes('build') || objective.includes('develop')) {
202
+ return 'hierarchical'; // Clear command structure for development
203
+ } else if (objective.includes('monitor') || objective.includes('maintain')) {
204
+ return 'ring'; // Circular for continuous monitoring
205
+ } else if (objective.includes('coordinate') || objective.includes('orchestrate')) {
206
+ return 'star'; // Centralized for coordination
207
+ }
208
+
209
+ return 'hierarchical'; // Default
210
+ }
211
+
212
+ /**
213
+ * Spawn the queen coordinator
214
+ */
215
+ async spawnQueen(queenData) {
216
+ const [spawnResult] = await this.mcpWrapper.spawnAgents(['coordinator'], this.state.swarmId);
217
+
218
+ this.state.queen = {
219
+ id: queenData.id,
220
+ agentId: spawnResult.agentId,
221
+ type: this.config.queenType,
222
+ status: 'active',
223
+ decisions: 0,
224
+ tasks: 0,
225
+ };
226
+
227
+ // Store queen info in memory
228
+ await this.mcpWrapper.storeMemory(this.state.swarmId, 'queen', this.state.queen, 'system');
229
+
230
+ this.emit('queen:spawned', this.state.queen);
231
+ return this.state.queen;
232
+ }
233
+
234
+ /**
235
+ * Spawn worker agents with batch optimization
236
+ */
237
+ async spawnWorkers(workerTypes) {
238
+ const startTime = Date.now();
239
+
240
+ try {
241
+ // Batch spawn agents in parallel with optimized chunking
242
+ const chunkSize = Math.min(workerTypes.length, 5); // Optimal batch size
243
+ const chunks = [];
244
+
245
+ for (let i = 0; i < workerTypes.length; i += chunkSize) {
246
+ chunks.push(workerTypes.slice(i, i + chunkSize));
247
+ }
248
+
249
+ // Process chunks in parallel with Promise.all
250
+ const allResults = await Promise.all(
251
+ chunks.map((chunk) => this.mcpWrapper.spawnAgents(chunk, this.state.swarmId)),
252
+ );
253
+
254
+ // Flatten results
255
+ const spawnResults = allResults.flat();
256
+
257
+ // Batch create worker objects
258
+ const workers = [];
259
+ const workerUpdates = [];
260
+
261
+ spawnResults.forEach((result, index) => {
262
+ const worker = {
263
+ id: `worker-${index}`,
264
+ agentId: result.agentId,
265
+ type: workerTypes[index],
266
+ status: 'idle',
267
+ tasksCompleted: 0,
268
+ currentTask: null,
269
+ spawnedAt: Date.now(),
270
+ performance: {
271
+ avgTaskTime: 0,
272
+ successRate: 1.0,
273
+ },
274
+ };
275
+
276
+ workers.push(worker);
277
+ this.state.workers.set(worker.id, worker);
278
+
279
+ workerUpdates.push({
280
+ type: 'worker_spawned',
281
+ workerId: worker.id,
282
+ workerType: worker.type,
283
+ timestamp: worker.spawnedAt,
284
+ });
285
+ });
286
+
287
+ // Batch memory operations
288
+ await Promise.all([
289
+ this.mcpWrapper.storeMemory(this.state.swarmId, 'workers', workers, 'system'),
290
+ this.mcpWrapper.storeMemory(
291
+ this.state.swarmId,
292
+ 'worker_spawn_batch',
293
+ {
294
+ count: workers.length,
295
+ types: workerTypes,
296
+ spawnTime: Date.now() - startTime,
297
+ updates: workerUpdates,
298
+ },
299
+ 'metrics',
300
+ ),
301
+ ]);
302
+
303
+ // Emit batch completion event
304
+ this.emit('workers:spawned', {
305
+ count: this.state.workers.size,
306
+ batchSize: workers.length,
307
+ spawnTime: Date.now() - startTime,
308
+ workers: workers,
309
+ });
310
+
311
+ return workers;
312
+ } catch (error) {
313
+ this.emit('error', {
314
+ type: 'spawn_batch_failed',
315
+ error,
316
+ workerTypes,
317
+ spawnTime: Date.now() - startTime,
318
+ });
319
+ throw error;
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Create and distribute task with performance optimization
325
+ */
326
+ async createTask(description, priority = 5, metadata = {}) {
327
+ const timestamp = Date.now();
328
+ const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr
329
+ const taskId = `task-${timestamp}-${randomPart}`;
330
+ const createdAt = Date.now();
331
+
332
+ const task = {
333
+ id: taskId,
334
+ swarmId: this.state.swarmId,
335
+ description,
336
+ priority,
337
+ status: 'pending',
338
+ createdAt: new Date(createdAt).toISOString(),
339
+ assignedTo: null,
340
+ result: null,
341
+ metadata: {
342
+ estimatedDuration: this._estimateTaskDuration(description),
343
+ complexity: this._analyzeTaskComplexity(description),
344
+ ...metadata,
345
+ },
346
+ };
347
+
348
+ // Parallel operations: task storage, orchestration, and worker finding
349
+ const [orchestrateResult, bestWorker] = await Promise.all([
350
+ this.mcpWrapper.orchestrateTask(description, 'adaptive'),
351
+ this._findBestWorkerAsync(task),
352
+ // Store task immediately in parallel
353
+ (async () => {
354
+ this.state.tasks.set(task.id, task);
355
+ await this.mcpWrapper.storeMemory(this.state.swarmId, `task-${task.id}`, task, 'task');
356
+ })(),
357
+ ]);
358
+
359
+ task.orchestrationId = orchestrateResult[0].taskId;
360
+
361
+ this.emit('task:created', task);
362
+
363
+ // Assign task if worker available
364
+ if (bestWorker) {
365
+ // Use non-blocking assignment
366
+ setImmediate(() => this._assignTask(bestWorker.id, task.id));
367
+ }
368
+
369
+ return task;
370
+ }
371
+
372
+ /**
373
+ * Estimate task duration based on description analysis
374
+ */
375
+ _estimateTaskDuration(description) {
376
+ const words = description.toLowerCase().split(/\s+/);
377
+ const complexityKeywords = {
378
+ simple: ['list', 'show', 'display', 'get', 'read'],
379
+ medium: ['create', 'update', 'modify', 'change', 'build'],
380
+ complex: ['analyze', 'optimize', 'refactor', 'implement', 'design'],
381
+ };
382
+
383
+ let score = 1;
384
+ for (const word of words) {
385
+ if (complexityKeywords.complex.includes(word)) score += 3;
386
+ else if (complexityKeywords.medium.includes(word)) score += 2;
387
+ else if (complexityKeywords.simple.includes(word)) score += 1;
388
+ }
389
+
390
+ return Math.min(score * 5000, 60000); // Cap at 1 minute
391
+ }
392
+
393
+ /**
394
+ * Analyze task complexity
395
+ */
396
+ _analyzeTaskComplexity(description) {
397
+ const words = description.toLowerCase().split(/\s+/);
398
+ const indicators = {
399
+ high: ['optimize', 'refactor', 'architecture', 'design', 'algorithm'],
400
+ medium: ['implement', 'build', 'create', 'develop', 'integrate'],
401
+ low: ['list', 'show', 'get', 'read', 'display'],
402
+ };
403
+
404
+ for (const [level, keywords] of Object.entries(indicators)) {
405
+ if (keywords.some((keyword) => words.includes(keyword))) {
406
+ return level;
407
+ }
408
+ }
409
+
410
+ return 'medium';
411
+ }
412
+
413
+ /**
414
+ * Find best worker for task (optimized async version)
415
+ */
416
+ async _findBestWorkerAsync(task) {
417
+ const availableWorkers = Array.from(this.state.workers.values()).filter(
418
+ (w) => w.status === 'idle',
419
+ );
420
+
421
+ if (availableWorkers.length === 0) {
422
+ return null;
423
+ }
424
+
425
+ // Use cached analysis if available
426
+ const cacheKey = `worker_match_${task.description.substring(0, 50)}`;
427
+ const cachedMatch = await this.mcpWrapper.retrieveMemory(this.state.swarmId, cacheKey);
428
+
429
+ if (cachedMatch && cachedMatch.timestamp > Date.now() - 300000) {
430
+ // 5 min cache
431
+ const cachedWorker = availableWorkers.find((w) => w.type === cachedMatch.workerType);
432
+ if (cachedWorker) return cachedWorker;
433
+ }
434
+
435
+ // Enhanced matching algorithm with performance scoring
436
+ const taskLower = task.description.toLowerCase();
437
+ const taskWords = taskLower.split(/\s+/);
438
+
439
+ // Enhanced priority mapping with weights
440
+ const priorityMap = {
441
+ researcher: {
442
+ keywords: ['research', 'investigate', 'analyze', 'study', 'explore'],
443
+ weight: 1.2,
444
+ },
445
+ coder: {
446
+ keywords: ['code', 'implement', 'build', 'develop', 'fix', 'create', 'program'],
447
+ weight: 1.0,
448
+ },
449
+ analyst: {
450
+ keywords: ['analyze', 'data', 'metrics', 'performance', 'report', 'statistics'],
451
+ weight: 1.1,
452
+ },
453
+ tester: { keywords: ['test', 'validate', 'check', 'verify', 'quality', 'qa'], weight: 1.0 },
454
+ architect: {
455
+ keywords: ['design', 'architecture', 'structure', 'plan', 'system'],
456
+ weight: 1.3,
457
+ },
458
+ reviewer: { keywords: ['review', 'feedback', 'improve', 'refactor', 'audit'], weight: 1.0 },
459
+ optimizer: {
460
+ keywords: ['optimize', 'performance', 'speed', 'efficiency', 'enhance'],
461
+ weight: 1.4,
462
+ },
463
+ documenter: { keywords: ['document', 'explain', 'write', 'describe', 'manual'], weight: 0.9 },
464
+ };
465
+
466
+ // Calculate scores for each worker
467
+ const workerScores = availableWorkers.map((worker) => {
468
+ const typeInfo = priorityMap[worker.type] || { keywords: [], weight: 1.0 };
469
+
470
+ // Keyword matching score
471
+ const keywordScore = typeInfo.keywords.reduce((score, keyword) => {
472
+ return score + (taskWords.includes(keyword) ? 1 : 0);
473
+ }, 0);
474
+
475
+ // Performance history score
476
+ const performanceScore = worker.performance
477
+ ? worker.performance.successRate * 0.5 + (1 / (worker.performance.avgTaskTime + 1)) * 0.5
478
+ : 0.5;
479
+
480
+ // Task completion rate
481
+ const completionScore =
482
+ worker.tasksCompleted > 0 ? Math.min(worker.tasksCompleted / 10, 1) : 0;
483
+
484
+ // Combined score
485
+ const totalScore =
486
+ (keywordScore * 2 + // Keyword relevance
487
+ performanceScore * 1.5 + // Historical performance
488
+ completionScore * 1.0) * // Experience
489
+ typeInfo.weight;
490
+
491
+ return {
492
+ worker,
493
+ score: totalScore,
494
+ breakdown: {
495
+ keyword: keywordScore,
496
+ performance: performanceScore,
497
+ completion: completionScore,
498
+ weight: typeInfo.weight,
499
+ },
500
+ };
501
+ });
502
+
503
+ // Sort by score and select best
504
+ workerScores.sort((a, b) => b.score - a.score);
505
+ const bestMatch = workerScores[0];
506
+
507
+ // Cache the result for future use
508
+ if (bestMatch.score > 0) {
509
+ setImmediate(async () => {
510
+ await this.mcpWrapper.storeMemory(
511
+ this.state.swarmId,
512
+ cacheKey,
513
+ {
514
+ workerType: bestMatch.worker.type,
515
+ score: bestMatch.score,
516
+ timestamp: Date.now(),
517
+ },
518
+ 'cache',
519
+ );
520
+ });
521
+ }
522
+
523
+ return bestMatch ? bestMatch.worker : availableWorkers[0];
524
+ }
525
+
526
+ /**
527
+ * Synchronous version for backward compatibility
528
+ */
529
+ _findBestWorker(task) {
530
+ const availableWorkers = Array.from(this.state.workers.values()).filter(
531
+ (w) => w.status === 'idle',
532
+ );
533
+
534
+ if (availableWorkers.length === 0) {
535
+ return null;
536
+ }
537
+
538
+ // Simplified scoring for sync version
539
+ const taskLower = task.description.toLowerCase();
540
+ const priorityMap = {
541
+ researcher: ['research', 'investigate', 'analyze', 'study'],
542
+ coder: ['code', 'implement', 'build', 'develop', 'fix', 'create'],
543
+ analyst: ['analyze', 'data', 'metrics', 'performance', 'report'],
544
+ tester: ['test', 'validate', 'check', 'verify', 'quality'],
545
+ architect: ['design', 'architecture', 'structure', 'plan'],
546
+ reviewer: ['review', 'feedback', 'improve', 'refactor'],
547
+ optimizer: ['optimize', 'performance', 'speed', 'efficiency'],
548
+ documenter: ['document', 'explain', 'write', 'describe'],
549
+ };
550
+
551
+ let bestWorker = null;
552
+ let bestScore = 0;
553
+
554
+ for (const worker of availableWorkers) {
555
+ const keywords = priorityMap[worker.type] || [];
556
+ const keywordScore = keywords.filter((k) => taskLower.includes(k)).length;
557
+ const performanceBonus = worker.performance ? worker.performance.successRate * 0.5 : 0;
558
+ const totalScore = keywordScore + performanceBonus;
559
+
560
+ if (totalScore > bestScore) {
561
+ bestScore = totalScore;
562
+ bestWorker = worker;
563
+ }
564
+ }
565
+
566
+ return bestWorker || availableWorkers[0];
567
+ }
568
+
569
+ /**
570
+ * Assign task to worker
571
+ */
572
+ async _assignTask(workerId, taskId) {
573
+ const worker = this.state.workers.get(workerId);
574
+ const task = this.state.tasks.get(taskId);
575
+
576
+ if (!worker || !task) return;
577
+
578
+ worker.status = 'busy';
579
+ worker.currentTask = taskId;
580
+ task.status = 'in_progress';
581
+ task.assignedTo = workerId;
582
+
583
+ // Store assignment in memory
584
+ await this.mcpWrapper.storeMemory(
585
+ this.state.swarmId,
586
+ `assignment-${taskId}`,
587
+ { workerId, taskId, timestamp: Date.now() },
588
+ 'task',
589
+ );
590
+
591
+ this.emit('task:assigned', { workerId, taskId });
592
+
593
+ // Simulate task execution
594
+ this._executeTask(workerId, taskId);
595
+ }
596
+
597
+ /**
598
+ * Execute task with performance optimization
599
+ */
600
+ async _executeTask(workerId, taskId) {
601
+ const worker = this.state.workers.get(workerId);
602
+ const task = this.state.tasks.get(taskId);
603
+ const startTime = Date.now();
604
+
605
+ try {
606
+ // Use performance optimizer for async execution
607
+ const result = await this.performanceOptimizer.optimizeAsyncOperation(
608
+ async () => {
609
+ // Simulate task execution based on complexity
610
+ const baseDuration = {
611
+ low: 5000,
612
+ medium: 15000,
613
+ high: 30000,
614
+ }[task.metadata?.complexity || 'medium'];
615
+
616
+ const duration = baseDuration + Math.random() * baseDuration * 0.5;
617
+
618
+ return new Promise((resolve) => {
619
+ setTimeout(() => {
620
+ resolve({
621
+ status: 'completed',
622
+ result: `Task completed by ${worker.type} worker`,
623
+ processingTime: Date.now() - startTime,
624
+ complexity: task.metadata?.complexity || 'medium',
625
+ });
626
+ }, duration);
627
+ });
628
+ },
629
+ { priority: task.priority },
630
+ );
631
+
632
+ // Update task and worker
633
+ task.status = 'completed';
634
+ task.completedAt = new Date().toISOString();
635
+ task.result = result.result;
636
+ task.actualDuration = result.processingTime;
637
+
638
+ worker.status = 'idle';
639
+ worker.currentTask = null;
640
+ worker.tasksCompleted++;
641
+
642
+ // Update worker performance metrics
643
+ if (!worker.performance.avgTaskTime) {
644
+ worker.performance.avgTaskTime = result.processingTime;
645
+ } else {
646
+ worker.performance.avgTaskTime =
647
+ (worker.performance.avgTaskTime * (worker.tasksCompleted - 1) + result.processingTime) /
648
+ worker.tasksCompleted;
649
+ }
650
+
651
+ // Batch store results for better performance
652
+ await this.performanceOptimizer.optimizeBatchOperation(
653
+ 'task_results',
654
+ {
655
+ key: `result-${taskId}`,
656
+ value: task,
657
+ type: 'result',
658
+ },
659
+ async (items) => {
660
+ // Batch store all results
661
+ await Promise.all(
662
+ items.map((item) =>
663
+ this.mcpWrapper.storeMemory(this.state.swarmId, item.key, item.value, item.type),
664
+ ),
665
+ );
666
+ return items.map(() => ({ success: true }));
667
+ },
668
+ );
669
+
670
+ this.emit('task:completed', task);
671
+ this.emit('worker:idle', workerId);
672
+ } catch (error) {
673
+ // Handle task failure
674
+ task.status = 'failed';
675
+ task.error = error.message;
676
+ task.failedAt = new Date().toISOString();
677
+
678
+ worker.status = 'idle';
679
+ worker.currentTask = null;
680
+ worker.performance.successRate =
681
+ (worker.performance.successRate * worker.tasksCompleted) / (worker.tasksCompleted + 1);
682
+
683
+ this.emit('task:failed', { task, error });
684
+ this.emit('worker:idle', workerId);
685
+ }
686
+ }
687
+
688
+ /**
689
+ * Assign next task to idle worker
690
+ */
691
+ _assignNextTask(workerId) {
692
+ const pendingTasks = Array.from(this.state.tasks.values())
693
+ .filter((t) => t.status === 'pending')
694
+ .sort((a, b) => b.priority - a.priority);
695
+
696
+ if (pendingTasks.length > 0) {
697
+ this._assignTask(workerId, pendingTasks[0].id);
698
+ }
699
+ }
700
+
701
+ /**
702
+ * Build consensus for decision
703
+ */
704
+ async buildConsensus(topic, options) {
705
+ const decision = {
706
+ id: `decision-${Date.now()}`,
707
+ swarmId: this.state.swarmId,
708
+ topic,
709
+ options,
710
+ votes: new Map(),
711
+ algorithm: this.config.consensusAlgorithm,
712
+ status: 'voting',
713
+ createdAt: new Date().toISOString(),
714
+ };
715
+
716
+ this.state.decisions.set(decision.id, decision);
717
+
718
+ // Simulate voting process
719
+ const workers = Array.from(this.state.workers.values());
720
+ const votes = {};
721
+
722
+ // Each worker votes
723
+ workers.forEach((worker) => {
724
+ const vote = options[Math.floor(Math.random() * options.length)];
725
+ votes[worker.id] = vote;
726
+ decision.votes.set(worker.id, vote);
727
+ });
728
+
729
+ // Queen gets weighted vote
730
+ const queenVote = options[Math.floor(Math.random() * options.length)];
731
+ votes['queen'] = queenVote;
732
+ decision.votes.set('queen', queenVote);
733
+
734
+ // Calculate consensus
735
+ const result = this._calculateConsensus(decision);
736
+ decision.result = result.decision;
737
+ decision.confidence = result.confidence;
738
+ decision.status = 'completed';
739
+
740
+ // Convert Map to plain object for proper JSON serialization
741
+ const decisionForStorage = {
742
+ ...decision,
743
+ votes: decision.votes instanceof Map ? Object.fromEntries(decision.votes) : decision.votes,
744
+ };
745
+
746
+ // Store decision in memory
747
+ await this.mcpWrapper.storeMemory(
748
+ this.state.swarmId,
749
+ `decision-${decision.id}`,
750
+ decisionForStorage,
751
+ 'consensus',
752
+ );
753
+
754
+ this.emit('decision:reached', decision);
755
+ return decision;
756
+ }
757
+
758
+ /**
759
+ * Calculate consensus based on algorithm
760
+ */
761
+ _calculateConsensus(decision) {
762
+ const votes = Array.from(decision.votes.values());
763
+ const voteCount = {};
764
+
765
+ // Count votes
766
+ votes.forEach((vote) => {
767
+ voteCount[vote] = (voteCount[vote] || 0) + 1;
768
+ });
769
+
770
+ switch (decision.algorithm) {
771
+ case 'majority':
772
+ // Simple majority
773
+ const sorted = Object.entries(voteCount).sort((a, b) => b[1] - a[1]);
774
+ const winner = sorted[0];
775
+ return {
776
+ decision: winner[0],
777
+ confidence: winner[1] / votes.length,
778
+ };
779
+
780
+ case 'weighted':
781
+ // Weight queen vote more heavily
782
+ const queenVote = decision.votes.get('queen');
783
+ voteCount[queenVote] = (voteCount[queenVote] || 0) + 2; // Queen counts as 3 votes
784
+
785
+ const weightedSorted = Object.entries(voteCount).sort((a, b) => b[1] - a[1]);
786
+ const weightedWinner = weightedSorted[0];
787
+ return {
788
+ decision: weightedWinner[0],
789
+ confidence: weightedWinner[1] / (votes.length + 2),
790
+ };
791
+
792
+ case 'byzantine':
793
+ // Requires 2/3 majority
794
+ const byzantineSorted = Object.entries(voteCount).sort((a, b) => b[1] - a[1]);
795
+ const byzantineWinner = byzantineSorted[0];
796
+ const byzantineConfidence = byzantineWinner[1] / votes.length;
797
+
798
+ if (byzantineConfidence >= 0.67) {
799
+ return {
800
+ decision: byzantineWinner[0],
801
+ confidence: byzantineConfidence,
802
+ };
803
+ } else {
804
+ return {
805
+ decision: 'no_consensus',
806
+ confidence: 0,
807
+ };
808
+ }
809
+
810
+ default:
811
+ return {
812
+ decision: 'unknown',
813
+ confidence: 0,
814
+ };
815
+ }
816
+ }
817
+
818
+ /**
819
+ * Check if auto-scaling is needed
820
+ */
821
+ async _checkAutoScale() {
822
+ if (!this.config.autoScale) return;
823
+
824
+ const pendingTasks = Array.from(this.state.tasks.values()).filter(
825
+ (t) => t.status === 'pending',
826
+ ).length;
827
+
828
+ const idleWorkers = Array.from(this.state.workers.values()).filter(
829
+ (w) => w.status === 'idle',
830
+ ).length;
831
+
832
+ // Scale up if too many pending tasks
833
+ if (pendingTasks > idleWorkers * 2 && this.state.workers.size < this.config.maxWorkers) {
834
+ const newWorkerType = this._determineWorkerType();
835
+ await this.spawnWorkers([newWorkerType]);
836
+ console.log(`Auto-scaled: Added ${newWorkerType} worker`);
837
+ }
838
+
839
+ // Scale down if too many idle workers
840
+ if (idleWorkers > pendingTasks + 2 && this.state.workers.size > 2) {
841
+ // TODO: Implement worker removal
842
+ }
843
+ }
844
+
845
+ /**
846
+ * Determine worker type for auto-scaling
847
+ */
848
+ _determineWorkerType() {
849
+ // Analyze pending tasks to determine needed worker type
850
+ const pendingTasks = Array.from(this.state.tasks.values()).filter(
851
+ (t) => t.status === 'pending',
852
+ );
853
+
854
+ // Simple heuristic based on task descriptions
855
+ const typeScores = {};
856
+
857
+ pendingTasks.forEach((task) => {
858
+ const taskLower = task.description.toLowerCase();
859
+
860
+ if (taskLower.includes('code') || taskLower.includes('implement')) {
861
+ typeScores.coder = (typeScores.coder || 0) + 1;
862
+ }
863
+ if (taskLower.includes('test') || taskLower.includes('validate')) {
864
+ typeScores.tester = (typeScores.tester || 0) + 1;
865
+ }
866
+ if (taskLower.includes('analyze') || taskLower.includes('data')) {
867
+ typeScores.analyst = (typeScores.analyst || 0) + 1;
868
+ }
869
+ if (taskLower.includes('research') || taskLower.includes('investigate')) {
870
+ typeScores.researcher = (typeScores.researcher || 0) + 1;
871
+ }
872
+ });
873
+
874
+ // Return type with highest score
875
+ const sorted = Object.entries(typeScores).sort((a, b) => b[1] - a[1]);
876
+ return sorted.length > 0 ? sorted[0][0] : 'coder'; // Default to coder
877
+ }
878
+
879
+ /**
880
+ * Update performance metrics
881
+ */
882
+ async _updatePerformanceMetrics() {
883
+ // Calculate performance metrics
884
+ const completionRate = this.state.metrics.tasksCompleted / this.state.metrics.tasksCreated;
885
+ const avgTasksPerWorker = this.state.metrics.tasksCompleted / this.state.workers.size;
886
+
887
+ // Store metrics in memory
888
+ await this.mcpWrapper.storeMemory(
889
+ this.state.swarmId,
890
+ 'metrics',
891
+ {
892
+ ...this.state.metrics,
893
+ completionRate,
894
+ avgTasksPerWorker,
895
+ timestamp: Date.now(),
896
+ },
897
+ 'metrics',
898
+ );
899
+
900
+ // Analyze performance if needed
901
+ if (this.state.metrics.tasksCompleted % 10 === 0) {
902
+ await this.mcpWrapper.analyzePerformance(this.state.swarmId);
903
+ }
904
+ }
905
+
906
+ /**
907
+ * Handle errors
908
+ */
909
+ _handleError(error) {
910
+ // Log error to memory
911
+ this.mcpWrapper
912
+ .storeMemory(
913
+ this.state.swarmId,
914
+ `error-${Date.now()}`,
915
+ {
916
+ message: error.message,
917
+ stack: error.stack,
918
+ timestamp: Date.now(),
919
+ },
920
+ 'error',
921
+ )
922
+ .catch(console.error);
923
+ }
924
+
925
+ /**
926
+ * Get current status with performance metrics
927
+ */
928
+ getStatus() {
929
+ const tasks = Array.from(this.state.tasks.values());
930
+ const workers = Array.from(this.state.workers.values());
931
+
932
+ return {
933
+ swarmId: this.state.swarmId,
934
+ status: this.state.status,
935
+ queen: this.state.queen,
936
+ workers: workers,
937
+ tasks: {
938
+ total: this.state.tasks.size,
939
+ pending: tasks.filter((t) => t.status === 'pending').length,
940
+ inProgress: tasks.filter((t) => t.status === 'in_progress').length,
941
+ completed: tasks.filter((t) => t.status === 'completed').length,
942
+ failed: tasks.filter((t) => t.status === 'failed').length,
943
+ },
944
+ metrics: {
945
+ ...this.state.metrics,
946
+ averageTaskTime: this._calculateAverageTaskTime(tasks),
947
+ workerEfficiency: this._calculateWorkerEfficiency(workers),
948
+ throughput: this._calculateThroughput(tasks),
949
+ },
950
+ decisions: this.state.decisions.size,
951
+ performance: this.performanceOptimizer.getPerformanceStats(),
952
+ };
953
+ }
954
+
955
+ /**
956
+ * Calculate average task completion time
957
+ */
958
+ _calculateAverageTaskTime(tasks) {
959
+ const completedTasks = tasks.filter((t) => t.status === 'completed' && t.actualDuration);
960
+ if (completedTasks.length === 0) return 0;
961
+
962
+ const totalTime = completedTasks.reduce((sum, task) => sum + task.actualDuration, 0);
963
+ return Math.round(totalTime / completedTasks.length);
964
+ }
965
+
966
+ /**
967
+ * Calculate worker efficiency
968
+ */
969
+ _calculateWorkerEfficiency(workers) {
970
+ if (workers.length === 0) return 0;
971
+
972
+ const efficiencies = workers.map((worker) => worker.performance?.successRate || 1.0);
973
+ return ((efficiencies.reduce((sum, eff) => sum + eff, 0) / workers.length) * 100).toFixed(2);
974
+ }
975
+
976
+ /**
977
+ * Calculate system throughput (tasks per minute)
978
+ */
979
+ _calculateThroughput(tasks) {
980
+ const completedTasks = tasks.filter((t) => t.status === 'completed' && t.completedAt);
981
+ if (completedTasks.length < 2) return 0;
982
+
983
+ const firstCompleted = new Date(completedTasks[0].completedAt).getTime();
984
+ const lastCompleted = new Date(completedTasks[completedTasks.length - 1].completedAt).getTime();
985
+ const timeSpanMinutes = (lastCompleted - firstCompleted) / (1000 * 60);
986
+
987
+ return timeSpanMinutes > 0 ? (completedTasks.length / timeSpanMinutes).toFixed(2) : 0;
988
+ }
989
+
990
+ /**
991
+ * Shutdown hive mind with cleanup
992
+ */
993
+ async shutdown() {
994
+ this.state.status = 'shutting_down';
995
+
996
+ try {
997
+ // Generate final performance report
998
+ const performanceReport = this.performanceOptimizer.generatePerformanceReport();
999
+
1000
+ // Save final state and performance report
1001
+ await Promise.all([
1002
+ this.mcpWrapper.storeMemory(this.state.swarmId, 'final_state', this.getStatus(), 'system'),
1003
+ this.mcpWrapper.storeMemory(
1004
+ this.state.swarmId,
1005
+ 'final_performance_report',
1006
+ performanceReport,
1007
+ 'metrics',
1008
+ ),
1009
+ ]);
1010
+
1011
+ // Close performance optimizer
1012
+ await this.performanceOptimizer.close();
1013
+
1014
+ // Destroy swarm
1015
+ await this.mcpWrapper.destroySwarm(this.state.swarmId);
1016
+
1017
+ this.state.status = 'shutdown';
1018
+ this.emit('shutdown', { performanceReport });
1019
+ } catch (error) {
1020
+ this.emit('error', { type: 'shutdown_failed', error });
1021
+ throw error;
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Get performance insights and recommendations
1027
+ */
1028
+ getPerformanceInsights() {
1029
+ return this.performanceOptimizer.generatePerformanceReport();
1030
+ }
1031
+ }