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,2277 @@
1
+ /**
2
+ * Swarm command wrapper for simple CLI
3
+ */
4
+
5
+ import { args, mkdirAsync, writeTextFile, exit, cwd } from '../node-compat.js';
6
+ import { spawn, execSync } from 'child_process';
7
+ import { existsSync, chmodSync, statSync } from 'fs';
8
+ import { open } from 'fs/promises';
9
+ import process from 'process';
10
+ import path from 'path';
11
+
12
+ /**
13
+ * Detects if the environment is headless (non-interactive)
14
+ */
15
+ function isHeadlessEnvironment() {
16
+ // Check for common CI environment variables
17
+ const ciEnvironments = [
18
+ 'CI',
19
+ 'GITHUB_ACTIONS',
20
+ 'GITLAB_CI',
21
+ 'JENKINS_URL',
22
+ 'CIRCLECI',
23
+ 'TRAVIS',
24
+ 'BUILDKITE',
25
+ 'DRONE',
26
+ 'DOCKER_CONTAINER',
27
+ ];
28
+
29
+ const isCI = ciEnvironments.some((env) => process.env[env]);
30
+
31
+ // Check if running in Docker
32
+ const isDocker =
33
+ existsSync('/.dockerenv') ||
34
+ (existsSync('/proc/1/cgroup') &&
35
+ require('fs').readFileSync('/proc/1/cgroup', 'utf8').includes('docker'));
36
+
37
+ // Check TTY availability
38
+ const hasTTY = process.stdin.isTTY && process.stdout.isTTY;
39
+
40
+ return isCI || isDocker || !hasTTY;
41
+ }
42
+
43
+ /**
44
+ * Basic swarm implementation for fallback scenarios
45
+ */
46
+ async function basicSwarmNew(args, flags) {
47
+ const objective = (args || []).join(' ').trim();
48
+
49
+ if (!objective) {
50
+ console.error('❌ Usage: swarm <objective>');
51
+ showSwarmHelp();
52
+ return;
53
+ }
54
+
55
+ const isHeadless = isHeadlessEnvironment();
56
+
57
+ // Configure for headless mode
58
+ if (isHeadless) {
59
+ console.log('🤖 Headless environment detected - running in non-interactive mode');
60
+ flags = {
61
+ ...flags,
62
+ 'non-interactive': true,
63
+ 'output-format': flags['output-format'] || 'stream-json', // Use stream-json for Claude compatibility
64
+ 'no-auto-permissions': false,
65
+ };
66
+ }
67
+
68
+ // Set up graceful shutdown handlers
69
+ const cleanup = () => {
70
+ console.log('\n🛑 Shutting down swarm gracefully...');
71
+ process.exit(0);
72
+ };
73
+
74
+ process.on('SIGTERM', cleanup);
75
+ process.on('SIGINT', cleanup);
76
+
77
+ try {
78
+ // Try to use the swarm executor
79
+ const { executeSwarm } = await import('./swarm-executor.js');
80
+
81
+ console.log(`🐝 Starting basic swarm execution...`);
82
+ console.log(`📋 Objective: ${objective}`);
83
+ console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);
84
+ console.log(`🏗️ Mode: ${flags.mode || 'centralized'}`);
85
+ console.log(`🤖 Max Agents: ${flags['max-agents'] || 5}`);
86
+
87
+ if (isHeadless) {
88
+ console.log(`🖥️ Headless Mode: Enabled`);
89
+ console.log(`📄 Output Format: ${flags['output-format']}`);
90
+ }
91
+
92
+ const result = await executeSwarm(objective, flags);
93
+
94
+ // Handle output based on format
95
+ if (flags['output-format'] === 'json') {
96
+ // In JSON mode, output clean JSON
97
+ const output = {
98
+ success: result.success,
99
+ swarmId: result.summary?.swarmId,
100
+ objective: objective,
101
+ duration: result.summary?.duration,
102
+ agents: result.summary?.totalAgents,
103
+ tasks: result.summary?.totalTasks,
104
+ timestamp: new Date().toISOString(),
105
+ };
106
+
107
+ if (flags['output-file']) {
108
+ const fs = await import('fs/promises');
109
+ await fs.writeFile(flags['output-file'], JSON.stringify(output, null, 2));
110
+ console.log(`✅ Output saved to: ${flags['output-file']}`);
111
+ } else {
112
+ console.log(JSON.stringify(output, null, 2));
113
+ }
114
+ } else {
115
+ // Text mode output
116
+ if (result.success) {
117
+ console.log(`\n✅ Swarm execution completed successfully!`);
118
+ if (result.summary) {
119
+ console.log(` Duration: ${result.summary.duration}`);
120
+ console.log(` Agents: ${result.summary.totalAgents}`);
121
+ console.log(` Tasks: ${result.summary.totalTasks}`);
122
+ }
123
+ } else {
124
+ console.error(`\n❌ Swarm execution failed: ${result.error}`);
125
+ }
126
+ }
127
+
128
+ return result;
129
+ } catch (error) {
130
+ console.error(`❌ Basic swarm execution error: ${error.message}`);
131
+
132
+ // In headless mode, ensure we output JSON error
133
+ if (flags['output-format'] === 'json') {
134
+ const errorOutput = {
135
+ success: false,
136
+ error: error.message,
137
+ timestamp: new Date().toISOString(),
138
+ };
139
+ console.log(JSON.stringify(errorOutput, null, 2));
140
+ }
141
+
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ function showSwarmHelp() {
147
+ console.log(`
148
+ 🐝 Claude Flow Advanced Swarm System
149
+
150
+ USAGE:
151
+ claude-flow swarm <objective> [options]
152
+
153
+ EXAMPLES:
154
+ claude-flow swarm "Build a REST API with authentication"
155
+ claude-flow swarm "Research cloud architecture patterns" --strategy research
156
+ claude-flow swarm "Analyze database performance" --max-agents 3 --parallel
157
+ claude-flow swarm "Develop user registration feature" --mode distributed
158
+ claude-flow swarm "Optimize React app performance" --strategy optimization
159
+ claude-flow swarm "Create microservice" --executor # Use built-in executor
160
+ claude-flow swarm "Build API" --claude # Open Claude Code CLI
161
+ claude-flow swarm "Build API endpoints" --output-format json # Get JSON output
162
+ claude-flow swarm "Research AI trends" --output-format json --output-file results.json
163
+
164
+ DEFAULT BEHAVIOR:
165
+ Swarm attempts to open Claude Code CLI with comprehensive MCP tool instructions
166
+ including memory coordination, agent management, and task orchestration.
167
+
168
+ If Claude CLI is not available:
169
+ • Use --claude flag to open Claude Code CLI
170
+ • Use --executor flag to run with the built-in executor
171
+
172
+ STRATEGIES:
173
+ auto Automatically determine best approach (default)
174
+ research Research and information gathering
175
+ development Software development and coding
176
+ analysis Data analysis and insights
177
+ testing Testing and quality assurance
178
+ optimization Performance optimization
179
+ maintenance System maintenance
180
+
181
+ MODES:
182
+ centralized Single coordinator (default)
183
+ distributed Multiple coordinators
184
+ hierarchical Tree structure coordination
185
+ mesh Peer-to-peer coordination
186
+ hybrid Mixed coordination strategies
187
+
188
+ KEY FEATURES:
189
+ 🤖 Intelligent agent management with specialized types
190
+ ⚡ Timeout-free background task execution
191
+ 🧠 Distributed memory sharing between agents
192
+ 🔄 Work stealing and advanced load balancing
193
+ 🛡️ Circuit breaker patterns for fault tolerance
194
+ 📊 Real-time monitoring and comprehensive metrics
195
+ 🎛️ Multiple coordination strategies and algorithms
196
+ 💾 Persistent state with backup and recovery
197
+ 🔒 Security features with encryption options
198
+ 🖥️ Interactive terminal UI for management
199
+
200
+ OPTIONS:
201
+ --strategy <type> Execution strategy (default: auto)
202
+ --mode <type> Coordination mode (default: centralized)
203
+ --max-agents <n> Maximum agents (default: 5)
204
+ --timeout <minutes> Timeout in minutes (default: 60)
205
+ --task-timeout-minutes <n> Task execution timeout in minutes (default: 59)
206
+ --parallel Enable parallel execution
207
+ --distributed Enable distributed coordination
208
+ --monitor Enable real-time monitoring
209
+ --ui Launch terminal UI interface
210
+ --background Run in background mode
211
+ --review Enable peer review
212
+ --testing Enable automated testing
213
+ --encryption Enable encryption
214
+ --verbose Enable detailed logging
215
+ --dry-run Show configuration without executing
216
+ --executor Use built-in executor instead of Claude Code
217
+ --claude Open Claude Code CLI
218
+ --output-format <format> Output format: json, text (default: text)
219
+ --output-file <path> Save output to file instead of stdout
220
+ --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)
221
+ --auto (Deprecated: auto-permissions enabled by default)
222
+ --no-auto-permissions Disable automatic --dangerously-skip-permissions
223
+ --analysis Enable analysis/read-only mode (no code changes)
224
+ --read-only Enable read-only mode (alias for --analysis)
225
+
226
+ ADVANCED OPTIONS:
227
+ --quality-threshold <n> Quality threshold 0-1 (default: 0.8)
228
+ --memory-namespace <name> Memory namespace (default: swarm)
229
+ --agent-selection <type> Agent selection strategy
230
+ --task-scheduling <type> Task scheduling algorithm
231
+ --load-balancing <type> Load balancing method
232
+ --fault-tolerance <type> Fault tolerance strategy
233
+ --headless Force headless mode for CI/Docker environments
234
+ --health-check Perform health check and exit (for Docker health)
235
+ --json-logs Output all logs in JSON format for log aggregation
236
+
237
+ HEADLESS MODE:
238
+ Automatically detected and enabled when running in:
239
+ - CI/CD environments (GitHub Actions, GitLab CI, Jenkins, etc.)
240
+ - Docker containers without TTY
241
+ - Non-interactive shells (no stdin/stdout TTY)
242
+
243
+ In headless mode:
244
+ - Output defaults to JSON format
245
+ - Non-interactive mode is enabled
246
+ - Graceful shutdown on SIGTERM/SIGINT
247
+ - Suitable for containerized deployments
248
+
249
+ For complete documentation and examples:
250
+ https://github.com/ruvnet/claude-code-flow/docs/swarm.md
251
+ `);
252
+ }
253
+
254
+ export async function swarmCommand(args, flags) {
255
+ // Handle headless mode early
256
+ if (flags && flags.headless) {
257
+ const isHeadless = isHeadlessEnvironment();
258
+ // Configure for headless mode
259
+ flags = {
260
+ ...flags,
261
+ 'non-interactive': true,
262
+ 'output-format': flags['output-format'] || 'stream-json',
263
+ 'no-auto-permissions': false,
264
+ };
265
+ }
266
+
267
+ // Handle health check first
268
+ if (flags && flags['health-check']) {
269
+ try {
270
+ // Quick health check for Docker/K8s
271
+ console.log(
272
+ JSON.stringify({
273
+ status: 'healthy',
274
+ service: 'claude-flow-swarm',
275
+ version: process.env.npm_package_version || '2.0.0',
276
+ timestamp: new Date().toISOString(),
277
+ }),
278
+ );
279
+ process.exit(0);
280
+ } catch (error) {
281
+ console.error(
282
+ JSON.stringify({
283
+ status: 'unhealthy',
284
+ error: error.message,
285
+ timestamp: new Date().toISOString(),
286
+ }),
287
+ );
288
+ process.exit(1);
289
+ }
290
+ }
291
+
292
+ const objective = (args || []).join(' ').trim();
293
+
294
+ if (!objective) {
295
+ console.error('❌ Usage: swarm <objective>');
296
+ showSwarmHelp();
297
+ return;
298
+ }
299
+
300
+ // Force headless mode if flag is set
301
+ if (flags && flags.headless) {
302
+ const isHeadless = isHeadlessEnvironment();
303
+ if (!isHeadless) {
304
+ console.log('🤖 Forcing headless mode as requested');
305
+ }
306
+ flags = {
307
+ ...flags,
308
+ 'non-interactive': true,
309
+ 'output-format': flags['output-format'] || 'json',
310
+ 'no-auto-permissions': false,
311
+ };
312
+ }
313
+
314
+ // Handle JSON output format
315
+ const outputFormat = flags && flags['output-format'];
316
+ const outputFile = flags && flags['output-file'];
317
+ const isJsonOutput = outputFormat === 'json';
318
+ const isNonInteractive = isJsonOutput || (flags && flags['no-interactive']);
319
+ const useJsonLogs = flags && flags['json-logs'];
320
+
321
+ // Override console.log for JSON logs if requested
322
+ if (useJsonLogs) {
323
+ const originalLog = console.log;
324
+ const originalError = console.error;
325
+
326
+ console.log = (...args) => {
327
+ originalLog(
328
+ JSON.stringify({
329
+ level: 'info',
330
+ message: args.join(' '),
331
+ timestamp: new Date().toISOString(),
332
+ service: 'claude-flow-swarm',
333
+ }),
334
+ );
335
+ };
336
+
337
+ console.error = (...args) => {
338
+ originalError(
339
+ JSON.stringify({
340
+ level: 'error',
341
+ message: args.join(' '),
342
+ timestamp: new Date().toISOString(),
343
+ service: 'claude-flow-swarm',
344
+ }),
345
+ );
346
+ };
347
+ }
348
+
349
+ // Handle analysis/read-only mode
350
+ const isAnalysisMode = flags && (flags.analysis || flags['read-only']);
351
+ const analysisMode = isAnalysisMode ? 'analysis' : 'standard';
352
+
353
+ // For JSON output, allow using Claude with stream-json format
354
+ // Only force executor mode if explicitly using 'json' format (not 'stream-json')
355
+ if (flags && flags['output-format'] === 'json' && !(flags && flags.executor)) {
356
+ // Keep backward compatibility - regular 'json' format uses executor
357
+ flags = { ...(flags || {}), executor: true };
358
+ }
359
+
360
+ // Check if we should use the old executor (opt-in with --executor flag)
361
+ if (flags && flags.executor) {
362
+ // Continue with the old swarm executor implementation below
363
+ } else {
364
+ // Default behavior: spawn Claude Code with comprehensive swarm MCP instructions
365
+ try {
366
+ const { execSync, spawn } = await import('child_process');
367
+
368
+ // Get configuration values first
369
+ const strategy = flags.strategy || 'auto';
370
+ const mode = flags.mode || 'centralized';
371
+ const maxAgents = flags['max-agents'] || 5;
372
+
373
+ // Get strategy-specific guidance
374
+ const strategyGuidance = getStrategyGuidance(strategy, objective);
375
+ const modeGuidance = getModeGuidance(mode);
376
+ const agentRecommendations = getAgentRecommendations(strategy, maxAgents, objective);
377
+
378
+ const enableSparc =
379
+ flags.sparc !== false && (strategy === 'development' || strategy === 'auto');
380
+
381
+ // Build the complete swarm prompt before checking for claude
382
+ const swarmPrompt = `You are orchestrating a Claude Flow Swarm using Claude Code's Task tool for agent execution.
383
+
384
+ 🚨 CRITICAL INSTRUCTION: Use Claude Code's Task Tool for ALL Agent Spawning!
385
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
386
+ ✅ Claude Code's Task tool = Spawns agents that DO the actual work
387
+ ❌ MCP tools = Only for coordination setup, NOT for execution
388
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
389
+
390
+ 🎯 OBJECTIVE: ${objective}
391
+
392
+ 🐝 SWARM CONFIGURATION:
393
+ - Strategy: ${strategy}
394
+ - Mode: ${mode}
395
+ - Max Agents: ${maxAgents}
396
+ - Timeout: ${flags.timeout || 60} minutes
397
+ - Parallel Execution: MANDATORY (Always use BatchTool)
398
+ - Review Mode: ${flags.review || false}
399
+ - Testing Mode: ${flags.testing || false}
400
+ - Analysis Mode: ${isAnalysisMode ? 'ENABLED (Read-Only)' : 'DISABLED'}
401
+
402
+ ${
403
+ isAnalysisMode
404
+ ? `🔍 ANALYSIS MODE CONSTRAINTS:
405
+
406
+ ⚠️ READ-ONLY MODE ACTIVE - NO CODE MODIFICATIONS ALLOWED
407
+
408
+ REQUIRED BEHAVIORS:
409
+ 1. ✅ READ files for analysis (Read tool)
410
+ 2. ✅ SEARCH codebases (Glob, Grep tools)
411
+ 3. ✅ ANALYZE code structure and patterns
412
+ 4. ✅ GENERATE reports and documentation
413
+ 5. ✅ CREATE analysis summaries
414
+ 6. ✅ STORE findings in memory for collaboration
415
+ 7. ✅ COMMUNICATE between agents about findings
416
+
417
+ FORBIDDEN OPERATIONS:
418
+ 1. ❌ NEVER use Write tool to modify files
419
+ 2. ❌ NEVER use Edit or MultiEdit tools
420
+ 3. ❌ NEVER use Bash to run commands that modify files
421
+ 4. ❌ NEVER create new files or directories
422
+ 5. ❌ NEVER install packages or dependencies
423
+ 6. ❌ NEVER modify configuration files
424
+ 7. ❌ NEVER execute code that changes system state
425
+
426
+ ALL AGENTS MUST OPERATE IN READ-ONLY MODE. Focus on:
427
+ - Code analysis and understanding
428
+ - Security vulnerability assessment
429
+ - Performance bottleneck identification
430
+ - Architecture documentation
431
+ - Technical debt analysis
432
+ - Dependency mapping
433
+ - Testing strategy recommendations
434
+
435
+ Generate comprehensive reports instead of making changes.
436
+
437
+ `
438
+ : ''
439
+ }🚨 CRITICAL: PARALLEL EXECUTION IS MANDATORY! 🚨
440
+
441
+ 📋 CLAUDE-FLOW SWARM BATCHTOOL INSTRUCTIONS
442
+
443
+ ⚡ THE GOLDEN RULE:
444
+ If you need to do X operations, they should be in 1 message, not X messages.
445
+
446
+ 🎯 MANDATORY PATTERNS FOR CLAUDE-FLOW SWARMS:
447
+
448
+ 1️⃣ **SWARM INITIALIZATION** - Use Claude Code's Task Tool for Agents:
449
+
450
+ Step A: Optional MCP Coordination Setup (Single Message):
451
+ \`\`\`javascript
452
+ [MCP Tools - Coordination ONLY]:
453
+ // Set up coordination topology (OPTIONAL)
454
+ mcp__claude-flow__swarm_init {"topology": "mesh", "maxAgents": ${maxAgents}}
455
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "SwarmLead"}
456
+ mcp__claude-flow__memory_store {"key": "swarm/objective", "value": "${objective}"}
457
+ mcp__claude-flow__memory_store {"key": "swarm/config", "value": {"strategy": "${strategy}"}}
458
+ \`\`\`
459
+
460
+ Step B: REQUIRED - Claude Code Task Tool for ACTUAL Agent Execution (Single Message):
461
+ \`\`\`javascript
462
+ [Claude Code Task Tool - CONCURRENT Agent Spawning]:
463
+ // Spawn ALL agents using Task tool in ONE message
464
+ Task("Coordinator", "Lead swarm coordination. Use hooks for memory sharing.", "coordinator")
465
+ Task("Researcher", "Analyze requirements and patterns. Coordinate via hooks.", "researcher")
466
+ Task("Backend Dev", "Implement server-side features. Share progress via hooks.", "coder")
467
+ Task("Frontend Dev", "Build UI components. Sync with backend via memory.", "coder")
468
+ Task("QA Engineer", "Create and run tests. Report findings via hooks.", "tester")
469
+
470
+ // Batch ALL todos in ONE TodoWrite call (5-10+ todos)
471
+ TodoWrite {"todos": [
472
+ {"id": "1", "content": "Initialize ${maxAgents} agent swarm", "status": "completed", "priority": "high"},
473
+ {"id": "2", "content": "Analyze: ${objective}", "status": "in_progress", "priority": "high"},
474
+ {"id": "3", "content": "Design architecture", "status": "pending", "priority": "high"},
475
+ {"id": "4", "content": "Implement backend", "status": "pending", "priority": "high"},
476
+ {"id": "5", "content": "Implement frontend", "status": "pending", "priority": "high"},
477
+ {"id": "6", "content": "Write unit tests", "status": "pending", "priority": "medium"},
478
+ {"id": "7", "content": "Integration testing", "status": "pending", "priority": "medium"},
479
+ {"id": "8", "content": "Performance optimization", "status": "pending", "priority": "low"},
480
+ {"id": "9", "content": "Documentation", "status": "pending", "priority": "low"}
481
+ ]}
482
+ \`\`\`
483
+
484
+ ⚠️ CRITICAL: Claude Code's Task tool does the ACTUAL work!
485
+ - MCP tools = Coordination setup only
486
+ - Task tool = Spawns agents that execute real work
487
+ - ALL agents MUST be spawned in ONE message
488
+ - ALL todos MUST be batched in ONE TodoWrite call
489
+
490
+ 2️⃣ **TASK COORDINATION** - Batch ALL assignments:
491
+ \`\`\`javascript
492
+ [Single Message]:
493
+ // Assign all tasks
494
+ mcp__claude-flow__task_assign {"taskId": "research-1", "agentId": "researcher-1"}
495
+ mcp__claude-flow__task_assign {"taskId": "design-1", "agentId": "architect-1"}
496
+ mcp__claude-flow__task_assign {"taskId": "code-1", "agentId": "coder-1"}
497
+ mcp__claude-flow__task_assign {"taskId": "code-2", "agentId": "coder-2"}
498
+
499
+ // Communicate to all agents
500
+ mcp__claude-flow__agent_communicate {"to": "all", "message": "Begin phase 1"}
501
+
502
+ // Update multiple task statuses
503
+ mcp__claude-flow__task_update {"taskId": "research-1", "status": "in_progress"}
504
+ mcp__claude-flow__task_update {"taskId": "design-1", "status": "pending"}
505
+ \`\`\`
506
+
507
+ 3️⃣ **MEMORY COORDINATION** - Store/retrieve in batches:
508
+ \`\`\`javascript
509
+ [Single Message]:
510
+ // Store multiple findings
511
+ mcp__claude-flow__memory_store {"key": "research/requirements", "value": {...}}
512
+ mcp__claude-flow__memory_store {"key": "research/constraints", "value": {...}}
513
+ mcp__claude-flow__memory_store {"key": "architecture/decisions", "value": {...}}
514
+
515
+ // Retrieve related data
516
+ mcp__claude-flow__memory_retrieve {"key": "research/*"}
517
+ mcp__claude-flow__memory_search {"pattern": "architecture"}
518
+ \`\`\`
519
+
520
+ 4️⃣ **FILE & CODE OPERATIONS** - Parallel execution:
521
+ \`\`\`javascript
522
+ [Single Message]:
523
+ // Read multiple files
524
+ Read {"file_path": "/src/index.js"}
525
+ Read {"file_path": "/src/config.js"}
526
+ Read {"file_path": "/package.json"}
527
+
528
+ // Write multiple files
529
+ Write {"file_path": "/src/api/auth.js", "content": "..."}
530
+ Write {"file_path": "/src/api/users.js", "content": "..."}
531
+ Write {"file_path": "/tests/auth.test.js", "content": "..."}
532
+
533
+ // Update memory with results
534
+ mcp__claude-flow__memory_store {"key": "code/api/auth", "value": "implemented"}
535
+ mcp__claude-flow__memory_store {"key": "code/api/users", "value": "implemented"}
536
+ \`\`\`
537
+
538
+ 5️⃣ **MONITORING & STATUS** - Combined checks:
539
+ \`\`\`javascript
540
+ [Single Message]:
541
+ mcp__claude-flow__swarm_monitor {}
542
+ mcp__claude-flow__swarm_status {}
543
+ mcp__claude-flow__agent_list {"status": "active"}
544
+ mcp__claude-flow__task_status {"includeCompleted": false}
545
+ TodoRead {}
546
+ \`\`\`
547
+
548
+ ❌ NEVER DO THIS (Sequential = SLOW):
549
+ \`\`\`
550
+ Message 1: mcp__claude-flow__agent_spawn
551
+ Message 2: mcp__claude-flow__agent_spawn
552
+ Message 3: TodoWrite (one todo)
553
+ Message 4: Read file
554
+ Message 5: mcp__claude-flow__memory_store
555
+ \`\`\`
556
+
557
+ ✅ ALWAYS DO THIS (Batch = FAST):
558
+ \`\`\`
559
+ Message 1: [All operations in one message]
560
+ \`\`\`
561
+
562
+ 💡 BATCHTOOL BEST PRACTICES:
563
+ - Group by operation type (all spawns, all reads, all writes)
564
+ - Use TodoWrite with 5-10 todos at once
565
+ - Combine file operations when analyzing codebases
566
+ - Store multiple memory items per message
567
+ - Never send more than one message for related operations
568
+
569
+ ${strategyGuidance}
570
+
571
+ ${modeGuidance}
572
+
573
+ ${agentRecommendations}
574
+
575
+ 📋 MANDATORY PARALLEL WORKFLOW:
576
+
577
+ 1. **INITIAL SPAWN (Single BatchTool Message):**
578
+ - Spawn ALL agents at once
579
+ - Create ALL initial todos at once
580
+ - Store initial memory state
581
+ - Create task hierarchy
582
+
583
+ Example:
584
+ \`\`\`
585
+ [BatchTool]:
586
+ mcp__claude-flow__agent_spawn (coordinator)
587
+ mcp__claude-flow__agent_spawn (architect)
588
+ mcp__claude-flow__agent_spawn (coder-1)
589
+ mcp__claude-flow__agent_spawn (coder-2)
590
+ mcp__claude-flow__agent_spawn (tester)
591
+ mcp__claude-flow__memory_store { key: "init", value: {...} }
592
+ mcp__claude-flow__task_create { name: "Main", subtasks: [...] }
593
+ TodoWrite { todos: [5-10 todos at once] }
594
+ \`\`\`
595
+
596
+ 2. **TASK EXECUTION (Parallel Batches):**
597
+ - Assign multiple tasks in one batch
598
+ - Update multiple statuses together
599
+ - Store multiple results simultaneously
600
+
601
+ 3. **MONITORING (Combined Operations):**
602
+ - Check all agent statuses together
603
+ - Retrieve multiple memory items
604
+ - Update all progress markers
605
+
606
+ 🔧 AVAILABLE MCP TOOLS FOR SWARM COORDINATION:
607
+
608
+ 📊 MONITORING & STATUS:
609
+ - mcp__claude-flow__swarm_status - Check current swarm status and agent activity
610
+ - mcp__claude-flow__swarm_monitor - Real-time monitoring of swarm execution
611
+ - mcp__claude-flow__agent_list - List all active agents and their capabilities
612
+ - mcp__claude-flow__task_status - Check task progress and dependencies
613
+
614
+ 🧠 MEMORY & KNOWLEDGE:
615
+ - mcp__claude-flow__memory_store - Store knowledge in swarm collective memory
616
+ - mcp__claude-flow__memory_retrieve - Retrieve shared knowledge from memory
617
+ - mcp__claude-flow__memory_search - Search collective memory by pattern
618
+ - mcp__claude-flow__memory_sync - Synchronize memory across agents
619
+
620
+ 🤖 AGENT MANAGEMENT:
621
+ - mcp__claude-flow__agent_spawn - Spawn specialized agents for tasks
622
+ - mcp__claude-flow__agent_assign - Assign tasks to specific agents
623
+ - mcp__claude-flow__agent_communicate - Send messages between agents
624
+ - mcp__claude-flow__agent_coordinate - Coordinate agent activities
625
+
626
+ 📋 TASK ORCHESTRATION:
627
+ - mcp__claude-flow__task_create - Create new tasks with dependencies
628
+ - mcp__claude-flow__task_assign - Assign tasks to agents
629
+ - mcp__claude-flow__task_update - Update task status and progress
630
+ - mcp__claude-flow__task_complete - Mark tasks as complete with results
631
+
632
+ 🎛️ COORDINATION MODES:
633
+ 1. CENTRALIZED (default): Single coordinator manages all agents
634
+ - Use when: Clear hierarchy needed, simple workflows
635
+ - Tools: agent_assign, task_create, swarm_monitor
636
+
637
+ 2. DISTRIBUTED: Multiple coordinators share responsibility
638
+ - Use when: Large scale tasks, fault tolerance needed
639
+ - Tools: agent_coordinate, memory_sync, task_update
640
+
641
+ 3. HIERARCHICAL: Tree structure with team leads
642
+ - Use when: Complex projects with sub-teams
643
+ - Tools: agent_spawn (with parent), task_create (with subtasks)
644
+
645
+ 4. MESH: Peer-to-peer agent coordination
646
+ - Use when: Maximum flexibility, self-organizing teams
647
+ - Tools: agent_communicate, memory_store/retrieve
648
+
649
+ ⚡ EXECUTION WORKFLOW - ALWAYS USE BATCHTOOL:
650
+ ${
651
+ enableSparc
652
+ ? `
653
+ 1. SPARC METHODOLOGY WITH PARALLEL EXECUTION:
654
+
655
+ S - Specification Phase (Single BatchTool):
656
+ \`\`\`
657
+ [BatchTool]:
658
+ mcp__claude-flow__memory_store { key: "specs/requirements", value: {...} }
659
+ mcp__claude-flow__task_create { name: "Requirement 1" }
660
+ mcp__claude-flow__task_create { name: "Requirement 2" }
661
+ mcp__claude-flow__task_create { name: "Requirement 3" }
662
+ mcp__claude-flow__agent_spawn { type: "researcher", name: "SpecAnalyst" }
663
+ \`\`\`
664
+
665
+ P - Pseudocode Phase (Single BatchTool):
666
+ \`\`\`
667
+ [BatchTool]:
668
+ mcp__claude-flow__memory_store { key: "pseudocode/main", value: {...} }
669
+ mcp__claude-flow__task_create { name: "Design API" }
670
+ mcp__claude-flow__task_create { name: "Design Data Model" }
671
+ mcp__claude-flow__agent_communicate { to: "all", message: "Review design" }
672
+ \`\`\`
673
+
674
+ A - Architecture Phase (Single BatchTool):
675
+ \`\`\`
676
+ [BatchTool]:
677
+ mcp__claude-flow__agent_spawn { type: "architect", name: "LeadArchitect" }
678
+ mcp__claude-flow__memory_store { key: "architecture/decisions", value: {...} }
679
+ mcp__claude-flow__task_create { name: "Backend", subtasks: [...] }
680
+ mcp__claude-flow__task_create { name: "Frontend", subtasks: [...] }
681
+ \`\`\`
682
+
683
+ R - Refinement Phase (Single BatchTool):
684
+ \`\`\`
685
+ [BatchTool]:
686
+ mcp__claude-flow__swarm_monitor {}
687
+ mcp__claude-flow__task_update { taskId: "1", progress: 50 }
688
+ mcp__claude-flow__task_update { taskId: "2", progress: 75 }
689
+ mcp__claude-flow__memory_store { key: "learnings/iteration1", value: {...} }
690
+ \`\`\`
691
+
692
+ C - Completion Phase (Single BatchTool):
693
+ \`\`\`
694
+ [BatchTool]:
695
+ mcp__claude-flow__task_complete { taskId: "1", results: {...} }
696
+ mcp__claude-flow__task_complete { taskId: "2", results: {...} }
697
+ mcp__claude-flow__memory_retrieve { pattern: "**/*" }
698
+ TodoWrite { todos: [{content: "Final review", status: "completed"}] }
699
+ \`\`\`
700
+ `
701
+ : `
702
+ 1. STANDARD SWARM EXECUTION WITH PARALLEL OPERATIONS:
703
+
704
+ Initial Setup (Single BatchTool):
705
+ \`\`\`
706
+ [BatchTool]:
707
+ mcp__claude-flow__task_create { name: "Main", subtasks: [...] }
708
+ mcp__claude-flow__agent_spawn { type: "coordinator" }
709
+ mcp__claude-flow__agent_spawn { type: "coder" }
710
+ mcp__claude-flow__agent_spawn { type: "tester" }
711
+ mcp__claude-flow__memory_store { key: "init", value: {...} }
712
+ \`\`\`
713
+
714
+ Task Assignment (Single BatchTool):
715
+ \`\`\`
716
+ [BatchTool]:
717
+ mcp__claude-flow__task_assign { taskId: "1", agentId: "agent-1" }
718
+ mcp__claude-flow__task_assign { taskId: "2", agentId: "agent-2" }
719
+ mcp__claude-flow__task_assign { taskId: "3", agentId: "agent-3" }
720
+ \`\`\`
721
+
722
+ Monitoring & Updates (Single BatchTool):
723
+ \`\`\`
724
+ [BatchTool]:
725
+ mcp__claude-flow__swarm_monitor {}
726
+ mcp__claude-flow__agent_communicate { to: "all", message: "Status update" }
727
+ mcp__claude-flow__memory_store { key: "progress", value: {...} }
728
+ \`\`\`
729
+ `
730
+ }
731
+
732
+ 🤝 AGENT TYPES & THEIR MCP TOOL USAGE:
733
+
734
+ COORDINATOR:
735
+ - Primary tools: swarm_monitor, agent_assign, task_create
736
+ - Monitors overall progress and assigns work
737
+ - Uses memory_store for decisions and memory_retrieve for context
738
+
739
+ RESEARCHER:
740
+ - Primary tools: memory_search, memory_store
741
+ - Gathers information and stores findings
742
+ - Uses agent_communicate to share discoveries
743
+
744
+ CODER:
745
+ - Primary tools: task_update, memory_retrieve, memory_store
746
+ - Implements solutions and updates progress
747
+ - Retrieves specs from memory, stores code artifacts
748
+
749
+ ANALYST:
750
+ - Primary tools: memory_search, swarm_monitor
751
+ - Analyzes data and patterns
752
+ - Stores insights and recommendations
753
+
754
+ TESTER:
755
+ - Primary tools: task_status, agent_communicate
756
+ - Validates implementations
757
+ - Reports issues via task_update
758
+
759
+ 📝 EXAMPLE MCP TOOL USAGE PATTERNS:
760
+
761
+ 1. Starting a swarm:
762
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "SwarmLead"}
763
+ mcp__claude-flow__memory_store {"key": "objective", "value": "${objective}"}
764
+ mcp__claude-flow__task_create {"name": "Main Objective", "type": "parent"}
765
+
766
+ 2. Spawning worker agents:
767
+ mcp__claude-flow__agent_spawn {"type": "researcher", "capabilities": ["web-search"]}
768
+ mcp__claude-flow__agent_spawn {"type": "coder", "capabilities": ["python", "testing"]}
769
+ mcp__claude-flow__task_assign {"taskId": "task-123", "agentId": "agent-456"}
770
+
771
+ 3. Coordinating work:
772
+ mcp__claude-flow__agent_communicate {"to": "agent-123", "message": "Begin phase 2"}
773
+ mcp__claude-flow__memory_store {"key": "phase1/results", "value": {...}}
774
+ mcp__claude-flow__task_update {"taskId": "task-123", "progress": 75}
775
+
776
+ 4. Monitoring progress:
777
+ mcp__claude-flow__swarm_monitor {}
778
+ mcp__claude-flow__task_status {"includeCompleted": true}
779
+ mcp__claude-flow__agent_list {"status": "active"}
780
+
781
+ 💾 MEMORY PATTERNS:
782
+
783
+ Use hierarchical keys for organization:
784
+ - "specs/requirements" - Store specifications
785
+ - "architecture/decisions" - Architecture choices
786
+ - "code/modules/[name]" - Code artifacts
787
+ - "tests/results/[id]" - Test outcomes
788
+ - "docs/api/[endpoint]" - Documentation
789
+
790
+ 🚀 BEGIN SWARM EXECUTION:
791
+
792
+ Start by spawning a coordinator agent and creating the initial task structure. Use the MCP tools to orchestrate the swarm, coordinate agents, and track progress. Remember to store important decisions and artifacts in collective memory for other agents to access.
793
+
794
+ The swarm should be self-documenting - use memory_store to save all important information, decisions, and results throughout the execution.`;
795
+
796
+ // If --claude flag is used, force Claude Code even if CLI not available
797
+ if (flags && flags.claude) {
798
+ // --claude flag means interactive mode, so don't apply non-interactive
799
+ console.log('🐝 Launching Claude Flow Swarm System...');
800
+ console.log(`📋 Objective: ${objective}`);
801
+ console.log(`🎯 Strategy: ${strategy}`);
802
+ console.log(`🏗️ Mode: ${mode}`);
803
+ console.log(`🤖 Max Agents: ${maxAgents}\n`);
804
+
805
+ console.log('🚀 Launching Claude Code with Swarm Coordination');
806
+ console.log('─'.repeat(60));
807
+
808
+ // Build arguments properly: for interactive mode, prompt can be first
809
+ const claudeArgs = [];
810
+
811
+ // Add auto-permission flag first
812
+ if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
813
+ claudeArgs.push('--dangerously-skip-permissions');
814
+ console.log(
815
+ '🔓 Using --dangerously-skip-permissions by default for seamless swarm execution',
816
+ );
817
+ }
818
+
819
+ // Add the prompt (for interactive mode, position doesn't matter as much)
820
+ claudeArgs.push(swarmPrompt);
821
+
822
+ // --claude flag means interactive mode, so don't add non-interactive flags
823
+
824
+ // For --claude interactive mode, spawn Claude directly
825
+ // Temporarily disable telemetry to avoid console output interference
826
+ const claudeEnv = { ...process.env };
827
+
828
+ // Remove telemetry env vars to prevent console output
829
+ delete claudeEnv.CLAUDE_CODE_ENABLE_TELEMETRY;
830
+ delete claudeEnv.OTEL_METRICS_EXPORTER;
831
+ delete claudeEnv.OTEL_LOGS_EXPORTER;
832
+
833
+ const claudeProcess = spawn('claude', claudeArgs, {
834
+ stdio: 'inherit',
835
+ shell: false,
836
+ env: claudeEnv,
837
+ });
838
+
839
+ console.log('\n✓ Claude Code launched with swarm coordination prompt!');
840
+ console.log(' The swarm coordinator will orchestrate all agent tasks');
841
+ console.log(' Use MCP tools for coordination and memory sharing');
842
+
843
+ console.log('\n💡 Pro Tips:');
844
+ console.log('─'.repeat(30));
845
+ console.log('• Use TodoWrite to track parallel tasks');
846
+ console.log('• Store results with mcp__claude-flow__memory_usage');
847
+ console.log('• Monitor progress with mcp__claude-flow__swarm_monitor');
848
+ console.log('• Check task status with mcp__claude-flow__task_status');
849
+
850
+ // Set up clean termination
851
+ const cleanup = () => {
852
+ console.log('\n🛑 Shutting down swarm gracefully...');
853
+ if (claudeProcess && !claudeProcess.killed) {
854
+ claudeProcess.kill('SIGTERM');
855
+ }
856
+ process.exit(0);
857
+ };
858
+
859
+ process.on('SIGINT', cleanup);
860
+ process.on('SIGTERM', cleanup);
861
+
862
+ // Wait for claude to exit
863
+ claudeProcess.on('exit', (code) => {
864
+ if (code === 0) {
865
+ console.log('\n✓ Swarm execution completed successfully');
866
+ } else if (code !== null) {
867
+ console.log(`\n✗ Swarm execution exited with code ${code}`);
868
+ }
869
+ process.exit(code || 0);
870
+ });
871
+
872
+ // Handle spawn errors (e.g., claude not found)
873
+ claudeProcess.on('error', (err) => {
874
+ if (err.code === 'ENOENT') {
875
+ console.error('\n❌ Claude Code CLI not found. Please install Claude Code:');
876
+ console.error(' https://claude.ai/download');
877
+ } else {
878
+ console.error('\n❌ Failed to launch Claude Code:', err.message);
879
+ }
880
+ process.exit(1);
881
+ });
882
+
883
+ return;
884
+ }
885
+
886
+ // Check if we're in non-interactive/headless mode FIRST (like alpha.83)
887
+ const isNonInteractive =
888
+ flags['no-interactive'] ||
889
+ flags['non-interactive'] ||
890
+ flags['output-format'] === 'stream-json' ||
891
+ isHeadlessEnvironment();
892
+
893
+ // Check if claude command exists
894
+ let claudeAvailable = false;
895
+ try {
896
+ execSync('which claude', { stdio: 'ignore' });
897
+ claudeAvailable = true;
898
+ } catch {
899
+ if (!isNonInteractive) {
900
+ console.log('⚠️ Claude Code CLI not found in PATH');
901
+ console.log('Install it with: npm install -g @anthropic-ai/claude-code');
902
+ console.log('Or use --claude flag to open Claude Code CLI');
903
+ console.log('\nWould spawn Claude Code with swarm objective:');
904
+ console.log(`📋 Objective: ${objective}`);
905
+ console.log('\nOptions:');
906
+ console.log(
907
+ ' • Use --executor flag for built-in executor: claude-flow swarm "objective" --executor',
908
+ );
909
+ console.log(
910
+ ' • Use --claude flag to open Claude Code CLI: claude-flow swarm "objective" --claude',
911
+ );
912
+ } else {
913
+ // In non-interactive mode, output JSON error
914
+ console.error(
915
+ JSON.stringify({
916
+ error: 'Claude Code CLI not found',
917
+ message: 'Install with: npm install -g @anthropic-ai/claude-code',
918
+ fallback: 'Use --executor flag for built-in executor',
919
+ }),
920
+ );
921
+ }
922
+ return;
923
+ }
924
+
925
+ // Claude is available, use it to run swarm
926
+ if (!isNonInteractive) {
927
+ console.log('🐝 Launching Claude Flow Swarm System...');
928
+ console.log(`📋 Objective: ${objective}`);
929
+ console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);
930
+ console.log(`🏗️ Mode: ${flags.mode || 'centralized'}`);
931
+ console.log(`🤖 Max Agents: ${flags['max-agents'] || 5}`);
932
+ if (isAnalysisMode) {
933
+ console.log(`🔍 Analysis Mode: ENABLED (Read-Only - No Code Changes)`);
934
+ }
935
+ console.log();
936
+ } else {
937
+ // Non-interactive mode output
938
+ console.log('🤖 Running in non-interactive mode with Claude');
939
+ console.log('📋 Command: claude [prompt] -p --output-format stream-json --verbose');
940
+ }
941
+
942
+ // Continue with the default swarm behavior if not using --claude flag
943
+
944
+ // Build arguments in correct order: flags first, then prompt
945
+ const claudeArgs = [];
946
+
947
+ // Add non-interactive flags FIRST if needed
948
+ if (isNonInteractive) {
949
+ claudeArgs.push('-p'); // Print mode
950
+ claudeArgs.push('--output-format', 'stream-json'); // JSON streaming
951
+ claudeArgs.push('--verbose'); // Verbose output
952
+ }
953
+
954
+ // Add auto-permission flag BEFORE the prompt
955
+ if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
956
+ claudeArgs.push('--dangerously-skip-permissions');
957
+ if (!isNonInteractive) {
958
+ console.log(
959
+ '🔓 Using --dangerously-skip-permissions by default for seamless swarm execution',
960
+ );
961
+ }
962
+ }
963
+
964
+ // Add the prompt as the LAST argument
965
+ claudeArgs.push(swarmPrompt);
966
+
967
+ // Spawn claude with properly ordered arguments
968
+ const claudeProcess = spawn('claude', claudeArgs, {
969
+ stdio: 'inherit',
970
+ shell: false,
971
+ });
972
+
973
+ if (!isNonInteractive) {
974
+ console.log('✓ Claude Code launched with swarm coordination prompt!');
975
+ console.log('\n🚀 The swarm coordination instructions have been injected into Claude Code');
976
+ console.log(' The prompt includes:');
977
+ console.log(' • Strategy-specific guidance for', strategy);
978
+ console.log(' • Coordination patterns for', mode, 'mode');
979
+ console.log(' • Recommended agents and MCP tool usage');
980
+ console.log(' • Complete workflow documentation\n');
981
+ }
982
+
983
+ // Handle process events
984
+ claudeProcess.on('error', (err) => {
985
+ console.error('❌ Failed to launch Claude Code:', err.message);
986
+ });
987
+
988
+ // Don't wait for completion - let it run
989
+ return;
990
+ } catch (error) {
991
+ console.error('❌ Failed to spawn Claude Code:', error.message);
992
+ console.log('\nFalling back to built-in executor...');
993
+ // Fall through to executor implementation
994
+ }
995
+ }
996
+
997
+ // Check if we should run in background mode
998
+ if (flags && flags.background && !process.env.CLAUDE_SWARM_NO_BG) {
999
+ // Check if we're in Deno environment
1000
+ if (typeof Deno !== 'undefined') {
1001
+ // In Deno, spawn a new process for true background execution
1002
+ const objective = (args || []).join(' ').trim();
1003
+ const swarmId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1004
+ const swarmRunDir = `./swarm-runs/${swarmId}`;
1005
+
1006
+ // Create swarm directory
1007
+ await mkdirAsync(swarmRunDir, { recursive: true });
1008
+
1009
+ console.log(`🐝 Launching swarm in background mode...`);
1010
+ console.log(`📋 Objective: ${objective}`);
1011
+ console.log(`🆔 Swarm ID: ${swarmId}`);
1012
+ console.log(`📁 Results: ${swarmRunDir}`);
1013
+
1014
+ // Build command args without background flag (to prevent infinite loop)
1015
+ const commandArgs = ['run', '--allow-all', import.meta.url, objective];
1016
+ const newFlags = { ...flags };
1017
+ delete newFlags.background; // Remove background flag
1018
+
1019
+ for (const [key, value] of Object.entries(newFlags)) {
1020
+ commandArgs.push(`--${key}`);
1021
+ if (value !== true) {
1022
+ commandArgs.push(String(value));
1023
+ }
1024
+ }
1025
+
1026
+ // Create log file
1027
+ const logFile = `${swarmRunDir}/swarm.log`;
1028
+ const logHandle = await open(logFile, 'w');
1029
+
1030
+ // Create a script to run the swarm without background flag
1031
+ const scriptContent = `#!/usr/bin/env -S deno run --allow-all
1032
+ import { swarmCommand } from "${import.meta.url}";
1033
+ import { cwd, exit, existsSync } from '../node-compat.js';
1034
+ import process from 'process';
1035
+
1036
+ // Remove background flag to prevent recursion
1037
+ const flags = ${JSON.stringify(newFlags)};
1038
+ const args = ${JSON.stringify(args)};
1039
+
1040
+ // Set env to prevent background spawning
1041
+ process.env.CLAUDE_SWARM_NO_BG = 'true';
1042
+
1043
+ // Run the swarm
1044
+ await swarmCommand(args, flags);
1045
+ `;
1046
+
1047
+ const scriptPath = `${swarmRunDir}/run-swarm.js`;
1048
+ await writeTextFile(scriptPath, scriptContent);
1049
+
1050
+ // Save process info first
1051
+ await writeTextFile(
1052
+ `${swarmRunDir}/process.json`,
1053
+ JSON.stringify(
1054
+ {
1055
+ swarmId: swarmId,
1056
+ objective: objective,
1057
+ startTime: new Date().toISOString(),
1058
+ logFile: logFile,
1059
+ status: 'starting',
1060
+ },
1061
+ null,
1062
+ 2,
1063
+ ),
1064
+ );
1065
+
1066
+ // Close log handle before spawning
1067
+ logHandle.close();
1068
+
1069
+ // Use the bash script for true background execution
1070
+ const binDir = new URL('../../../bin/', import.meta.url).pathname;
1071
+ const bgScriptPath = `${binDir}claude-flow-swarm-bg`;
1072
+
1073
+ try {
1074
+ // Check if the background script exists
1075
+ statSync(bgScriptPath);
1076
+
1077
+ // Build command args for the background script
1078
+ const bgArgs = [objective];
1079
+ for (const [key, value] of Object.entries(newFlags)) {
1080
+ bgArgs.push(`--${key}`);
1081
+ if (value !== true) {
1082
+ bgArgs.push(String(value));
1083
+ }
1084
+ }
1085
+
1086
+ // Use the bash background script
1087
+ const bgProcess = spawn(bgScriptPath, bgArgs, {
1088
+ stdio: ['ignore', 'pipe', 'pipe'],
1089
+ });
1090
+
1091
+ // Read and display output
1092
+ const decoder = new TextDecoder();
1093
+ const output = await bgProcess.output();
1094
+ console.log(decoder.decode(output.stdout));
1095
+
1096
+ // Exit immediately after launching
1097
+ exit(0);
1098
+ } catch (error) {
1099
+ // Fallback: create a double-fork pattern using a shell script
1100
+ console.log(`\n⚠️ Background script not found, using fallback method`);
1101
+
1102
+ // Create a shell script that will run the swarm
1103
+ const shellScript = `#!/bin/bash
1104
+ # Double fork to detach from parent
1105
+ (
1106
+ (
1107
+ node "${scriptPath}" > "${logFile}" 2>&1 &
1108
+ echo $! > "${swarmRunDir}/swarm.pid"
1109
+ ) &
1110
+ )
1111
+ exit 0
1112
+ `;
1113
+
1114
+ const shellScriptPath = `${swarmRunDir}/launch-background.sh`;
1115
+ await writeTextFile(shellScriptPath, shellScript);
1116
+ chmodSync(shellScriptPath, 0o755);
1117
+
1118
+ // Execute the shell script
1119
+ const shellProcess = spawn('bash', [shellScriptPath], {
1120
+ stdio: 'ignore',
1121
+ detached: true,
1122
+ });
1123
+ shellProcess.unref();
1124
+
1125
+ console.log(`\n✅ Swarm launched in background!`);
1126
+ console.log(`📄 Logs: tail -f ${logFile}`);
1127
+ console.log(`📊 Status: claude-flow swarm status ${swarmId}`);
1128
+ console.log(`\nThe swarm will continue running independently.`);
1129
+
1130
+ // Exit immediately
1131
+ exit(0);
1132
+ }
1133
+ }
1134
+
1135
+ // Node.js environment - use background script
1136
+ const { execSync } = await import('child_process');
1137
+ const path = await import('path');
1138
+ const fs = await import('fs');
1139
+
1140
+ const objective = (args || []).join(' ').trim();
1141
+
1142
+ // Get the claude-flow-swarm-bg script path
1143
+ const bgScriptPath = path.join(
1144
+ path.dirname(new URL(import.meta.url).pathname),
1145
+ '../../../bin/claude-flow-swarm-bg',
1146
+ );
1147
+
1148
+ // Check if background script exists
1149
+ if (fs.existsSync(bgScriptPath)) {
1150
+ // Build command args
1151
+ const commandArgs = [objective];
1152
+ for (const [key, value] of Object.entries(flags)) {
1153
+ if (key !== 'background') {
1154
+ // Skip background flag
1155
+ commandArgs.push(`--${key}`);
1156
+ if (value !== true) {
1157
+ commandArgs.push(String(value));
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ // Execute the background script
1163
+ try {
1164
+ execSync(`"${bgScriptPath}" ${commandArgs.map((arg) => `"${arg}"`).join(' ')}`, {
1165
+ stdio: 'inherit',
1166
+ });
1167
+ } catch (error) {
1168
+ console.error('Failed to launch background swarm:', error.message);
1169
+ }
1170
+ } else {
1171
+ // Fallback to simple message
1172
+ console.log(`🐝 Background mode requested`);
1173
+ console.log(`📋 Objective: ${objective}`);
1174
+ console.log(`\n⚠️ Background execution requires the claude-flow-swarm-bg script.`);
1175
+ console.log(`\nFor true background execution, use:`);
1176
+ console.log(
1177
+ ` nohup claude-flow swarm "${objective}" ${Object.entries(flags)
1178
+ .filter(([k, v]) => k !== 'background' && v)
1179
+ .map(([k, v]) => `--${k}${v !== true ? ` ${v}` : ''}`)
1180
+ .join(' ')} > swarm.log 2>&1 &`,
1181
+ );
1182
+ }
1183
+ return;
1184
+ }
1185
+
1186
+ try {
1187
+ // Try to load the compiled JavaScript module first
1188
+ let swarmAction;
1189
+ try {
1190
+ // Try the compiled version first (for production/npm packages)
1191
+ const distPath = new URL('../../../dist/cli/commands/swarm-new.js', import.meta.url);
1192
+ const module = await import(distPath);
1193
+ swarmAction = module.swarmAction;
1194
+ } catch (distError) {
1195
+ // Instead of immediately falling back to basic mode,
1196
+ // continue to the Claude integration below
1197
+ console.log('📦 Compiled swarm module not found, checking for Claude CLI...');
1198
+ }
1199
+
1200
+ // Only call swarmAction if it was successfully loaded
1201
+ if (swarmAction) {
1202
+ // Create command context compatible with TypeScript version
1203
+ const ctx = {
1204
+ args: args || [],
1205
+ flags: flags || {},
1206
+ command: 'swarm',
1207
+ };
1208
+
1209
+ await swarmAction(ctx);
1210
+ return; // Exit after successful execution
1211
+ }
1212
+ } catch (error) {
1213
+ // If import fails (e.g., in node_modules), provide inline implementation
1214
+ if (
1215
+ error.code === 'ERR_MODULE_NOT_FOUND' ||
1216
+ error.code === 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING' ||
1217
+ error.code === 'ERR_UNKNOWN_FILE_EXTENSION'
1218
+ ) {
1219
+ // Provide a basic swarm implementation that works without TypeScript imports
1220
+ const objective = (args || []).join(' ').trim();
1221
+
1222
+ if (!objective) {
1223
+ console.error('❌ Usage: swarm <objective>');
1224
+ showSwarmHelp();
1225
+ return;
1226
+ }
1227
+
1228
+ // Try to use the swarm executor directly
1229
+ try {
1230
+ const { executeSwarm } = await import('./swarm-executor.js');
1231
+ const result = await executeSwarm(objective, flags);
1232
+
1233
+ // If execution was successful, exit
1234
+ if (result && result.success) {
1235
+ return;
1236
+ }
1237
+ } catch (execError) {
1238
+ console.log(`⚠️ Swarm executor error: ${execError.message}`);
1239
+ // If swarm executor fails, try to create files directly
1240
+ try {
1241
+ await createSwarmFiles(objective, flags);
1242
+ return;
1243
+ } catch (createError) {
1244
+ console.log(`⚠️ Direct file creation error: ${createError.message}`);
1245
+ // Continue with fallback implementation
1246
+ }
1247
+ }
1248
+
1249
+ // Provide a basic inline swarm implementation for npm packages
1250
+ console.log('🐝 Launching swarm system...');
1251
+ console.log(`📋 Objective: ${objective}`);
1252
+ console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);
1253
+ console.log(`🏗️ Mode: ${flags.mode || 'centralized'}`);
1254
+ console.log(`🤖 Max Agents: ${flags['max-agents'] || 5}`);
1255
+ console.log();
1256
+
1257
+ // Generate swarm ID
1258
+ const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;
1259
+
1260
+ if (flags['dry-run']) {
1261
+ console.log(`🆔 Swarm ID: ${swarmId}`);
1262
+ console.log(`📊 Max Tasks: ${flags['max-tasks'] || 100}`);
1263
+ console.log(`⏰ Timeout: ${flags.timeout || 60} minutes`);
1264
+ console.log(`🔄 Parallel: ${flags.parallel || false}`);
1265
+ console.log(`🌐 Distributed: ${flags.distributed || false}`);
1266
+ console.log(`🔍 Monitoring: ${flags.monitor || false}`);
1267
+ console.log(`👥 Review Mode: ${flags.review || false}`);
1268
+ console.log(`🧪 Testing: ${flags.testing || false}`);
1269
+ console.log(`🧠 Memory Namespace: ${flags['memory-namespace'] || 'swarm'}`);
1270
+ console.log(`💾 Persistence: ${flags.persistence !== false}`);
1271
+ console.log(`🔒 Encryption: ${flags.encryption || false}`);
1272
+ console.log(`📊 Quality Threshold: ${flags['quality-threshold'] || 0.8}`);
1273
+ console.log();
1274
+ console.log('🎛️ Coordination Strategy:');
1275
+ console.log(` • Agent Selection: ${flags['agent-selection'] || 'capability-based'}`);
1276
+ console.log(` • Task Scheduling: ${flags['task-scheduling'] || 'priority'}`);
1277
+ console.log(` • Load Balancing: ${flags['load-balancing'] || 'work-stealing'}`);
1278
+ console.log(` • Fault Tolerance: ${flags['fault-tolerance'] || 'retry'}`);
1279
+ console.log(` • Communication: ${flags.communication || 'event-driven'}`);
1280
+ console.log('⚠️ DRY RUN - Advanced Swarm Configuration');
1281
+ return;
1282
+ }
1283
+
1284
+ // For actual execution in npm context, try to find and run swarm-demo.ts
1285
+ try {
1286
+ const path = await import('path');
1287
+ const { fileURLToPath } = await import('url');
1288
+ const fs = await import('fs');
1289
+ const { spawn } = await import('child_process');
1290
+
1291
+ const __filename = fileURLToPath(import.meta.url);
1292
+ const __dirname = path.dirname(__filename);
1293
+
1294
+ // Look for swarm-demo.ts in the package
1295
+ const possiblePaths = [
1296
+ path.join(__dirname, '../../../swarm-demo.ts'),
1297
+ path.join(__dirname, '../../swarm-demo.ts'),
1298
+ ];
1299
+
1300
+ let swarmDemoPath = null;
1301
+ for (const p of possiblePaths) {
1302
+ if (fs.existsSync(p)) {
1303
+ swarmDemoPath = p;
1304
+ break;
1305
+ }
1306
+ }
1307
+
1308
+ if (swarmDemoPath && Deno) {
1309
+ // Run swarm-demo.ts directly with Deno
1310
+ const swarmArgs = [objective];
1311
+ for (const [key, value] of Object.entries(flags || {})) {
1312
+ swarmArgs.push(`--${key}`);
1313
+ if (value !== true) {
1314
+ swarmArgs.push(String(value));
1315
+ }
1316
+ }
1317
+
1318
+ console.log('🚀 Starting advanced swarm execution...');
1319
+ const swarmProcess = spawn('node', [swarmDemoPath, ...swarmArgs], {
1320
+ stdio: 'inherit',
1321
+ });
1322
+
1323
+ swarmProcess.on('error', (err) => {
1324
+ console.error('❌ Failed to launch swarm:', err.message);
1325
+ });
1326
+
1327
+ swarmProcess.on('exit', (code) => {
1328
+ if (code !== 0) {
1329
+ console.error(`❌ Swarm exited with code ${code}`);
1330
+ }
1331
+ });
1332
+ return;
1333
+ }
1334
+ } catch (e) {
1335
+ // Fallback to basic message if can't run swarm-demo.ts
1336
+ }
1337
+
1338
+ // Try to use Claude wrapper approach like SPARC does
1339
+ try {
1340
+ const { execSync } = await import('child_process');
1341
+
1342
+ // Check if claude command exists
1343
+ try {
1344
+ execSync('which claude', { stdio: 'ignore' });
1345
+ } catch (e) {
1346
+ // Claude not found, show fallback message
1347
+ console.log(`✅ Swarm initialized with ID: ${swarmId}`);
1348
+ console.log('\n⚠️ Note: Advanced swarm features require Claude or local installation.');
1349
+ console.log('Install Claude: https://claude.ai/code');
1350
+ console.log('Or install locally: npm install -g claude-flow@latest');
1351
+ console.log('\nThe swarm system would coordinate the following:');
1352
+ console.log('1. Agent spawning and task distribution');
1353
+ console.log('2. Parallel execution of subtasks');
1354
+ console.log('3. Memory sharing between agents');
1355
+ console.log('4. Progress monitoring and reporting');
1356
+ console.log('5. Result aggregation and quality checks');
1357
+ return;
1358
+ }
1359
+
1360
+ // Claude is available, use it to run swarm
1361
+ console.log('🚀 Launching swarm via Claude wrapper...');
1362
+ if (flags.sparc !== false) {
1363
+ console.log('🧪 SPARC methodology enabled - using full TDD workflow');
1364
+ }
1365
+
1366
+ // Build the prompt for Claude using SPARC methodology
1367
+ const enableSparc = flags.sparc !== false;
1368
+ const swarmPrompt = `Execute a swarm coordination task using ${enableSparc ? 'the full SPARC methodology' : 'standard approach'}:
1369
+
1370
+ OBJECTIVE: ${objective}
1371
+
1372
+ CONFIGURATION:
1373
+ - Strategy: ${flags.strategy || 'auto'}
1374
+ - Mode: ${flags.mode || 'centralized'}
1375
+ - Max Agents: ${flags['max-agents'] || 5}
1376
+ - Memory Namespace: ${flags['memory-namespace'] || 'swarm'}
1377
+ - Quality Threshold: ${flags['quality-threshold'] || 0.8}
1378
+ ${enableSparc ? '- SPARC Enabled: YES - Use full Specification, Pseudocode, Architecture, Refinement (TDD), Completion methodology' : ''}
1379
+
1380
+ ${
1381
+ enableSparc
1382
+ ? `
1383
+ SPARC METHODOLOGY REQUIREMENTS:
1384
+
1385
+ 1. SPECIFICATION PHASE:
1386
+ - Create detailed requirements and acceptance criteria
1387
+ - Define user stories with clear objectives
1388
+ - Document functional and non-functional requirements
1389
+ - Establish quality metrics and success criteria
1390
+
1391
+ 2. PSEUDOCODE PHASE:
1392
+ - Design algorithms and data structures
1393
+ - Create flow diagrams and logic patterns
1394
+ - Define interfaces and contracts
1395
+ - Plan error handling strategies
1396
+
1397
+ 3. ARCHITECTURE PHASE:
1398
+ - Design system architecture with proper components
1399
+ - Define APIs and service boundaries
1400
+ - Plan database schemas if applicable
1401
+ - Create deployment architecture
1402
+
1403
+ 4. REFINEMENT PHASE (TDD):
1404
+ - RED: Write comprehensive failing tests first
1405
+ - GREEN: Implement minimal code to pass tests
1406
+ - REFACTOR: Optimize and clean up implementation
1407
+ - Ensure >80% test coverage
1408
+
1409
+ 5. COMPLETION PHASE:
1410
+ - Integrate all components
1411
+ - Create comprehensive documentation
1412
+ - Perform end-to-end testing
1413
+ - Validate against original requirements
1414
+ `
1415
+ : ''
1416
+ }
1417
+
1418
+ EXECUTION APPROACH:
1419
+ 1. Analyze the objective and break it down into specific tasks
1420
+ 2. Create a comprehensive implementation plan
1421
+ 3. ${enableSparc ? 'Follow SPARC phases sequentially with proper artifacts for each phase' : 'Implement the solution directly'}
1422
+ 4. Generate production-ready code with proper structure
1423
+ 5. Include all necessary files (source code, tests, configs, documentation)
1424
+ 6. Ensure the implementation is complete and functional
1425
+
1426
+ TARGET DIRECTORY:
1427
+ Extract from the objective or use a sensible default. Create all files in the appropriate directory structure.
1428
+
1429
+ IMPORTANT:
1430
+ - Create actual, working implementations - not templates or placeholders
1431
+ - Include comprehensive tests using appropriate testing frameworks
1432
+ - Add proper error handling and logging
1433
+ - Include configuration files (package.json, requirements.txt, etc.)
1434
+ - Create detailed README with setup and usage instructions
1435
+ - Follow best practices for the technology stack
1436
+ - Make the code production-ready, not just examples
1437
+
1438
+ Begin execution now. Create all necessary files and provide a complete, working solution.`;
1439
+
1440
+ // Execute Claude non-interactively by piping the prompt
1441
+ const { spawn } = await import('child_process');
1442
+
1443
+ const claudeArgs = [];
1444
+
1445
+ // Add auto-permission flag by default for swarm mode (unless explicitly disabled)
1446
+ if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
1447
+ claudeArgs.push('--dangerously-skip-permissions');
1448
+ }
1449
+
1450
+ // Spawn claude process
1451
+ const claudeProcess = spawn('claude', claudeArgs, {
1452
+ stdio: ['pipe', 'inherit', 'inherit'],
1453
+ shell: false,
1454
+ });
1455
+
1456
+ // Write the prompt to stdin and close it
1457
+ claudeProcess.stdin.write(swarmPrompt);
1458
+ claudeProcess.stdin.end();
1459
+
1460
+ // Wait for the process to complete
1461
+ await new Promise((resolve, reject) => {
1462
+ claudeProcess.on('close', (code) => {
1463
+ if (code === 0) {
1464
+ resolve();
1465
+ } else {
1466
+ reject(new Error(`Claude process exited with code ${code}`));
1467
+ }
1468
+ });
1469
+
1470
+ claudeProcess.on('error', (err) => {
1471
+ reject(err);
1472
+ });
1473
+ });
1474
+ } catch (error) {
1475
+ // Fallback if Claude execution fails
1476
+ console.log(`✅ Swarm initialized with ID: ${swarmId}`);
1477
+ console.log('\n⚠️ Note: Advanced swarm features require Claude or local installation.');
1478
+ console.log('Install Claude: https://claude.ai/code');
1479
+ console.log('Or install locally: npm install -g claude-flow@latest');
1480
+ console.log('\nThe swarm system would coordinate the following:');
1481
+ console.log('1. Agent spawning and task distribution');
1482
+ console.log('2. Parallel execution of subtasks');
1483
+ console.log('3. Memory sharing between agents');
1484
+ console.log('4. Progress monitoring and reporting');
1485
+ console.log('5. Result aggregation and quality checks');
1486
+ }
1487
+
1488
+ return;
1489
+ }
1490
+
1491
+ console.error('Swarm command error:', error);
1492
+
1493
+ // Fallback to comprehensive help if there's an import error
1494
+ console.log(`
1495
+ 🐝 Claude Flow Advanced Swarm System
1496
+
1497
+ USAGE:
1498
+ claude-flow swarm <objective> [options]
1499
+
1500
+ EXAMPLES:
1501
+ claude-flow swarm "Build a REST API" --strategy development
1502
+ claude-flow swarm "Research cloud architecture" --strategy research --ui
1503
+ claude-flow swarm "Analyze data trends" --strategy analysis --parallel
1504
+ claude-flow swarm "Optimize performance" --distributed --monitor
1505
+
1506
+ STRATEGIES:
1507
+ auto Automatically determine best approach (default)
1508
+ research Research and information gathering
1509
+ development Software development and coding
1510
+ analysis Data analysis and insights
1511
+ testing Testing and quality assurance
1512
+ optimization Performance optimization
1513
+ maintenance System maintenance
1514
+
1515
+ MODES:
1516
+ centralized Single coordinator (default)
1517
+ distributed Multiple coordinators
1518
+ hierarchical Tree structure coordination
1519
+ mesh Peer-to-peer coordination
1520
+ hybrid Mixed coordination strategies
1521
+
1522
+ KEY FEATURES:
1523
+ 🤖 Intelligent agent management with specialized types
1524
+ ⚡ Timeout-free background task execution
1525
+ 🧠 Distributed memory sharing between agents
1526
+ 🔄 Work stealing and advanced load balancing
1527
+ 🛡️ Circuit breaker patterns for fault tolerance
1528
+ 📊 Real-time monitoring and comprehensive metrics
1529
+ 🎛️ Multiple coordination strategies and algorithms
1530
+ 💾 Persistent state with backup and recovery
1531
+ 🔒 Security features with encryption options
1532
+ 🖥️ Interactive terminal UI for management
1533
+
1534
+ OPTIONS:
1535
+ --strategy <type> Execution strategy (default: auto)
1536
+ --mode <type> Coordination mode (default: centralized)
1537
+ --max-agents <n> Maximum agents (default: 5)
1538
+ --timeout <minutes> Timeout in minutes (default: 60)
1539
+ --task-timeout-minutes <n> Task execution timeout in minutes (default: 59)
1540
+ --parallel Enable parallel execution
1541
+ --distributed Enable distributed coordination
1542
+ --monitor Enable real-time monitoring
1543
+ --ui Launch terminal UI interface
1544
+ --background Run in background mode
1545
+ --review Enable peer review
1546
+ --testing Enable automated testing
1547
+ --encryption Enable encryption
1548
+ --verbose Enable detailed logging
1549
+ --dry-run Show configuration without executing
1550
+ --executor Use built-in executor instead of Claude Code
1551
+ --claude Open Claude Code CLI
1552
+ --output-format <format> Output format: json, text (default: text)
1553
+ --output-file <path> Save output to file instead of stdout
1554
+ --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)
1555
+ --auto (Deprecated: auto-permissions enabled by default)
1556
+ --no-auto-permissions Disable automatic --dangerously-skip-permissions
1557
+ --analysis Enable analysis/read-only mode (no code changes)
1558
+ --read-only Enable read-only mode (alias for --analysis)
1559
+
1560
+ ADVANCED OPTIONS:
1561
+ --quality-threshold <n> Quality threshold 0-1 (default: 0.8)
1562
+ --memory-namespace <name> Memory namespace (default: swarm)
1563
+ --agent-selection <type> Agent selection strategy
1564
+ --task-scheduling <type> Task scheduling algorithm
1565
+ --load-balancing <type> Load balancing method
1566
+ --fault-tolerance <type> Fault tolerance strategy
1567
+
1568
+ For complete documentation and examples:
1569
+ https://github.com/ruvnet/claude-code-flow/docs/swarm.md
1570
+ `);
1571
+ }
1572
+ }
1573
+
1574
+ // Function to create swarm files directly
1575
+ async function createSwarmFiles(objective, flags) {
1576
+ const fs = await import('fs');
1577
+ const path = await import('path');
1578
+
1579
+ const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;
1580
+
1581
+ console.log(`🐝 Swarm Execution Started: ${swarmId}`);
1582
+ console.log(`📋 Objective: ${objective}`);
1583
+ console.log(`🎯 Strategy: ${flags.strategy || 'auto'}`);
1584
+
1585
+ // Extract target directory from objective
1586
+ const targetMatch = objective.match(/in\s+([^\s]+)\/?$/i);
1587
+ let targetDir = targetMatch ? targetMatch[1] : 'output';
1588
+
1589
+ // Resolve relative paths
1590
+ if (!targetDir.startsWith('/')) {
1591
+ targetDir = path.join(process.cwd(), targetDir);
1592
+ }
1593
+
1594
+ console.log(`📁 Target directory: ${targetDir}`);
1595
+
1596
+ // Ensure target directory exists
1597
+ await fs.promises.mkdir(targetDir, { recursive: true });
1598
+
1599
+ // Determine what to build based on objective
1600
+ const isRestAPI =
1601
+ objective.toLowerCase().includes('rest api') || objective.toLowerCase().includes('api');
1602
+
1603
+ if (isRestAPI) {
1604
+ // Create REST API
1605
+ const apiDir = path.join(targetDir, 'rest-api');
1606
+ await fs.promises.mkdir(apiDir, { recursive: true });
1607
+
1608
+ console.log(`\n🏗️ Creating REST API...`);
1609
+ console.log(` 🤖 Agent developer-1: Creating server implementation`);
1610
+
1611
+ // Create server.js
1612
+ const serverCode = `const express = require('express');
1613
+ const app = express();
1614
+ const port = process.env.PORT || 3000;
1615
+
1616
+ // Middleware
1617
+ app.use(express.json());
1618
+ app.use(express.urlencoded({ extended: true }));
1619
+
1620
+ // Health check endpoint
1621
+ app.get('/health', (req, res) => {
1622
+ res.json({
1623
+ status: 'healthy',
1624
+ service: 'REST API',
1625
+ swarmId: '${swarmId}',
1626
+ created: new Date().toISOString()
1627
+ });
1628
+ });
1629
+
1630
+ // Sample endpoints
1631
+ app.get('/api/v1/items', (req, res) => {
1632
+ res.json({
1633
+ items: [
1634
+ { id: 1, name: 'Item 1', description: 'First item' },
1635
+ { id: 2, name: 'Item 2', description: 'Second item' }
1636
+ ],
1637
+ total: 2
1638
+ });
1639
+ });
1640
+
1641
+ app.get('/api/v1/items/:id', (req, res) => {
1642
+ const id = parseInt(req.params.id);
1643
+ res.json({
1644
+ id,
1645
+ name: \`Item \${id}\`,
1646
+ description: \`Description for item \${id}\`
1647
+ });
1648
+ });
1649
+
1650
+ app.post('/api/v1/items', (req, res) => {
1651
+ const newItem = {
1652
+ id: Date.now(),
1653
+ ...req.body,
1654
+ createdAt: new Date().toISOString()
1655
+ };
1656
+ res.status(201).json(newItem);
1657
+ });
1658
+
1659
+ // Start server
1660
+ app.listen(port, () => {
1661
+ console.log(\`REST API server running on port \${port}\`);
1662
+ console.log('Created by Claude Flow Swarm');
1663
+ });
1664
+
1665
+ module.exports = app;
1666
+ `;
1667
+
1668
+ await fs.promises.writeFile(path.join(apiDir, 'server.js'), serverCode);
1669
+ console.log(` ✅ Created: server.js`);
1670
+
1671
+ // Create package.json
1672
+ const packageJson = {
1673
+ name: 'rest-api',
1674
+ version: '1.0.0',
1675
+ description: 'REST API created by Claude Flow Swarm',
1676
+ main: 'server.js',
1677
+ scripts: {
1678
+ start: 'node server.js',
1679
+ dev: 'nodemon server.js',
1680
+ test: 'jest',
1681
+ },
1682
+ keywords: ['rest', 'api', 'swarm', 'claude-flow'],
1683
+ author: 'Claude Flow Swarm',
1684
+ license: 'MIT',
1685
+ dependencies: {
1686
+ express: '^4.18.2',
1687
+ },
1688
+ devDependencies: {
1689
+ nodemon: '^3.0.1',
1690
+ jest: '^29.7.0',
1691
+ supertest: '^6.3.3',
1692
+ },
1693
+ swarmMetadata: {
1694
+ swarmId,
1695
+ strategy: flags.strategy || 'development',
1696
+ created: new Date().toISOString(),
1697
+ },
1698
+ };
1699
+
1700
+ await fs.promises.writeFile(
1701
+ path.join(apiDir, 'package.json'),
1702
+ JSON.stringify(packageJson, null, 2),
1703
+ );
1704
+ console.log(` ✅ Created: package.json`);
1705
+
1706
+ // Create README
1707
+ const readme = `# REST API
1708
+
1709
+ This REST API was created by the Claude Flow Swarm system.
1710
+
1711
+ ## Swarm Details
1712
+ - Swarm ID: ${swarmId}
1713
+ - Strategy: ${flags.strategy || 'development'}
1714
+ - Generated: ${new Date().toISOString()}
1715
+
1716
+ ## Installation
1717
+
1718
+ \`\`\`bash
1719
+ npm install
1720
+ \`\`\`
1721
+
1722
+ ## Usage
1723
+
1724
+ Start the server:
1725
+ \`\`\`bash
1726
+ npm start
1727
+ \`\`\`
1728
+
1729
+ ## API Endpoints
1730
+
1731
+ - \`GET /health\` - Health check
1732
+ - \`GET /api/v1/items\` - Get all items
1733
+ - \`GET /api/v1/items/:id\` - Get item by ID
1734
+ - \`POST /api/v1/items\` - Create new item
1735
+
1736
+ ---
1737
+ Created by Claude Flow Swarm
1738
+ `;
1739
+
1740
+ await fs.promises.writeFile(path.join(apiDir, 'README.md'), readme);
1741
+ console.log(` ✅ Created: README.md`);
1742
+
1743
+ console.log(`\n✅ Swarm completed successfully!`);
1744
+ console.log(`📁 Files created in: ${apiDir}`);
1745
+ console.log(`🆔 Swarm ID: ${swarmId}`);
1746
+ } else {
1747
+ // Create generic application
1748
+ console.log(`\n🏗️ Creating application...`);
1749
+
1750
+ const appCode = `// Application created by Claude Flow Swarm
1751
+ // Objective: ${objective}
1752
+ // Swarm ID: ${swarmId}
1753
+
1754
+ function main() {
1755
+ console.log('Executing swarm objective: ${objective}');
1756
+ console.log('Implementation would be based on the specific requirements');
1757
+ }
1758
+
1759
+ main();
1760
+ `;
1761
+
1762
+ await fs.promises.writeFile(path.join(targetDir, 'app.js'), appCode);
1763
+ console.log(` ✅ Created: app.js`);
1764
+
1765
+ const packageJson = {
1766
+ name: 'swarm-app',
1767
+ version: '1.0.0',
1768
+ description: `Application created by Claude Flow Swarm: ${objective}`,
1769
+ main: 'app.js',
1770
+ scripts: {
1771
+ start: 'node app.js',
1772
+ },
1773
+ swarmMetadata: {
1774
+ swarmId,
1775
+ objective,
1776
+ created: new Date().toISOString(),
1777
+ },
1778
+ };
1779
+
1780
+ await fs.promises.writeFile(
1781
+ path.join(targetDir, 'package.json'),
1782
+ JSON.stringify(packageJson, null, 2),
1783
+ );
1784
+ console.log(` ✅ Created: package.json`);
1785
+
1786
+ console.log(`\n✅ Swarm completed successfully!`);
1787
+ console.log(`📁 Files created in: ${targetDir}`);
1788
+ console.log(`🆔 Swarm ID: ${swarmId}`);
1789
+ }
1790
+ }
1791
+
1792
+ /**
1793
+ * Get strategy-specific guidance for swarm execution
1794
+ */
1795
+ function getStrategyGuidance(strategy, objective) {
1796
+ const guidanceMap = {
1797
+ auto: `🤖 AUTO STRATEGY - INTELLIGENT TASK ANALYSIS:
1798
+ The swarm will analyze "${objective}" and automatically determine the best approach.
1799
+
1800
+ ANALYSIS APPROACH:
1801
+ 1. Task Decomposition: Break down the objective into subtasks
1802
+ 2. Skill Matching: Identify required capabilities and expertise
1803
+ 3. Agent Selection: Spawn appropriate agent types based on needs
1804
+ 4. Workflow Design: Create optimal execution flow
1805
+
1806
+ MCP TOOL PATTERN:
1807
+ - Start with memory_store to save the objective analysis
1808
+ - Use task_create to build a hierarchical task structure
1809
+ - Spawn agents with agent_spawn based on detected requirements
1810
+ - Monitor with swarm_monitor and adjust strategy as needed`,
1811
+
1812
+ research: `🔬 RESEARCH STRATEGY - INFORMATION GATHERING & ANALYSIS:
1813
+ Optimized for: "${objective}"
1814
+
1815
+ RESEARCH PHASES:
1816
+ 1. Discovery: Broad information gathering
1817
+ 2. Analysis: Deep dive into findings
1818
+ 3. Synthesis: Combine insights
1819
+ 4. Reporting: Document conclusions
1820
+
1821
+ RECOMMENDED AGENTS:
1822
+ - Lead Researcher: Coordinates research efforts
1823
+ - Data Analysts: Process and analyze findings
1824
+ - Subject Experts: Domain-specific investigation
1825
+ - Documentation Specialist: Compile reports
1826
+
1827
+ MCP TOOL USAGE:
1828
+ - memory_store: Save all research findings with structured keys
1829
+ - memory_search: Find related information across research
1830
+ - agent_communicate: Share discoveries between researchers
1831
+ - task_create: Break research into focused sub-investigations`,
1832
+
1833
+ development: `💻 DEVELOPMENT STRATEGY - SOFTWARE CREATION:
1834
+ Building: "${objective}"
1835
+
1836
+ DEVELOPMENT WORKFLOW:
1837
+ 1. Architecture: Design system structure
1838
+ 2. Implementation: Build components
1839
+ 3. Integration: Connect systems
1840
+ 4. Testing: Validate functionality
1841
+ 5. Documentation: Create guides
1842
+
1843
+ RECOMMENDED AGENTS:
1844
+ - System Architect: Overall design
1845
+ - Backend Developers: API/server implementation
1846
+ - Frontend Developers: UI/UX implementation
1847
+ - DevOps Engineer: Infrastructure setup
1848
+ - QA Engineers: Testing and validation
1849
+
1850
+ MCP TOOL USAGE:
1851
+ - memory_store: Save architecture decisions, code modules
1852
+ - task_create: Create implementation tasks with dependencies
1853
+ - agent_assign: Assign specific components to developers
1854
+ - swarm_monitor: Track build progress and blockers`,
1855
+
1856
+ analysis: `📊 ANALYSIS STRATEGY - DATA EXAMINATION:
1857
+ Analyzing: "${objective}"
1858
+
1859
+ ANALYSIS FRAMEWORK:
1860
+ 1. Data Collection: Gather relevant information
1861
+ 2. Processing: Clean and prepare data
1862
+ 3. Analysis: Apply analytical methods
1863
+ 4. Visualization: Create insights
1864
+ 5. Recommendations: Actionable outcomes
1865
+
1866
+ RECOMMENDED AGENTS:
1867
+ - Lead Analyst: Coordinate analysis efforts
1868
+ - Data Engineers: Prepare data pipelines
1869
+ - Statistical Analysts: Apply analytical methods
1870
+ - Visualization Experts: Create dashboards
1871
+ - Business Analysts: Translate to recommendations
1872
+
1873
+ MCP TOOL USAGE:
1874
+ - memory_store: Save datasets and analysis results
1875
+ - memory_retrieve: Access historical analysis
1876
+ - task_create: Define analysis pipelines
1877
+ - agent_coordinate: Sync analysis phases`,
1878
+
1879
+ testing: `🧪 TESTING STRATEGY - QUALITY ASSURANCE:
1880
+ Testing: "${objective}"
1881
+
1882
+ TESTING PHASES:
1883
+ 1. Test Planning: Define test scenarios
1884
+ 2. Test Development: Create test cases
1885
+ 3. Execution: Run test suites
1886
+ 4. Bug Tracking: Document issues
1887
+ 5. Regression: Ensure fixes work
1888
+
1889
+ RECOMMENDED AGENTS:
1890
+ - Test Lead: Coordinate testing efforts
1891
+ - Unit Testers: Component-level testing
1892
+ - Integration Testers: System-level testing
1893
+ - Performance Testers: Load and stress testing
1894
+ - Security Testers: Vulnerability assessment
1895
+
1896
+ MCP TOOL USAGE:
1897
+ - task_create: Create test cases and scenarios
1898
+ - memory_store: Save test results and bug reports
1899
+ - agent_communicate: Report bugs to developers
1900
+ - swarm_monitor: Track testing coverage and progress`,
1901
+
1902
+ optimization: `⚡ OPTIMIZATION STRATEGY - PERFORMANCE IMPROVEMENT:
1903
+ Optimizing: "${objective}"
1904
+
1905
+ OPTIMIZATION PROCESS:
1906
+ 1. Profiling: Identify bottlenecks
1907
+ 2. Analysis: Understand root causes
1908
+ 3. Implementation: Apply optimizations
1909
+ 4. Validation: Measure improvements
1910
+ 5. Documentation: Record changes
1911
+
1912
+ RECOMMENDED AGENTS:
1913
+ - Performance Lead: Coordinate optimization
1914
+ - System Profilers: Identify bottlenecks
1915
+ - Algorithm Experts: Optimize logic
1916
+ - Database Specialists: Query optimization
1917
+ - Infrastructure Engineers: System tuning
1918
+
1919
+ MCP TOOL USAGE:
1920
+ - memory_store: Save performance baselines and results
1921
+ - task_create: Create optimization tasks by priority
1922
+ - swarm_monitor: Track performance improvements
1923
+ - agent_communicate: Coordinate optimization efforts`,
1924
+
1925
+ maintenance: `🔧 MAINTENANCE STRATEGY - SYSTEM UPKEEP:
1926
+ Maintaining: "${objective}"
1927
+
1928
+ MAINTENANCE WORKFLOW:
1929
+ 1. Assessment: Evaluate current state
1930
+ 2. Planning: Prioritize updates
1931
+ 3. Implementation: Apply changes
1932
+ 4. Testing: Verify stability
1933
+ 5. Documentation: Update records
1934
+
1935
+ RECOMMENDED AGENTS:
1936
+ - Maintenance Lead: Coordinate efforts
1937
+ - System Administrators: Infrastructure updates
1938
+ - Security Engineers: Patch vulnerabilities
1939
+ - Database Administrators: Data maintenance
1940
+ - Documentation Writers: Update guides
1941
+
1942
+ MCP TOOL USAGE:
1943
+ - memory_retrieve: Access system history
1944
+ - task_create: Schedule maintenance tasks
1945
+ - agent_assign: Delegate specific updates
1946
+ - memory_store: Document all changes`,
1947
+ };
1948
+
1949
+ return guidanceMap[strategy] || guidanceMap['auto'];
1950
+ }
1951
+
1952
+ /**
1953
+ * Get mode-specific guidance for coordination
1954
+ */
1955
+ function getModeGuidance(mode) {
1956
+ const modeMap = {
1957
+ centralized: `🎯 CENTRALIZED MODE - SINGLE COORDINATOR:
1958
+ All decisions flow through one coordinator agent.
1959
+
1960
+ COORDINATION PATTERN:
1961
+ - Spawn a single COORDINATOR as the first agent
1962
+ - All other agents report to the coordinator
1963
+ - Coordinator assigns tasks and monitors progress
1964
+ - Use agent_assign for task delegation
1965
+ - Use swarm_monitor for oversight
1966
+
1967
+ BENEFITS:
1968
+ - Clear chain of command
1969
+ - Consistent decision making
1970
+ - Simple communication flow
1971
+ - Easy progress tracking
1972
+
1973
+ BEST FOR:
1974
+ - Small to medium projects
1975
+ - Well-defined objectives
1976
+ - Clear task dependencies`,
1977
+
1978
+ distributed: `🌐 DISTRIBUTED MODE - MULTIPLE COORDINATORS:
1979
+ Multiple coordinators share responsibility by domain.
1980
+
1981
+ COORDINATION PATTERN:
1982
+ - Spawn domain-specific coordinators (e.g., frontend-lead, backend-lead)
1983
+ - Each coordinator manages their domain agents
1984
+ - Use agent_coordinate for inter-coordinator sync
1985
+ - Use memory_sync to share state
1986
+ - Implement consensus protocols for decisions
1987
+
1988
+ BENEFITS:
1989
+ - Fault tolerance
1990
+ - Parallel decision making
1991
+ - Domain expertise
1992
+ - Scalability
1993
+
1994
+ BEST FOR:
1995
+ - Large projects
1996
+ - Multiple workstreams
1997
+ - Complex systems
1998
+ - High availability needs`,
1999
+
2000
+ hierarchical: `🏗️ HIERARCHICAL MODE - TREE STRUCTURE:
2001
+ Agents organized in management layers.
2002
+
2003
+ COORDINATION PATTERN:
2004
+ - Spawn top-level coordinator
2005
+ - Spawn team leads under coordinator
2006
+ - Spawn workers under team leads
2007
+ - Use parent parameter in agent_spawn
2008
+ - Tasks flow down, results flow up
2009
+
2010
+ BENEFITS:
2011
+ - Clear reporting structure
2012
+ - Efficient for large teams
2013
+ - Natural work breakdown
2014
+ - Manageable span of control
2015
+
2016
+ BEST FOR:
2017
+ - Enterprise projects
2018
+ - Multi-team efforts
2019
+ - Complex hierarchies
2020
+ - Phased deliveries`,
2021
+
2022
+ mesh: `🔗 MESH MODE - PEER-TO-PEER:
2023
+ Agents coordinate directly without central authority.
2024
+
2025
+ COORDINATION PATTERN:
2026
+ - All agents are peers
2027
+ - Use agent_communicate for direct messaging
2028
+ - Consensus through voting or protocols
2029
+ - Self-organizing teams
2030
+ - Emergent leadership
2031
+
2032
+ BENEFITS:
2033
+ - Maximum flexibility
2034
+ - Fast local decisions
2035
+ - Resilient to failures
2036
+ - Creative solutions
2037
+
2038
+ BEST FOR:
2039
+ - Research projects
2040
+ - Exploratory work
2041
+ - Innovation tasks
2042
+ - Small expert teams`,
2043
+
2044
+ hybrid: `🎨 HYBRID MODE - MIXED STRATEGIES:
2045
+ Combine different coordination patterns as needed.
2046
+
2047
+ COORDINATION PATTERN:
2048
+ - Start with one mode, adapt as needed
2049
+ - Mix hierarchical for structure with mesh for innovation
2050
+ - Use distributed for resilience with centralized for control
2051
+ - Dynamic reorganization based on task needs
2052
+
2053
+ BENEFITS:
2054
+ - Adaptability
2055
+ - Best of all modes
2056
+ - Task-appropriate structure
2057
+ - Evolution over time
2058
+
2059
+ BEST FOR:
2060
+ - Complex projects
2061
+ - Uncertain requirements
2062
+ - Long-term efforts
2063
+ - Diverse objectives`,
2064
+ };
2065
+
2066
+ return modeMap[mode] || modeMap['centralized'];
2067
+ }
2068
+
2069
+ /**
2070
+ * Get agent recommendations based on strategy
2071
+ */
2072
+ function getAgentRecommendations(strategy, maxAgents, objective) {
2073
+ const recommendations = {
2074
+ auto: `
2075
+ 🤖 RECOMMENDED AGENT COMPOSITION (Auto-detected):
2076
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2077
+
2078
+ \`\`\`
2079
+ [BatchTool - Single Message]:
2080
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "SwarmLead"}
2081
+ mcp__claude-flow__agent_spawn {"type": "researcher", "name": "RequirementsAnalyst"}
2082
+ mcp__claude-flow__agent_spawn {"type": "architect", "name": "SystemDesigner"}
2083
+ mcp__claude-flow__memory_store {"key": "swarm/objective", "value": "${objective}"}
2084
+ mcp__claude-flow__task_create {"name": "Analyze Requirements", "assignTo": "RequirementsAnalyst"}
2085
+ mcp__claude-flow__task_create {"name": "Design Architecture", "assignTo": "SystemDesigner", "dependsOn": ["Analyze Requirements"]}
2086
+ TodoWrite {"todos": [
2087
+ {"id": "1", "content": "Initialize swarm coordination", "status": "completed", "priority": "high"},
2088
+ {"id": "2", "content": "Analyze objective requirements", "status": "in_progress", "priority": "high"},
2089
+ {"id": "3", "content": "Design system architecture", "status": "pending", "priority": "high"},
2090
+ {"id": "4", "content": "Spawn additional agents as needed", "status": "pending", "priority": "medium"}
2091
+ ]}
2092
+ \`\`\``,
2093
+
2094
+ research: `
2095
+ 🔬 RECOMMENDED RESEARCH AGENTS:
2096
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2097
+
2098
+ \`\`\`
2099
+ [BatchTool - Single Message]:
2100
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "ResearchLead"}
2101
+ mcp__claude-flow__agent_spawn {"type": "researcher", "name": "PrimaryInvestigator"}
2102
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "DataScientist"}
2103
+ mcp__claude-flow__agent_spawn {"type": "researcher", "name": "LiteratureExpert"}
2104
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "InsightsCompiler"}
2105
+ mcp__claude-flow__memory_store {"key": "research/objective", "value": "${objective}"}
2106
+ mcp__claude-flow__task_create {"name": "Literature Review", "assignTo": "LiteratureExpert"}
2107
+ mcp__claude-flow__task_create {"name": "Primary Research", "assignTo": "PrimaryInvestigator"}
2108
+ mcp__claude-flow__task_create {"name": "Data Analysis", "assignTo": "DataScientist"}
2109
+ mcp__claude-flow__task_create {"name": "Compile Insights", "assignTo": "InsightsCompiler", "dependsOn": ["Literature Review", "Primary Research", "Data Analysis"]}
2110
+ TodoWrite {"todos": [
2111
+ {"id": "1", "content": "Initialize research swarm", "status": "completed", "priority": "high"},
2112
+ {"id": "2", "content": "Conduct literature review", "status": "in_progress", "priority": "high"},
2113
+ {"id": "3", "content": "Execute primary research", "status": "in_progress", "priority": "high"},
2114
+ {"id": "4", "content": "Analyze collected data", "status": "pending", "priority": "high"},
2115
+ {"id": "5", "content": "Compile and synthesize insights", "status": "pending", "priority": "medium"}
2116
+ ]}
2117
+ \`\`\``,
2118
+
2119
+ development: `
2120
+ 💻 RECOMMENDED DEVELOPMENT AGENTS:
2121
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2122
+
2123
+ \`\`\`
2124
+ [BatchTool - Single Message]:
2125
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "TechLead"}
2126
+ mcp__claude-flow__agent_spawn {"type": "architect", "name": "SystemArchitect"}
2127
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "BackendDev"}
2128
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "FrontendDev"}
2129
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "QAEngineer"}
2130
+ mcp__claude-flow__memory_store {"key": "dev/objective", "value": "${objective}"}
2131
+ mcp__claude-flow__task_create {"name": "System Architecture", "assignTo": "SystemArchitect"}
2132
+ mcp__claude-flow__task_create {"name": "Backend Implementation", "assignTo": "BackendDev", "dependsOn": ["System Architecture"]}
2133
+ mcp__claude-flow__task_create {"name": "Frontend Implementation", "assignTo": "FrontendDev", "dependsOn": ["System Architecture"]}
2134
+ mcp__claude-flow__task_create {"name": "Testing Suite", "assignTo": "QAEngineer", "dependsOn": ["Backend Implementation", "Frontend Implementation"]}
2135
+ TodoWrite {"todos": [
2136
+ {"id": "1", "content": "Initialize development swarm", "status": "completed", "priority": "high"},
2137
+ {"id": "2", "content": "Design system architecture", "status": "in_progress", "priority": "high"},
2138
+ {"id": "3", "content": "Implement backend services", "status": "pending", "priority": "high"},
2139
+ {"id": "4", "content": "Implement frontend UI", "status": "pending", "priority": "high"},
2140
+ {"id": "5", "content": "Create comprehensive tests", "status": "pending", "priority": "medium"}
2141
+ ]}
2142
+ \`\`\``,
2143
+
2144
+ analysis: `
2145
+ 📊 RECOMMENDED ANALYSIS AGENTS:
2146
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2147
+
2148
+ \`\`\`
2149
+ [BatchTool - Single Message]:
2150
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "AnalysisLead"}
2151
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "DataEngineer"}
2152
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "StatisticalExpert"}
2153
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "VisualizationDev"}
2154
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "BusinessAnalyst"}
2155
+ mcp__claude-flow__memory_store {"key": "analysis/objective", "value": "${objective}"}
2156
+ mcp__claude-flow__task_create {"name": "Data Pipeline Setup", "assignTo": "DataEngineer"}
2157
+ mcp__claude-flow__task_create {"name": "Statistical Analysis", "assignTo": "StatisticalExpert", "dependsOn": ["Data Pipeline Setup"]}
2158
+ mcp__claude-flow__task_create {"name": "Create Visualizations", "assignTo": "VisualizationDev", "dependsOn": ["Statistical Analysis"]}
2159
+ mcp__claude-flow__task_create {"name": "Business Insights", "assignTo": "BusinessAnalyst", "dependsOn": ["Statistical Analysis"]}
2160
+ TodoWrite {"todos": [
2161
+ {"id": "1", "content": "Initialize analysis swarm", "status": "completed", "priority": "high"},
2162
+ {"id": "2", "content": "Setup data pipelines", "status": "in_progress", "priority": "high"},
2163
+ {"id": "3", "content": "Perform statistical analysis", "status": "pending", "priority": "high"},
2164
+ {"id": "4", "content": "Create data visualizations", "status": "pending", "priority": "medium"},
2165
+ {"id": "5", "content": "Generate business insights", "status": "pending", "priority": "medium"}
2166
+ ]}
2167
+ \`\`\``,
2168
+
2169
+ testing: `
2170
+ 🧪 RECOMMENDED TESTING AGENTS:
2171
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2172
+
2173
+ \`\`\`
2174
+ [BatchTool - Single Message]:
2175
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "QALead"}
2176
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "UnitTestEngineer"}
2177
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "IntegrationTester"}
2178
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "PerformanceTester"}
2179
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "SecurityAuditor"}
2180
+ mcp__claude-flow__memory_store {"key": "testing/objective", "value": "${objective}"}
2181
+ mcp__claude-flow__task_create {"name": "Unit Test Suite", "assignTo": "UnitTestEngineer"}
2182
+ mcp__claude-flow__task_create {"name": "Integration Tests", "assignTo": "IntegrationTester"}
2183
+ mcp__claude-flow__task_create {"name": "Performance Tests", "assignTo": "PerformanceTester"}
2184
+ mcp__claude-flow__task_create {"name": "Security Audit", "assignTo": "SecurityAuditor"}
2185
+ TodoWrite {"todos": [
2186
+ {"id": "1", "content": "Initialize testing swarm", "status": "completed", "priority": "high"},
2187
+ {"id": "2", "content": "Create unit tests", "status": "in_progress", "priority": "high"},
2188
+ {"id": "3", "content": "Create integration tests", "status": "in_progress", "priority": "high"},
2189
+ {"id": "4", "content": "Run performance tests", "status": "pending", "priority": "medium"},
2190
+ {"id": "5", "content": "Execute security audit", "status": "pending", "priority": "high"}
2191
+ ]}
2192
+ \`\`\``,
2193
+
2194
+ optimization: `
2195
+ ⚡ RECOMMENDED OPTIMIZATION AGENTS:
2196
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2197
+
2198
+ \`\`\`
2199
+ [BatchTool - Single Message]:
2200
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "OptimizationLead"}
2201
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "PerformanceProfiler"}
2202
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "AlgorithmExpert"}
2203
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "DatabaseOptimizer"}
2204
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "SystemsTuner"}
2205
+ mcp__claude-flow__memory_store {"key": "optimization/objective", "value": "${objective}"}
2206
+ mcp__claude-flow__task_create {"name": "Performance Profiling", "assignTo": "PerformanceProfiler"}
2207
+ mcp__claude-flow__task_create {"name": "Algorithm Optimization", "assignTo": "AlgorithmExpert", "dependsOn": ["Performance Profiling"]}
2208
+ mcp__claude-flow__task_create {"name": "Database Optimization", "assignTo": "DatabaseOptimizer", "dependsOn": ["Performance Profiling"]}
2209
+ mcp__claude-flow__task_create {"name": "System Tuning", "assignTo": "SystemsTuner", "dependsOn": ["Performance Profiling"]}
2210
+ TodoWrite {"todos": [
2211
+ {"id": "1", "content": "Initialize optimization swarm", "status": "completed", "priority": "high"},
2212
+ {"id": "2", "content": "Profile system performance", "status": "in_progress", "priority": "high"},
2213
+ {"id": "3", "content": "Optimize algorithms", "status": "pending", "priority": "high"},
2214
+ {"id": "4", "content": "Optimize database queries", "status": "pending", "priority": "high"},
2215
+ {"id": "5", "content": "Tune system parameters", "status": "pending", "priority": "medium"}
2216
+ ]}
2217
+ \`\`\``,
2218
+
2219
+ maintenance: `
2220
+ 🔧 RECOMMENDED MAINTENANCE AGENTS:
2221
+ ⚡ SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:
2222
+
2223
+ \`\`\`
2224
+ [BatchTool - Single Message]:
2225
+ mcp__claude-flow__agent_spawn {"type": "coordinator", "name": "MaintenanceLead"}
2226
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "SystemAuditor"}
2227
+ mcp__claude-flow__agent_spawn {"type": "coder", "name": "PatchDeveloper"}
2228
+ mcp__claude-flow__agent_spawn {"type": "tester", "name": "RegressionTester"}
2229
+ mcp__claude-flow__agent_spawn {"type": "analyst", "name": "DocumentationUpdater"}
2230
+ mcp__claude-flow__memory_store {"key": "maintenance/objective", "value": "${objective}"}
2231
+ mcp__claude-flow__task_create {"name": "System Audit", "assignTo": "SystemAuditor"}
2232
+ mcp__claude-flow__task_create {"name": "Develop Patches", "assignTo": "PatchDeveloper", "dependsOn": ["System Audit"]}
2233
+ mcp__claude-flow__task_create {"name": "Regression Testing", "assignTo": "RegressionTester", "dependsOn": ["Develop Patches"]}
2234
+ mcp__claude-flow__task_create {"name": "Update Documentation", "assignTo": "DocumentationUpdater", "dependsOn": ["Develop Patches"]}
2235
+ TodoWrite {"todos": [
2236
+ {"id": "1", "content": "Initialize maintenance swarm", "status": "completed", "priority": "high"},
2237
+ {"id": "2", "content": "Audit system health", "status": "in_progress", "priority": "high"},
2238
+ {"id": "3", "content": "Develop necessary patches", "status": "pending", "priority": "high"},
2239
+ {"id": "4", "content": "Run regression tests", "status": "pending", "priority": "high"},
2240
+ {"id": "5", "content": "Update documentation", "status": "pending", "priority": "medium"}
2241
+ ]}
2242
+ \`\`\``,
2243
+ };
2244
+
2245
+ return recommendations[strategy] || recommendations['auto'];
2246
+ }
2247
+
2248
+ // Allow direct execution
2249
+ if (import.meta.main) {
2250
+ // When called directly as a script, parse all arguments
2251
+ const args = [];
2252
+ const flags = {};
2253
+
2254
+ // Parse arguments and flags
2255
+ for (let i = 0; i < args.length; i++) {
2256
+ const arg = args[i];
2257
+ if (arg.startsWith('--')) {
2258
+ const flagName = arg.substring(2);
2259
+ const nextArg = args[i + 1];
2260
+
2261
+ if (nextArg && !nextArg.startsWith('--')) {
2262
+ flags[flagName] = nextArg;
2263
+ i++; // Skip the next argument
2264
+ } else {
2265
+ flags[flagName] = true;
2266
+ }
2267
+ } else {
2268
+ args.push(arg);
2269
+ }
2270
+ }
2271
+
2272
+ // The objective is all non-flag arguments joined
2273
+ const objective = args.join(' ');
2274
+
2275
+ // Execute the swarm command
2276
+ await swarmCommand([objective], flags);
2277
+ }