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,1045 @@
1
+ // SPARC Coordinator
2
+ // Integrates SPARC methodology with swarm system for enhanced coordination
3
+
4
+ import { SparcPhase } from './phase-base.js';
5
+
6
+ export class SparcCoordinator {
7
+ constructor(phases, options = {}) {
8
+ this.phases = phases;
9
+ this.options = options;
10
+ this.swarmId = null;
11
+ this.agents = [];
12
+ this.phaseAgents = new Map();
13
+ this.coordination = {
14
+ strategy: 'adaptive',
15
+ topology: 'hierarchical',
16
+ communication: 'event-driven',
17
+ loadBalancing: 'capability-based',
18
+ };
19
+ this.metrics = {
20
+ phaseExecutions: 0,
21
+ agentUtilization: {},
22
+ coordinationEfficiency: 0,
23
+ qualityGates: [],
24
+ learningData: [],
25
+ };
26
+ this.neuralContext = null;
27
+ this.swarmEnabled = options.swarmEnabled || false;
28
+ }
29
+
30
+ /**
31
+ * Initialize swarm for SPARC execution
32
+ */
33
+ async initializeSwarm() {
34
+ if (!this.swarmEnabled) {
35
+ console.log('🔄 SPARC running in standalone mode');
36
+ return;
37
+ }
38
+
39
+ console.log('🐝 Initializing SPARC Swarm Coordination');
40
+
41
+ try {
42
+ // Initialize swarm using ruv-swarm hooks
43
+ const swarmConfig = {
44
+ topology: this.coordination.topology,
45
+ maxAgents: this.calculateOptimalAgentCount(),
46
+ strategy: 'sparc_methodology',
47
+ communication: this.coordination.communication,
48
+ loadBalancing: this.coordination.loadBalancing,
49
+ };
50
+
51
+ this.swarmId = await this.executeSwarmHook('swarm_init', swarmConfig);
52
+ console.log(`🆔 Swarm initialized: ${this.swarmId}`);
53
+
54
+ // Spawn specialized SPARC agents
55
+ await this.spawnSparcAgents();
56
+
57
+ // Setup inter-phase coordination
58
+ await this.setupPhaseCoordination();
59
+
60
+ console.log('✅ SPARC Swarm coordination initialized');
61
+ } catch (error) {
62
+ console.warn(`⚠️ Swarm initialization failed: ${error.message}`);
63
+ console.log('🔄 Falling back to standalone mode');
64
+ this.swarmEnabled = false;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Calculate optimal agent count based on SPARC phases
70
+ */
71
+ calculateOptimalAgentCount() {
72
+ const baseAgents = Object.keys(this.phases).length; // One per phase
73
+ const complexityMultiplier = this.assessTaskComplexity();
74
+ const parallelismFactor = this.options.parallelExecution ? 2 : 1;
75
+
76
+ return Math.min(20, Math.max(5, baseAgents * complexityMultiplier * parallelismFactor));
77
+ }
78
+
79
+ /**
80
+ * Assess task complexity for agent allocation
81
+ */
82
+ assessTaskComplexity() {
83
+ const taskDescription = this.options.taskDescription || '';
84
+ const complexityKeywords = [
85
+ 'complex',
86
+ 'enterprise',
87
+ 'scalable',
88
+ 'distributed',
89
+ 'microservice',
90
+ 'integration',
91
+ ];
92
+ const matchedKeywords = complexityKeywords.filter((keyword) =>
93
+ taskDescription.toLowerCase().includes(keyword),
94
+ );
95
+
96
+ if (matchedKeywords.length >= 3) return 3; // High complexity
97
+ if (matchedKeywords.length >= 1) return 2; // Medium complexity
98
+ return 1; // Low complexity
99
+ }
100
+
101
+ /**
102
+ * Spawn specialized SPARC agents
103
+ */
104
+ async spawnSparcAgents() {
105
+ const agentTypes = [
106
+ {
107
+ type: 'sparc_specification',
108
+ role: 'Requirements Analyst',
109
+ capabilities: ['analysis', 'documentation', 'validation'],
110
+ },
111
+ {
112
+ type: 'sparc_pseudocode',
113
+ role: 'Logic Designer',
114
+ capabilities: ['design', 'flowcharts', 'algorithms'],
115
+ },
116
+ {
117
+ type: 'sparc_architecture',
118
+ role: 'System Architect',
119
+ capabilities: ['architecture', 'design_patterns', 'scalability'],
120
+ },
121
+ {
122
+ type: 'sparc_refinement',
123
+ role: 'TDD Engineer',
124
+ capabilities: ['testing', 'refactoring', 'code_quality'],
125
+ },
126
+ {
127
+ type: 'sparc_completion',
128
+ role: 'Integration Specialist',
129
+ capabilities: ['integration', 'deployment', 'validation'],
130
+ },
131
+ {
132
+ type: 'sparc_coordinator',
133
+ role: 'SPARC Orchestrator',
134
+ capabilities: ['coordination', 'monitoring', 'optimization'],
135
+ },
136
+ ];
137
+
138
+ for (const agentSpec of agentTypes) {
139
+ try {
140
+ const agentId = await this.executeSwarmHook('agent_spawn', {
141
+ type: agentSpec.type,
142
+ role: agentSpec.role,
143
+ capabilities: agentSpec.capabilities,
144
+ maxConcurrentTasks: this.getAgentConcurrency(agentSpec.type),
145
+ specialization: 'sparc_methodology',
146
+ });
147
+
148
+ const agent = {
149
+ id: agentId,
150
+ type: agentSpec.type,
151
+ role: agentSpec.role,
152
+ capabilities: agentSpec.capabilities,
153
+ status: 'ready',
154
+ currentPhase: null,
155
+ assignedTasks: [],
156
+ performance: {
157
+ tasksCompleted: 0,
158
+ averageTime: 0,
159
+ qualityScore: 1.0,
160
+ efficiency: 1.0,
161
+ },
162
+ };
163
+
164
+ this.agents.push(agent);
165
+ console.log(` 🤖 Spawned ${agentSpec.role} (${agentSpec.type})`);
166
+ } catch (error) {
167
+ console.warn(`⚠️ Failed to spawn ${agentSpec.role}: ${error.message}`);
168
+ }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Get agent concurrency based on type
174
+ */
175
+ getAgentConcurrency(agentType) {
176
+ const concurrencyMap = {
177
+ sparc_specification: 2,
178
+ sparc_pseudocode: 1,
179
+ sparc_architecture: 3,
180
+ sparc_refinement: 4,
181
+ sparc_completion: 2,
182
+ sparc_coordinator: 1,
183
+ };
184
+
185
+ return concurrencyMap[agentType] || 2;
186
+ }
187
+
188
+ /**
189
+ * Setup phase coordination
190
+ */
191
+ async setupPhaseCoordination() {
192
+ // Map agents to phases
193
+ for (const agent of this.agents) {
194
+ const phaseName = agent.type.replace('sparc_', '');
195
+ if (this.phases[phaseName]) {
196
+ if (!this.phaseAgents.has(phaseName)) {
197
+ this.phaseAgents.set(phaseName, []);
198
+ }
199
+ this.phaseAgents.get(phaseName).push(agent);
200
+ }
201
+ }
202
+
203
+ // Setup phase dependencies
204
+ await this.executeSwarmHook('setup_dependencies', {
205
+ phases: Object.keys(this.phases),
206
+ dependencies: {
207
+ pseudocode: ['specification'],
208
+ architecture: ['specification', 'pseudocode'],
209
+ refinement: ['specification', 'pseudocode', 'architecture'],
210
+ completion: ['specification', 'pseudocode', 'architecture', 'refinement'],
211
+ },
212
+ });
213
+
214
+ // Setup quality gates between phases
215
+ await this.setupQualityGates();
216
+ }
217
+
218
+ /**
219
+ * Setup quality gates between phases
220
+ */
221
+ async setupQualityGates() {
222
+ const qualityGates = [
223
+ {
224
+ phase: 'specification',
225
+ criteria: ['requirements_complete', 'acceptance_criteria_defined'],
226
+ threshold: 0.9,
227
+ },
228
+ {
229
+ phase: 'pseudocode',
230
+ criteria: ['flow_diagram_complete', 'algorithms_defined'],
231
+ threshold: 0.85,
232
+ },
233
+ {
234
+ phase: 'architecture',
235
+ criteria: ['components_defined', 'patterns_selected'],
236
+ threshold: 0.85,
237
+ },
238
+ {
239
+ phase: 'refinement',
240
+ criteria: ['tests_passing', 'code_quality_acceptable'],
241
+ threshold: 0.8,
242
+ },
243
+ {
244
+ phase: 'completion',
245
+ criteria: ['validation_passed', 'deployment_successful'],
246
+ threshold: 0.9,
247
+ },
248
+ ];
249
+
250
+ for (const gate of qualityGates) {
251
+ await this.executeSwarmHook('register_quality_gate', gate);
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Pre-phase coordination
257
+ */
258
+ async prePhase(phaseName) {
259
+ if (!this.swarmEnabled) return;
260
+
261
+ console.log(`🔄 Pre-phase coordination: ${phaseName}`);
262
+
263
+ try {
264
+ // Load neural context for the phase
265
+ await this.loadNeuralContext(phaseName);
266
+
267
+ // Assign agents to phase
268
+ await this.assignAgentsToPhase(phaseName);
269
+
270
+ // Prepare phase environment
271
+ await this.preparePhaseEnvironment(phaseName);
272
+
273
+ // Store phase initiation in memory
274
+ await this.executeSwarmHook('memory_store', {
275
+ key: `sparc_phase_${phaseName}_start`,
276
+ value: {
277
+ timestamp: Date.now(),
278
+ agents: this.phaseAgents.get(phaseName)?.map((a) => a.id) || [],
279
+ neuralContext: this.neuralContext,
280
+ },
281
+ });
282
+ } catch (error) {
283
+ console.warn(`⚠️ Pre-phase coordination failed for ${phaseName}: ${error.message}`);
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Load neural context for phase
289
+ */
290
+ async loadNeuralContext(phaseName) {
291
+ try {
292
+ const neuralData = await this.executeSwarmHook('neural_load_context', {
293
+ phase: phaseName,
294
+ methodology: 'sparc',
295
+ taskType: this.classifyTaskType(),
296
+ });
297
+
298
+ this.neuralContext = {
299
+ phase: phaseName,
300
+ patterns: neuralData.patterns || [],
301
+ insights: neuralData.insights || [],
302
+ recommendations: neuralData.recommendations || [],
303
+ confidence: neuralData.confidence || 0.5,
304
+ };
305
+
306
+ console.log(
307
+ `🧠 Neural context loaded for ${phaseName} (confidence: ${this.neuralContext.confidence.toFixed(2)})`,
308
+ );
309
+ } catch (error) {
310
+ console.warn(`⚠️ Neural context loading failed: ${error.message}`);
311
+ this.neuralContext = {
312
+ phase: phaseName,
313
+ patterns: [],
314
+ insights: [],
315
+ recommendations: [],
316
+ confidence: 0.5,
317
+ };
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Classify task type for neural learning
323
+ */
324
+ classifyTaskType() {
325
+ const taskDescription = this.options.taskDescription || '';
326
+ const taskLower = taskDescription.toLowerCase();
327
+
328
+ if (taskLower.includes('api') || taskLower.includes('service')) return 'api_development';
329
+ if (taskLower.includes('ui') || taskLower.includes('frontend')) return 'frontend_development';
330
+ if (taskLower.includes('data') || taskLower.includes('database')) return 'data_management';
331
+ if (taskLower.includes('test') || taskLower.includes('testing')) return 'testing';
332
+ if (taskLower.includes('deploy') || taskLower.includes('infrastructure')) return 'deployment';
333
+
334
+ return 'general_development';
335
+ }
336
+
337
+ /**
338
+ * Assign agents to phase
339
+ */
340
+ async assignAgentsToPhase(phaseName) {
341
+ const phaseAgents = this.phaseAgents.get(phaseName) || [];
342
+
343
+ for (const agent of phaseAgents) {
344
+ agent.currentPhase = phaseName;
345
+ agent.status = 'assigned';
346
+
347
+ await this.executeSwarmHook('agent_assign', {
348
+ agentId: agent.id,
349
+ phase: phaseName,
350
+ priority: this.getPhasePriority(phaseName),
351
+ context: this.neuralContext,
352
+ });
353
+ }
354
+
355
+ // If no dedicated agents, assign general coordinator
356
+ if (phaseAgents.length === 0) {
357
+ const coordinator = this.agents.find((a) => a.type === 'sparc_coordinator');
358
+ if (coordinator) {
359
+ coordinator.currentPhase = phaseName;
360
+ coordinator.status = 'assigned';
361
+
362
+ await this.executeSwarmHook('agent_assign', {
363
+ agentId: coordinator.id,
364
+ phase: phaseName,
365
+ priority: this.getPhasePriority(phaseName),
366
+ context: this.neuralContext,
367
+ });
368
+ }
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Get phase priority for scheduling
374
+ */
375
+ getPhasePriority(phaseName) {
376
+ const priorities = {
377
+ specification: 5, // Highest priority
378
+ pseudocode: 4,
379
+ architecture: 4,
380
+ refinement: 3,
381
+ completion: 2,
382
+ };
383
+
384
+ return priorities[phaseName] || 1;
385
+ }
386
+
387
+ /**
388
+ * Prepare phase environment
389
+ */
390
+ async preparePhaseEnvironment(phaseName) {
391
+ // Create phase-specific workspace
392
+ await this.executeSwarmHook('create_workspace', {
393
+ phase: phaseName,
394
+ namespace: this.options.namespace || 'sparc',
395
+ isolation: true,
396
+ });
397
+
398
+ // Load previous phase artifacts
399
+ const dependencies = this.getPhaseDependencies(phaseName);
400
+ for (const dependency of dependencies) {
401
+ await this.executeSwarmHook('load_artifacts', {
402
+ fromPhase: dependency,
403
+ toPhase: phaseName,
404
+ artifactTypes: ['outputs', 'decisions', 'validations'],
405
+ });
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Get phase dependencies
411
+ */
412
+ getPhaseDependencies(phaseName) {
413
+ const dependencies = {
414
+ specification: [],
415
+ pseudocode: ['specification'],
416
+ architecture: ['specification', 'pseudocode'],
417
+ refinement: ['specification', 'pseudocode', 'architecture'],
418
+ completion: ['specification', 'pseudocode', 'architecture', 'refinement'],
419
+ };
420
+
421
+ return dependencies[phaseName] || [];
422
+ }
423
+
424
+ /**
425
+ * Post-phase coordination
426
+ */
427
+ async postPhase(phaseName, result) {
428
+ if (!this.swarmEnabled) return;
429
+
430
+ console.log(`✅ Post-phase coordination: ${phaseName}`);
431
+
432
+ try {
433
+ // Validate phase results
434
+ const validation = await this.validatePhaseResults(phaseName, result);
435
+
436
+ // Update agent performance
437
+ await this.updateAgentPerformance(phaseName, result, validation);
438
+
439
+ // Store phase completion in memory
440
+ await this.executeSwarmHook('memory_store', {
441
+ key: `sparc_phase_${phaseName}_complete`,
442
+ value: {
443
+ timestamp: Date.now(),
444
+ result: result,
445
+ validation: validation,
446
+ agents:
447
+ this.phaseAgents.get(phaseName)?.map((a) => ({
448
+ id: a.id,
449
+ performance: a.performance,
450
+ })) || [],
451
+ },
452
+ });
453
+
454
+ // Neural learning from phase execution
455
+ if (this.options.neuralLearning) {
456
+ await this.recordNeuralLearning(phaseName, result, validation);
457
+ }
458
+
459
+ // Prepare handoff to next phase
460
+ await this.preparePhaseHandoff(phaseName, result);
461
+
462
+ // Update metrics
463
+ this.updateCoordinationMetrics(phaseName, result, validation);
464
+ } catch (error) {
465
+ console.warn(`⚠️ Post-phase coordination failed for ${phaseName}: ${error.message}`);
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Validate phase results
471
+ */
472
+ async validatePhaseResults(phaseName, result) {
473
+ const validation = {
474
+ phase: phaseName,
475
+ passed: true,
476
+ score: 0,
477
+ issues: [],
478
+ recommendations: [],
479
+ };
480
+
481
+ try {
482
+ // Execute swarm-based validation
483
+ const swarmValidation = await this.executeSwarmHook('validate_phase', {
484
+ phase: phaseName,
485
+ result: result,
486
+ criteria: this.getValidationCriteria(phaseName),
487
+ });
488
+
489
+ validation.passed = swarmValidation.passed;
490
+ validation.score = swarmValidation.score;
491
+ validation.issues = swarmValidation.issues || [];
492
+ validation.recommendations = swarmValidation.recommendations || [];
493
+ } catch (error) {
494
+ console.warn(`⚠️ Swarm validation failed: ${error.message}`);
495
+ // Fallback to basic validation
496
+ validation.passed = !!result;
497
+ validation.score = result ? 85 : 0;
498
+ }
499
+
500
+ return validation;
501
+ }
502
+
503
+ /**
504
+ * Get validation criteria for phase
505
+ */
506
+ getValidationCriteria(phaseName) {
507
+ const criteria = {
508
+ specification: {
509
+ requiredFields: ['requirements', 'acceptanceCriteria', 'userStories'],
510
+ qualityThresholds: { completeness: 0.9, clarity: 0.8 },
511
+ },
512
+ pseudocode: {
513
+ requiredFields: ['flowDiagram', 'pseudocode', 'algorithms'],
514
+ qualityThresholds: { completeness: 0.85, complexity: 0.7 },
515
+ },
516
+ architecture: {
517
+ requiredFields: ['systemDesign', 'components', 'designPatterns'],
518
+ qualityThresholds: { modularity: 0.8, scalability: 0.75 },
519
+ },
520
+ refinement: {
521
+ requiredFields: ['testResults', 'codeQuality', 'implementations'],
522
+ qualityThresholds: { testCoverage: 0.8, codeQuality: 0.75 },
523
+ },
524
+ completion: {
525
+ requiredFields: ['validation', 'deployment', 'documentation'],
526
+ qualityThresholds: { completeness: 0.9, readiness: 0.85 },
527
+ },
528
+ };
529
+
530
+ return criteria[phaseName] || { requiredFields: [], qualityThresholds: {} };
531
+ }
532
+
533
+ /**
534
+ * Update agent performance metrics
535
+ */
536
+ async updateAgentPerformance(phaseName, result, validation) {
537
+ const phaseAgents = this.phaseAgents.get(phaseName) || [];
538
+
539
+ for (const agent of phaseAgents) {
540
+ agent.performance.tasksCompleted += 1;
541
+
542
+ // Update quality score based on validation
543
+ const qualityScore = validation.score / 100;
544
+ agent.performance.qualityScore = (agent.performance.qualityScore + qualityScore) / 2;
545
+
546
+ // Update efficiency based on execution time
547
+ const executionTime = Date.now() - this.getPhaseStartTime(phaseName);
548
+ const expectedTime = this.getExpectedPhaseTime(phaseName);
549
+ const efficiency = Math.min(1, expectedTime / executionTime);
550
+ agent.performance.efficiency = (agent.performance.efficiency + efficiency) / 2;
551
+
552
+ // Update average time
553
+ agent.performance.averageTime = (agent.performance.averageTime + executionTime) / 2;
554
+
555
+ // Store performance update
556
+ await this.executeSwarmHook('update_agent_performance', {
557
+ agentId: agent.id,
558
+ performance: agent.performance,
559
+ phase: phaseName,
560
+ });
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Get phase start time
566
+ */
567
+ getPhaseStartTime(phaseName) {
568
+ // This would typically be stored in memory or agent state
569
+ return Date.now() - 5 * 60 * 1000; // Default to 5 minutes ago
570
+ }
571
+
572
+ /**
573
+ * Get expected phase execution time
574
+ */
575
+ getExpectedPhaseTime(phaseName) {
576
+ const expectedTimes = {
577
+ specification: 10 * 60 * 1000, // 10 minutes
578
+ pseudocode: 5 * 60 * 1000, // 5 minutes
579
+ architecture: 15 * 60 * 1000, // 15 minutes
580
+ refinement: 20 * 60 * 1000, // 20 minutes
581
+ completion: 10 * 60 * 1000, // 10 minutes
582
+ };
583
+
584
+ return expectedTimes[phaseName] || 10 * 60 * 1000;
585
+ }
586
+
587
+ /**
588
+ * Record neural learning from phase execution
589
+ */
590
+ async recordNeuralLearning(phaseName, result, validation) {
591
+ try {
592
+ const learningData = {
593
+ phase: phaseName,
594
+ taskType: this.classifyTaskType(),
595
+ methodology: 'sparc',
596
+ execution: {
597
+ result: result,
598
+ validation: validation,
599
+ timestamp: Date.now(),
600
+ },
601
+ context: {
602
+ taskDescription: this.options.taskDescription,
603
+ neuralContext: this.neuralContext,
604
+ agentPerformance: this.getAgentPerformanceData(phaseName),
605
+ },
606
+ outcomes: {
607
+ success: validation.passed,
608
+ quality: validation.score,
609
+ efficiency: this.calculatePhaseEfficiency(phaseName),
610
+ learnings: this.extractLearnings(phaseName, result, validation),
611
+ },
612
+ };
613
+
614
+ await this.executeSwarmHook('neural_record_learning', learningData);
615
+
616
+ // Train neural patterns based on this execution
617
+ await this.executeSwarmHook('neural_train', {
618
+ data: learningData,
619
+ updateWeights: true,
620
+ savePattern: true,
621
+ });
622
+
623
+ console.log(`🧠 Neural learning recorded for ${phaseName}`);
624
+ } catch (error) {
625
+ console.warn(`⚠️ Neural learning failed: ${error.message}`);
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Get agent performance data for phase
631
+ */
632
+ getAgentPerformanceData(phaseName) {
633
+ const phaseAgents = this.phaseAgents.get(phaseName) || [];
634
+ return phaseAgents.map((agent) => ({
635
+ id: agent.id,
636
+ type: agent.type,
637
+ performance: agent.performance,
638
+ }));
639
+ }
640
+
641
+ /**
642
+ * Calculate phase efficiency
643
+ */
644
+ calculatePhaseEfficiency(phaseName) {
645
+ const phaseAgents = this.phaseAgents.get(phaseName) || [];
646
+ if (phaseAgents.length === 0) return 0.5;
647
+
648
+ const avgEfficiency =
649
+ phaseAgents.reduce((sum, agent) => sum + agent.performance.efficiency, 0) /
650
+ phaseAgents.length;
651
+ return avgEfficiency;
652
+ }
653
+
654
+ /**
655
+ * Extract learnings from phase execution
656
+ */
657
+ extractLearnings(phaseName, result, validation) {
658
+ const learnings = [];
659
+
660
+ if (validation.passed) {
661
+ learnings.push(`${phaseName} phase executed successfully`);
662
+ if (validation.score > 90) {
663
+ learnings.push(`High quality output achieved in ${phaseName}`);
664
+ }
665
+ } else {
666
+ learnings.push(`${phaseName} phase encountered issues: ${validation.issues.join(', ')}`);
667
+ }
668
+
669
+ if (validation.recommendations.length > 0) {
670
+ learnings.push(`Recommendations for ${phaseName}: ${validation.recommendations.join(', ')}`);
671
+ }
672
+
673
+ return learnings;
674
+ }
675
+
676
+ /**
677
+ * Prepare handoff to next phase
678
+ */
679
+ async preparePhaseHandoff(phaseName, result) {
680
+ const nextPhase = this.getNextPhase(phaseName);
681
+ if (!nextPhase) return;
682
+
683
+ // Prepare artifacts for next phase
684
+ await this.executeSwarmHook('prepare_handoff', {
685
+ fromPhase: phaseName,
686
+ toPhase: nextPhase,
687
+ artifacts: {
688
+ outputs: result,
689
+ decisions: this.extractDecisions(result),
690
+ context: this.neuralContext,
691
+ },
692
+ });
693
+
694
+ // Pre-warm next phase agents
695
+ const nextPhaseAgents = this.phaseAgents.get(nextPhase) || [];
696
+ for (const agent of nextPhaseAgents) {
697
+ await this.executeSwarmHook('agent_prewarm', {
698
+ agentId: agent.id,
699
+ phase: nextPhase,
700
+ context: result,
701
+ });
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Get next phase in SPARC sequence
707
+ */
708
+ getNextPhase(currentPhase) {
709
+ const sequence = ['specification', 'pseudocode', 'architecture', 'refinement', 'completion'];
710
+ const currentIndex = sequence.indexOf(currentPhase);
711
+ return currentIndex >= 0 && currentIndex < sequence.length - 1
712
+ ? sequence[currentIndex + 1]
713
+ : null;
714
+ }
715
+
716
+ /**
717
+ * Extract decisions from phase result
718
+ */
719
+ extractDecisions(result) {
720
+ const decisions = [];
721
+
722
+ if (result.architecturalDecisions) {
723
+ decisions.push(...result.architecturalDecisions);
724
+ }
725
+
726
+ if (result.designDecisions) {
727
+ decisions.push(...result.designDecisions);
728
+ }
729
+
730
+ if (result.qualityGates) {
731
+ decisions.push(
732
+ ...result.qualityGates.map((gate) => ({
733
+ decision: `Quality gate: ${gate.name}`,
734
+ rationale: gate.rationale || 'Quality assurance',
735
+ impact: gate.impact || 'process',
736
+ })),
737
+ );
738
+ }
739
+
740
+ return decisions;
741
+ }
742
+
743
+ /**
744
+ * Update coordination metrics
745
+ */
746
+ updateCoordinationMetrics(phaseName, result, validation) {
747
+ this.metrics.phaseExecutions += 1;
748
+
749
+ // Update agent utilization
750
+ const phaseAgents = this.phaseAgents.get(phaseName) || [];
751
+ for (const agent of phaseAgents) {
752
+ if (!this.metrics.agentUtilization[agent.id]) {
753
+ this.metrics.agentUtilization[agent.id] = { phases: 0, totalTime: 0, quality: 0 };
754
+ }
755
+ this.metrics.agentUtilization[agent.id].phases += 1;
756
+ this.metrics.agentUtilization[agent.id].quality += validation.score;
757
+ }
758
+
759
+ // Update coordination efficiency
760
+ const efficiency = this.calculatePhaseEfficiency(phaseName);
761
+ this.metrics.coordinationEfficiency = (this.metrics.coordinationEfficiency + efficiency) / 2;
762
+
763
+ // Record quality gate
764
+ this.metrics.qualityGates.push({
765
+ phase: phaseName,
766
+ passed: validation.passed,
767
+ score: validation.score,
768
+ timestamp: Date.now(),
769
+ });
770
+
771
+ // Record learning data
772
+ if (validation.passed) {
773
+ this.metrics.learningData.push({
774
+ phase: phaseName,
775
+ success: true,
776
+ quality: validation.score,
777
+ patterns: this.neuralContext?.patterns || [],
778
+ });
779
+ }
780
+ }
781
+
782
+ /**
783
+ * Finalize coordination
784
+ */
785
+ async finalize() {
786
+ if (!this.swarmEnabled) return;
787
+
788
+ console.log('🏁 Finalizing SPARC coordination');
789
+
790
+ try {
791
+ // Generate coordination report
792
+ const report = await this.generateCoordinationReport();
793
+
794
+ // Store final metrics
795
+ await this.executeSwarmHook('memory_store', {
796
+ key: 'sparc_coordination_final',
797
+ value: {
798
+ metrics: this.metrics,
799
+ report: report,
800
+ timestamp: Date.now(),
801
+ },
802
+ });
803
+
804
+ // Shutdown agents
805
+ for (const agent of this.agents) {
806
+ await this.executeSwarmHook('agent_shutdown', {
807
+ agentId: agent.id,
808
+ graceful: true,
809
+ });
810
+ }
811
+
812
+ // Shutdown swarm
813
+ await this.executeSwarmHook('swarm_shutdown', {
814
+ swarmId: this.swarmId,
815
+ preserveData: true,
816
+ });
817
+
818
+ console.log('✅ SPARC coordination finalized');
819
+ } catch (error) {
820
+ console.warn(`⚠️ Coordination finalization failed: ${error.message}`);
821
+ }
822
+ }
823
+
824
+ /**
825
+ * Generate coordination report
826
+ */
827
+ async generateCoordinationReport() {
828
+ const report = {
829
+ summary: {
830
+ phasesExecuted: this.metrics.phaseExecutions,
831
+ agentsUtilized: Object.keys(this.metrics.agentUtilization).length,
832
+ coordinationEfficiency: this.metrics.coordinationEfficiency,
833
+ qualityGatesPassed: this.metrics.qualityGates.filter((g) => g.passed).length,
834
+ totalQualityGates: this.metrics.qualityGates.length,
835
+ },
836
+ agentPerformance: this.calculateAgentPerformanceSummary(),
837
+ phaseAnalysis: this.analyzePhasePerformance(),
838
+ recommendations: this.generateRecommendations(),
839
+ neuralInsights: this.extractNeuralInsights(),
840
+ };
841
+
842
+ return report;
843
+ }
844
+
845
+ /**
846
+ * Calculate agent performance summary
847
+ */
848
+ calculateAgentPerformanceSummary() {
849
+ const summary = {};
850
+
851
+ for (const agent of this.agents) {
852
+ summary[agent.id] = {
853
+ type: agent.type,
854
+ role: agent.role,
855
+ tasksCompleted: agent.performance.tasksCompleted,
856
+ averageQuality: agent.performance.qualityScore,
857
+ efficiency: agent.performance.efficiency,
858
+ averageTime: agent.performance.averageTime,
859
+ };
860
+ }
861
+
862
+ return summary;
863
+ }
864
+
865
+ /**
866
+ * Analyze phase performance
867
+ */
868
+ analyzePhasePerformance() {
869
+ const analysis = {};
870
+
871
+ for (const gate of this.metrics.qualityGates) {
872
+ if (!analysis[gate.phase]) {
873
+ analysis[gate.phase] = {
874
+ executions: 0,
875
+ passed: 0,
876
+ averageScore: 0,
877
+ totalScore: 0,
878
+ };
879
+ }
880
+
881
+ analysis[gate.phase].executions += 1;
882
+ if (gate.passed) analysis[gate.phase].passed += 1;
883
+ analysis[gate.phase].totalScore += gate.score;
884
+ }
885
+
886
+ // Calculate averages
887
+ for (const phase of Object.keys(analysis)) {
888
+ analysis[phase].averageScore = analysis[phase].totalScore / analysis[phase].executions;
889
+ analysis[phase].successRate = analysis[phase].passed / analysis[phase].executions;
890
+ }
891
+
892
+ return analysis;
893
+ }
894
+
895
+ /**
896
+ * Generate recommendations for improvement
897
+ */
898
+ generateRecommendations() {
899
+ const recommendations = [];
900
+
901
+ // Analyze agent utilization
902
+ const avgUtilization =
903
+ Object.values(this.metrics.agentUtilization).reduce((sum, agent) => sum + agent.phases, 0) /
904
+ Object.keys(this.metrics.agentUtilization).length;
905
+
906
+ if (avgUtilization < 2) {
907
+ recommendations.push('Consider reducing agent count for better utilization');
908
+ } else if (avgUtilization > 4) {
909
+ recommendations.push('Consider increasing agent count to distribute load');
910
+ }
911
+
912
+ // Analyze coordination efficiency
913
+ if (this.metrics.coordinationEfficiency < 0.7) {
914
+ recommendations.push('Improve coordination efficiency through better task decomposition');
915
+ }
916
+
917
+ // Analyze quality gates
918
+ const qualityGateSuccess =
919
+ this.metrics.qualityGates.filter((g) => g.passed).length / this.metrics.qualityGates.length;
920
+ if (qualityGateSuccess < 0.8) {
921
+ recommendations.push('Review quality gate criteria and provide additional agent training');
922
+ }
923
+
924
+ return recommendations;
925
+ }
926
+
927
+ /**
928
+ * Extract neural insights
929
+ */
930
+ extractNeuralInsights() {
931
+ const insights = [];
932
+
933
+ // Pattern analysis
934
+ const successfulPatterns = this.metrics.learningData.filter((d) => d.success);
935
+ if (successfulPatterns.length > 0) {
936
+ insights.push(`${successfulPatterns.length} successful execution patterns identified`);
937
+ }
938
+
939
+ // Quality analysis
940
+ const avgQuality =
941
+ this.metrics.learningData.reduce((sum, d) => sum + d.quality, 0) /
942
+ this.metrics.learningData.length;
943
+ if (avgQuality > 85) {
944
+ insights.push('High quality outcomes consistently achieved');
945
+ } else if (avgQuality < 70) {
946
+ insights.push('Quality improvements needed in execution');
947
+ }
948
+
949
+ return insights;
950
+ }
951
+
952
+ /**
953
+ * Execute swarm hook with error handling
954
+ */
955
+ async executeSwarmHook(hookName, data = {}) {
956
+ if (!this.swarmEnabled) {
957
+ throw new Error('Swarm not enabled');
958
+ }
959
+
960
+ try {
961
+ const { spawn } = await import('child_process');
962
+
963
+ return new Promise((resolve, reject) => {
964
+ const args = ['ruv-swarm', 'hook', hookName];
965
+
966
+ // Add data as JSON argument
967
+ if (Object.keys(data).length > 0) {
968
+ args.push('--data', JSON.stringify(data));
969
+ }
970
+
971
+ const process = spawn('npx', args, {
972
+ stdio: 'pipe',
973
+ });
974
+
975
+ let output = '';
976
+ let error = '';
977
+
978
+ process.stdout.on('data', (data) => {
979
+ output += data.toString();
980
+ });
981
+
982
+ process.stderr.on('data', (data) => {
983
+ error += data.toString();
984
+ });
985
+
986
+ process.on('close', (code) => {
987
+ if (code === 0) {
988
+ try {
989
+ const result = JSON.parse(output);
990
+ resolve(result);
991
+ } catch (parseError) {
992
+ resolve(output.trim());
993
+ }
994
+ } else {
995
+ reject(new Error(`Hook ${hookName} failed: ${error}`));
996
+ }
997
+ });
998
+
999
+ process.on('error', (err) => {
1000
+ reject(err);
1001
+ });
1002
+ });
1003
+ } catch (error) {
1004
+ throw new Error(`Failed to execute swarm hook ${hookName}: ${error.message}`);
1005
+ }
1006
+ }
1007
+
1008
+ /**
1009
+ * Record learning from SPARC execution
1010
+ */
1011
+ async recordLearning(learningData) {
1012
+ if (!this.options.neuralLearning) return;
1013
+
1014
+ try {
1015
+ await this.executeSwarmHook('neural_record_learning', {
1016
+ methodology: 'sparc',
1017
+ data: learningData,
1018
+ timestamp: Date.now(),
1019
+ });
1020
+ } catch (error) {
1021
+ console.warn(`⚠️ Failed to record learning: ${error.message}`);
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Get coordination status
1027
+ */
1028
+ getStatus() {
1029
+ return {
1030
+ swarmEnabled: this.swarmEnabled,
1031
+ swarmId: this.swarmId,
1032
+ agentCount: this.agents.length,
1033
+ phaseAgents: Object.fromEntries(
1034
+ Array.from(this.phaseAgents.entries()).map(([phase, agents]) => [
1035
+ phase,
1036
+ agents.map((a) => ({ id: a.id, type: a.type, status: a.status })),
1037
+ ]),
1038
+ ),
1039
+ metrics: this.metrics,
1040
+ coordination: this.coordination,
1041
+ };
1042
+ }
1043
+ }
1044
+
1045
+ export default SparcCoordinator;