claude-flow-novice 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -1,1271 +1,1084 @@
1
1
  // init/index.js - Initialize Claude Code integration files
2
- import { printSuccess, printError, printWarning, exit } from '../../utils.js';
3
- import { existsSync } from 'fs';
4
- import { promises as fs } from 'fs';
5
- import { fileURLToPath } from 'url';
6
- import { dirname, join } from 'path';
7
- import process from 'process';
8
- import { spawn, execSync } from 'child_process';
9
- import { promisify } from 'util';
10
-
2
+ import { printSuccess, printError, printWarning } from "../../utils.js";
3
+ import { existsSync } from "fs";
4
+ import { promises as fs } from "fs";
5
+ import { fileURLToPath } from "url";
6
+ import { dirname, join } from "path";
7
+ import process from "process";
8
+ import { spawn, execSync } from "child_process";
11
9
  // Helper to replace Deno.Command
12
10
  function runCommand(command, args, options = {}) {
13
- return new Promise((resolve, reject) => {
14
- const child = spawn(command, args, {
15
- cwd: options.cwd,
16
- env: { ...process.env, ...options.env },
17
- stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe',
18
- });
19
-
20
- let stdout = '';
21
- let stderr = '';
22
-
23
- if (options.stdout !== 'inherit') {
24
- child.stdout.on('data', (data) => {
25
- stdout += data;
26
- });
27
- child.stderr.on('data', (data) => {
28
- stderr += data;
29
- });
30
- }
31
-
32
- child.on('close', (code) => {
33
- if (code === 0) {
34
- resolve({ success: true, code, stdout, stderr });
35
- } else {
36
- reject(new Error(`Command failed with exit code ${code}`));
37
- }
11
+ return new Promise((resolve, reject)=>{
12
+ const child = spawn(command, args, {
13
+ cwd: options.cwd,
14
+ env: {
15
+ ...process.env,
16
+ ...options.env
17
+ },
18
+ stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe'
19
+ });
20
+ let stdout = '';
21
+ let stderr = '';
22
+ if (options.stdout !== 'inherit') {
23
+ child.stdout.on('data', (data)=>{
24
+ stdout += data;
25
+ });
26
+ child.stderr.on('data', (data)=>{
27
+ stderr += data;
28
+ });
29
+ }
30
+ child.on('close', (code)=>{
31
+ if (code === 0) {
32
+ resolve({
33
+ success: true,
34
+ code,
35
+ stdout,
36
+ stderr
37
+ });
38
+ } else {
39
+ reject(new Error(`Command failed with exit code ${code}`));
40
+ }
41
+ });
42
+ child.on('error', reject);
38
43
  });
39
-
40
- child.on('error', reject);
41
- });
42
44
  }
43
- import { createLocalExecutable } from './executable-wrapper.js';
44
- import { createSparcStructureManually } from './sparc-structure.js';
45
- import { createClaudeSlashCommands } from './claude-commands/slash-commands.js';
46
- import { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';
47
- import { copyTemplates } from './template-copier.js';
48
- import { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';
49
- import {
50
- copyAgentFiles,
51
- createAgentDirectories,
52
- validateAgentSystem,
53
- copyCommandFiles,
54
- } from './agent-copier.js';
55
- import { showInitHelp } from './help.js';
56
- import { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';
57
- import { ValidationSystem, runFullValidation } from './validation/index.js';
58
- import { RollbackSystem, createAtomicOperation } from './rollback/index.js';
59
- import {
60
- createEnhancedClaudeMd,
61
- createEnhancedSettingsJson,
62
- createWrapperScript,
63
- createCommandDoc,
64
- createHelperScript,
65
- COMMAND_STRUCTURE,
66
- } from './templates/enhanced-templates.js';
67
- import { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';
68
- import { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';
69
- import {
70
- createVerificationClaudeMd,
71
- createVerificationSettingsJson,
72
- } from './templates/verification-claude-md.js';
73
- import { createFullMemoryBankMd, createMinimalMemoryBankMd } from './templates/memory-bank-md.js';
74
- import {
75
- createFullCoordinationMd,
76
- createMinimalCoordinationMd,
77
- } from './templates/coordination-md.js';
78
- import { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';
79
- import { initializeHiveMind, getHiveMindStatus, rollbackHiveMindInit } from './hive-mind-init.js';
80
-
45
+ import { createLocalExecutable } from "./executable-wrapper.js";
46
+ import { createSparcStructureManually } from "./sparc-structure.js";
47
+ import { createClaudeSlashCommands } from "./claude-commands/slash-commands.js";
48
+ import { createOptimizedClaudeSlashCommands } from "./claude-commands/optimized-slash-commands.js";
49
+ import { copyTemplates } from "./template-copier.js";
50
+ import { copyRevisedTemplates, validateTemplatesExist } from "./copy-revised-templates.js";
51
+ import { copyAgentFiles, createAgentDirectories, validateAgentSystem, copyCommandFiles } from "./agent-copier.js";
52
+ import { showInitHelp } from "./help.js";
53
+ import { batchInitCommand, batchInitFromConfig, validateBatchOptions } from "./batch-init.js";
54
+ import { ValidationSystem, runFullValidation } from "./validation/index.js";
55
+ import { RollbackSystem, createAtomicOperation } from "./rollback/index.js";
56
+ import { createEnhancedSettingsJson, createWrapperScript, createCommandDoc, createHelperScript, COMMAND_STRUCTURE } from "./templates/enhanced-templates.js";
57
+ import { getIsolatedNpxEnv } from "../../../utils/npx-isolated-cache.js";
58
+ import { updateGitignore } from "./gitignore-updater.js";
59
+ import { createFullMemoryBankMd, createMinimalMemoryBankMd } from "./templates/memory-bank-md.js";
60
+ import { createFullCoordinationMd, createMinimalCoordinationMd } from "./templates/coordination-md.js";
61
+ import { createAgentsReadme, createSessionsReadme } from "./templates/readme-files.js";
62
+ import { initializeHiveMind, getHiveMindStatus, rollbackHiveMindInit } from "./hive-mind-init.js";
81
63
  // Get the directory path of this module for resolving template files
82
64
  const __filename = fileURLToPath(import.meta.url);
83
65
  const __dirname = dirname(__filename);
84
-
85
66
  /**
86
67
  * Read the CLAUDE.md template file
87
68
  * @returns {Promise<string>} The template content
88
- */
89
- async function readClaudeMdTemplate() {
90
- // In source: templates/CLAUDE.md
91
- // In dist: the files are copied directly to init/ directory (not templates/)
92
- const possiblePaths = [
93
- join(__dirname, 'templates', 'CLAUDE.md'), // Source location
94
- join(__dirname, 'CLAUDE.md'), // Dist location (files copied directly)
95
- ];
96
-
97
- for (const templatePath of possiblePaths) {
98
- try {
99
- const content = await fs.readFile(templatePath, 'utf8');
100
- console.log(`✅ Using CLAUDE.md template from: ${templatePath}`);
101
- return content;
102
- } catch (error) {
103
- // Try next path
104
- continue;
69
+ */ async function readClaudeMdTemplate() {
70
+ // In source: templates/CLAUDE.md
71
+ // In dist: the files are copied directly to init/ directory (not templates/)
72
+ const possiblePaths = [
73
+ join(__dirname, 'templates', 'CLAUDE.md'),
74
+ join(__dirname, 'CLAUDE.md')
75
+ ];
76
+ for (const templatePath of possiblePaths){
77
+ try {
78
+ const content = await fs.readFile(templatePath, 'utf8');
79
+ console.log(`✅ Using CLAUDE.md template from: ${templatePath}`);
80
+ return content;
81
+ } catch (error) {
82
+ continue;
83
+ }
105
84
  }
106
- }
107
-
108
- // If template not found, throw error instead of falling back
109
- throw new Error('CLAUDE.md template file not found! Please ensure templates are included in the build.');
85
+ // If template not found, throw error instead of falling back
86
+ throw new Error('CLAUDE.md template file not found! Please ensure templates are included in the build.');
110
87
  }
111
-
112
88
  /**
113
89
  * Check if Claude Code CLI is installed
114
- */
115
- function isClaudeCodeInstalled() {
116
- try {
117
- execSync('which claude', { stdio: 'ignore' });
118
- return true;
119
- } catch {
120
- return false;
121
- }
90
+ */ function isClaudeCodeInstalled() {
91
+ try {
92
+ execSync('which claude', {
93
+ stdio: 'ignore'
94
+ });
95
+ return true;
96
+ } catch {
97
+ return false;
98
+ }
122
99
  }
123
-
124
100
  /**
125
101
  * Set up MCP servers in Claude Code (Legacy - replaced by bulletproof system)
126
- */
127
- async function setupMcpServers(dryRun = false) {
128
- console.log('\n🔌 Setting up MCP servers for Claude Code...');
129
-
130
- const servers = [
131
- {
132
- name: 'claude-flow-novice',
133
- command: 'node dist/mcp/mcp-server-sdk.js',
134
- description: 'Claude Flow Novice MCP server with 30 essential tools',
135
- },
136
- ];
137
-
138
- for (const server of servers) {
139
- try {
140
- if (!dryRun) {
141
- console.log(` 🔄 Adding ${server.name}...`);
142
- execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });
143
- console.log(` ✅ Added ${server.name} - ${server.description}`);
144
- } else {
145
- console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);
146
- }
147
- } catch (err) {
148
- console.log(` ⚠️ Failed to add ${server.name}: ${err.message}`);
149
- console.log(
150
- ` You can add it manually with: claude mcp add ${server.name} ${server.command}`,
151
- );
102
+ */ async function setupMcpServers(dryRun1 = false) {
103
+ console.log('\n🔌 Setting up MCP servers for Claude Code...');
104
+ const servers = [
105
+ {
106
+ name: 'claude-flow-novice',
107
+ command: 'node dist/mcp/mcp-server-sdk.js',
108
+ description: 'Claude Flow Novice MCP server with 30 essential tools'
109
+ }
110
+ ];
111
+ for (const server of servers){
112
+ try {
113
+ if (!dryRun1) {
114
+ console.log(` 🔄 Adding ${server.name}...`);
115
+ execSync(`claude mcp add ${server.name} ${server.command}`, {
116
+ stdio: 'inherit'
117
+ });
118
+ console.log(` Added ${server.name} - ${server.description}`);
119
+ } else {
120
+ console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);
121
+ }
122
+ } catch (err) {
123
+ console.log(` ⚠️ Failed to add ${server.name}: ${err.message}`);
124
+ console.log(` You can add it manually with: claude mcp add ${server.name} ${server.command}`);
125
+ }
152
126
  }
153
- }
154
-
155
- if (!dryRun) {
156
- console.log('\n 📋 Verifying MCP servers...');
157
- try {
158
- execSync('claude mcp list', { stdio: 'inherit' });
159
- } catch (err) {
160
- console.log(' ⚠️ Could not verify MCP servers');
127
+ if (!dryRun1) {
128
+ console.log('\n 📋 Verifying MCP servers...');
129
+ try {
130
+ execSync('claude mcp list', {
131
+ stdio: 'inherit'
132
+ });
133
+ } catch (err) {
134
+ console.log(' ⚠️ Could not verify MCP servers');
135
+ }
161
136
  }
162
- }
163
137
  }
164
-
165
138
  /**
166
139
  * Bulletproof MCP setup using the new configuration manager
167
- */
168
- async function setupBulletproofMcp(options = {}) {
169
- console.log('\n🛡️ Setting up bulletproof MCP configuration...');
170
-
171
- try {
172
- // Import the MCP configuration manager
173
- const { enhancedMcpInit } = await import('../../mcp/mcp-config-manager.js');
174
-
175
- const result = await enhancedMcpInit({
176
- verbose: options.verbose || false,
177
- autoFix: options.autoFix !== false, // Default to true
178
- dryRun: options.dryRun || false,
179
- enhancedUx: true, // Enable enhanced user experience
180
- showEducation: options.showEducation || false // Show educational content for first-time users
181
- });
182
-
183
- if (result.success) {
184
- console.log('✅ Bulletproof MCP configuration completed successfully');
185
-
186
- // Display additional success information
187
- if (result.details) {
188
- console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
189
- console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
190
- console.log(` • Duration: ${result.duration || 'N/A'}ms`);
191
- }
192
-
193
- return true;
194
- } else {
195
- console.log(`⚠️ MCP configuration had issues: ${result.error}`);
196
-
197
- // Display recovery information if available
198
- if (result.rollbackAvailable) {
199
- console.log(' 🔄 Automatic rollback was performed');
200
- }
201
-
202
- if (result.recovery && result.recovery.recommendedActions) {
203
- console.log('\n 🛠️ Recommended actions:');
204
- result.recovery.recommendedActions.slice(0, 3).forEach((action, i) => {
205
- console.log(` ${i + 1}. ${action}`);
140
+ */ async function setupBulletproofMcp(options = {}) {
141
+ console.log('\n🛡️ Setting up bulletproof MCP configuration...');
142
+ try {
143
+ // Import the MCP configuration manager
144
+ const { enhancedMcpInit } = await import("../../mcp/mcp-config-manager.js");
145
+ const result = await enhancedMcpInit({
146
+ verbose: options.verbose || false,
147
+ autoFix: options.autoFix !== false,
148
+ dryRun: options.dryRun || false,
149
+ enhancedUx: true,
150
+ showEducation: options.showEducation || false // Show educational content for first-time users
206
151
  });
207
- }
208
-
209
- return false;
210
- }
211
- } catch (error) {
212
- console.log(`⚠️ Bulletproof MCP setup failed: ${error.message}`);
213
- console.log(' This may be due to missing dependencies or system configuration.');
214
-
215
- // Check if it's a dependency issue
216
- if (error.message.includes('Cannot find module') || error.message.includes('import')) {
217
- console.log(' 💡 Try installing dependencies: npm install');
152
+ if (result.success) {
153
+ console.log('✅ Bulletproof MCP configuration completed successfully');
154
+ // Display additional success information
155
+ if (result.details) {
156
+ console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
157
+ console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
158
+ console.log(` • Duration: ${result.duration || 'N/A'}ms`);
159
+ }
160
+ return true;
161
+ } else {
162
+ console.log(`⚠️ MCP configuration had issues: ${result.error}`);
163
+ // Display recovery information if available
164
+ if (result.rollbackAvailable) {
165
+ console.log(' 🔄 Automatic rollback was performed');
166
+ }
167
+ if (result.recovery && result.recovery.recommendedActions) {
168
+ console.log('\n 🛠️ Recommended actions:');
169
+ result.recovery.recommendedActions.slice(0, 3).forEach((action, i)=>{
170
+ console.log(` ${i + 1}. ${action}`);
171
+ });
172
+ }
173
+ return false;
174
+ }
175
+ } catch (error) {
176
+ console.log(`⚠️ Bulletproof MCP setup failed: ${error.message}`);
177
+ console.log(' This may be due to missing dependencies or system configuration.');
178
+ // Check if it's a dependency issue
179
+ if (error.message.includes('Cannot find module') || error.message.includes('import')) {
180
+ console.log(' 💡 Try installing dependencies: npm install');
181
+ }
182
+ console.log(' 📞 Falling back to legacy MCP setup...');
183
+ // Fallback to legacy setup
184
+ await setupMcpServers(options.dryRun);
185
+ return false;
218
186
  }
219
-
220
- console.log(' 📞 Falling back to legacy MCP setup...');
221
-
222
- // Fallback to legacy setup
223
- await setupMcpServers(options.dryRun);
224
- return false;
225
- }
226
187
  }
227
-
228
188
  export async function initCommand(subArgs, flags) {
229
- // Show help if requested
230
- if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {
231
- showInitHelp();
232
- return;
233
- }
234
-
235
- // Check for verification flags first
236
- const hasVerificationFlags =
237
- subArgs.includes('--verify') || subArgs.includes('--pair') || flags.verify || flags.pair;
238
-
239
- // Flow-nexus mode removed
240
-
241
- // Default to enhanced Claude Flow v2 init unless other modes are specified
242
- // Use --basic flag for old behavior, or verification flags for verification mode
243
- if (!flags.basic && !flags.minimal && !flags.sparc && !hasVerificationFlags) {
244
- return await enhancedClaudeFlowInit(flags, subArgs);
245
- }
246
-
247
- // Check for validation and rollback commands
248
- if (subArgs.includes('--validate') || subArgs.includes('--validate-only')) {
249
- return handleValidationCommand(subArgs, flags);
250
- }
251
-
252
- if (subArgs.includes('--rollback')) {
253
- return handleRollbackCommand(subArgs, flags);
254
- }
255
-
256
- if (subArgs.includes('--list-backups')) {
257
- return handleListBackups(subArgs, flags);
258
- }
259
-
260
- // Check for batch operations
261
- const batchInitFlag = flags['batch-init'] || subArgs.includes('--batch-init');
262
- const configFlag = flags.config || subArgs.includes('--config');
263
-
264
- if (batchInitFlag || configFlag) {
265
- return handleBatchInit(subArgs, flags);
266
- }
267
-
268
- // Parse init options
269
- const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;
270
- const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;
271
- const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag
272
- const initDryRun = subArgs.includes('--dry-run') || subArgs.includes('-d') || flags.dryRun;
273
- const initOptimized = initSparc && initForce; // Use optimized templates when both flags are present
274
- const selectedModes = flags.modes ? flags.modes.split(',') : null; // Support selective mode initialization
275
-
276
- // Check for verification and pair programming flags
277
- const initVerify = subArgs.includes('--verify') || flags.verify;
278
- const initPair = subArgs.includes('--pair') || flags.pair;
279
-
280
- // Get the actual working directory (where the command was run from)
281
- // Use PWD environment variable which preserves the original directory
282
- const workingDir = process.env.PWD || cwd();
283
- console.log(`📁 Initializing in: ${workingDir}`);
284
-
285
- // Change to the working directory to ensure all file operations happen there
286
- try {
287
- process.chdir(workingDir);
288
- } catch (err) {
289
- printWarning(`Could not change to directory ${workingDir}: ${err.message}`);
290
- }
291
-
292
- try {
293
- printSuccess('Initializing Claude Code integration files...');
294
-
295
- // Check if files already exist in the working directory
296
- const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];
297
- const existingFiles = [];
298
-
299
- for (const file of files) {
300
- try {
301
- await fs.stat(`${workingDir}/${file}`);
302
- existingFiles.push(file);
303
- } catch {
304
- // File doesn't exist, which is what we want
305
- }
189
+ // Show help if requested
190
+ if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {
191
+ showInitHelp();
192
+ return;
306
193
  }
307
-
308
- if (existingFiles.length > 0 && !initForce) {
309
- printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
310
- console.log('Use --force to overwrite existing files');
311
- return;
194
+ // Check for verification flags first
195
+ const hasVerificationFlags = subArgs.includes('--verify') || subArgs.includes('--pair') || flags.verify || flags.pair;
196
+ // Flow-nexus mode removed
197
+ // Default to enhanced Claude Flow v2 init unless other modes are specified
198
+ // Use --basic flag for old behavior, or verification flags for verification mode
199
+ if (!flags.basic && !flags.minimal && !flags.sparc && !hasVerificationFlags) {
200
+ return await enhancedClaudeFlowInit(flags, subArgs);
312
201
  }
313
-
314
- // Use template copier to copy all template files
315
- const templateOptions = {
316
- sparc: initSparc,
317
- minimal: initMinimal,
318
- optimized: initOptimized,
319
- dryRun: initDryRun,
320
- force: initForce,
321
- selectedModes: selectedModes,
322
- verify: initVerify,
323
- pair: initPair,
324
- };
325
-
326
- // If verification flags are set, always use generated templates for CLAUDE.md and settings.json
327
- if (initVerify || initPair) {
328
- console.log(' 📁 Creating verification-focused configuration...');
329
-
330
- // Create verification CLAUDE.md
331
- if (!initDryRun) {
332
- const { createVerificationClaudeMd, createVerificationSettingsJson } = await import(
333
- './templates/verification-claude-md.js'
334
- );
335
- await fs.writeFile(`${workingDir}/CLAUDE.md`, createVerificationClaudeMd(), 'utf8');
336
-
337
- // Create .claude directory and settings
338
- await fs.mkdir(`${workingDir}/.claude`, { recursive: true });
339
- await fs.writeFile(
340
- `${workingDir}/.claude/settings.json`,
341
- createVerificationSettingsJson(),
342
- 'utf8',
343
- );
344
- console.log(' ✅ Created verification-focused CLAUDE.md and settings.json');
345
- } else {
346
- console.log(' [DRY RUN] Would create verification-focused CLAUDE.md and settings.json');
347
- }
348
-
349
- // Copy other template files from repository if available
350
- const validation = validateTemplatesExist();
351
- if (validation.valid) {
352
- const revisedResults = await copyRevisedTemplates(workingDir, {
353
- force: initForce,
354
- dryRun: initDryRun,
355
- verbose: false,
356
- sparc: initSparc,
357
- });
358
- }
359
-
360
- // Also create standard memory and coordination files
361
- const copyResults = await copyTemplates(workingDir, {
362
- ...templateOptions,
363
- skipClaudeMd: true, // Don't overwrite the verification CLAUDE.md
364
- skipSettings: true, // Don't overwrite the verification settings.json
365
- });
366
- } else {
367
- // Standard template copying logic
368
- const validation = validateTemplatesExist();
369
- if (validation.valid) {
370
- console.log(' 📁 Copying revised template files...');
371
- const revisedResults = await copyRevisedTemplates(workingDir, {
372
- force: initForce,
373
- dryRun: initDryRun,
374
- verbose: true,
375
- sparc: initSparc,
376
- });
377
-
378
- if (revisedResults.success) {
379
- console.log(` ✅ Copied ${revisedResults.copiedFiles.length} template files`);
380
- if (revisedResults.skippedFiles.length > 0) {
381
- console.log(` ⏭️ Skipped ${revisedResults.skippedFiles.length} existing files`);
382
- }
383
- } else {
384
- console.log(' ⚠️ Some template files could not be copied:');
385
- revisedResults.errors.forEach((err) => console.log(` - ${err}`));
386
- }
387
- } else {
388
- // Fall back to generated templates
389
- console.log(' ⚠️ Revised templates not available, using generated templates');
390
- const copyResults = await copyTemplates(workingDir, templateOptions);
391
-
392
- if (!copyResults.success) {
393
- printError('Failed to copy templates:');
394
- copyResults.errors.forEach((err) => console.log(` ❌ ${err}`));
395
- return;
396
- }
397
- }
202
+ // Check for validation and rollback commands
203
+ if (subArgs.includes('--validate') || subArgs.includes('--validate-only')) {
204
+ return handleValidationCommand(subArgs, flags);
398
205
  }
399
-
400
- // Agent setup moved to end of function where execution is guaranteed
401
-
402
- // Directory structure is created by template copier
403
-
404
- // SPARC files are created by template copier when --sparc flag is used
405
-
406
- // Memory README files and persistence database are created by template copier
407
-
408
- // Create local claude-flow-novice executable wrapper
409
- if (!initDryRun) {
410
- await createLocalExecutable(workingDir);
411
- } else {
412
- console.log(' [DRY RUN] Would create local claude-flow-novice executable wrapper');
206
+ if (subArgs.includes('--rollback')) {
207
+ return handleRollbackCommand(subArgs, flags);
413
208
  }
414
-
415
- // SPARC initialization
416
- if (initSparc) {
417
- console.log('\n🚀 Initializing SPARC development environment...');
418
-
419
- if (initDryRun) {
420
- console.log(' [DRY RUN] Would run: npx -y create-sparc init --force');
421
- console.log(' [DRY RUN] Would create SPARC environment with all modes');
422
- console.log(
423
- ' [DRY RUN] Would create Claude slash commands' +
424
- (initOptimized ? ' (Batchtools-optimized)' : ''),
425
- );
426
- if (selectedModes) {
427
- console.log(
428
- ` [DRY RUN] Would create commands for selected modes: ${selectedModes.join(', ')}`,
429
- );
209
+ if (subArgs.includes('--list-backups')) {
210
+ return handleListBackups(subArgs, flags);
211
+ }
212
+ // Check for batch operations
213
+ const batchInitFlag = flags['batch-init'] || subArgs.includes('--batch-init');
214
+ const configFlag = flags.config || subArgs.includes('--config');
215
+ if (batchInitFlag || configFlag) {
216
+ return handleBatchInit(subArgs, flags);
217
+ }
218
+ // Parse init options
219
+ const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;
220
+ const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;
221
+ const initSparc = flags.roo || subArgs && subArgs.includes('--roo'); // SPARC only with --roo flag
222
+ const initDryRun = subArgs.includes('--dry-run') || subArgs.includes('-d') || flags.dryRun;
223
+ const initOptimized = initSparc && initForce; // Use optimized templates when both flags are present
224
+ const selectedModes = flags.modes ? flags.modes.split(',') : null; // Support selective mode initialization
225
+ // Check for verification and pair programming flags
226
+ const initVerify = subArgs.includes('--verify') || flags.verify;
227
+ const initPair = subArgs.includes('--pair') || flags.pair;
228
+ // Get the actual working directory (where the command was run from)
229
+ // Use PWD environment variable which preserves the original directory
230
+ const workingDir = process.env.PWD || cwd();
231
+ console.log(`📁 Initializing in: ${workingDir}`);
232
+ // Change to the working directory to ensure all file operations happen there
233
+ try {
234
+ process.chdir(workingDir);
235
+ } catch (err) {
236
+ printWarning(`Could not change to directory ${workingDir}: ${err.message}`);
237
+ }
238
+ try {
239
+ printSuccess('Initializing Claude Code integration files...');
240
+ // Check if files already exist in the working directory
241
+ const files = [
242
+ 'CLAUDE.md',
243
+ 'memory-bank.md',
244
+ 'coordination.md'
245
+ ];
246
+ const existingFiles = [];
247
+ for (const file of files){
248
+ try {
249
+ await fs.stat(`${workingDir}/${file}`);
250
+ existingFiles.push(file);
251
+ } catch {
252
+ // File doesn't exist, which is what we want
253
+ }
430
254
  }
431
- } else {
432
- // Check if create-sparc exists and run it
433
- let sparcInitialized = false;
434
- try {
435
- // Use isolated NPX cache to prevent concurrent conflicts
436
- console.log(' 🔄 Running: npx -y create-sparc init --force');
437
- const createSparcResult = await runCommand(
438
- 'npx',
439
- ['-y', 'create-sparc', 'init', '--force'],
440
- {
441
- cwd: workingDir,
442
- stdout: 'inherit',
443
- stderr: 'inherit',
444
- env: getIsolatedNpxEnv({
445
- PWD: workingDir,
446
- }),
447
- },
448
- );
449
-
450
- if (createSparcResult.success) {
451
- console.log(' ✅ SPARC environment initialized successfully');
452
- sparcInitialized = true;
453
- } else {
454
- printWarning('create-sparc failed, creating basic SPARC structure manually...');
455
-
456
- // Fallback: create basic SPARC structure manually
457
- await createSparcStructureManually();
458
- sparcInitialized = true; // Manual creation still counts as initialized
459
- }
460
- } catch (err) {
461
- printWarning('create-sparc not available, creating basic SPARC structure manually...');
462
-
463
- // Fallback: create basic SPARC structure manually
464
- await createSparcStructureManually();
465
- sparcInitialized = true; // Manual creation still counts as initialized
255
+ if (existingFiles.length > 0 && !initForce) {
256
+ printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
257
+ console.log('Use --force to overwrite existing files');
258
+ return;
466
259
  }
467
-
468
- // Always create Claude slash commands after SPARC initialization
469
- if (sparcInitialized) {
470
- try {
471
- if (initOptimized) {
472
- await createOptimizedClaudeSlashCommands(workingDir, selectedModes);
260
+ // Use template copier to copy all template files
261
+ const templateOptions = {
262
+ sparc: initSparc,
263
+ minimal: initMinimal,
264
+ optimized: initOptimized,
265
+ dryRun: initDryRun,
266
+ force: initForce,
267
+ selectedModes: selectedModes,
268
+ verify: initVerify,
269
+ pair: initPair
270
+ };
271
+ // If verification flags are set, always use generated templates for CLAUDE.md and settings.json
272
+ if (initVerify || initPair) {
273
+ console.log(' 📁 Creating verification-focused configuration...');
274
+ // Create verification CLAUDE.md
275
+ if (!initDryRun) {
276
+ const { createVerificationClaudeMd, createVerificationSettingsJson } = await import("./templates/verification-claude-md.js");
277
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, createVerificationClaudeMd(), 'utf8');
278
+ // Create .claude directory and settings
279
+ await fs.mkdir(`${workingDir}/.claude`, {
280
+ recursive: true
281
+ });
282
+ await fs.writeFile(`${workingDir}/.claude/settings.json`, createVerificationSettingsJson(), 'utf8');
283
+ console.log(' ✅ Created verification-focused CLAUDE.md and settings.json');
473
284
  } else {
474
- await createClaudeSlashCommands(workingDir);
285
+ console.log(' [DRY RUN] Would create verification-focused CLAUDE.md and settings.json');
286
+ }
287
+ // Copy other template files from repository if available
288
+ const validation = validateTemplatesExist();
289
+ if (validation.valid) {
290
+ const revisedResults = await copyRevisedTemplates(workingDir, {
291
+ force: initForce,
292
+ dryRun: initDryRun,
293
+ verbose: false,
294
+ sparc: initSparc
295
+ });
296
+ }
297
+ // Also create standard memory and coordination files
298
+ const copyResults = await copyTemplates(workingDir, {
299
+ ...templateOptions,
300
+ skipClaudeMd: true,
301
+ skipSettings: true
302
+ });
303
+ } else {
304
+ // Standard template copying logic
305
+ const validation = validateTemplatesExist();
306
+ if (validation.valid) {
307
+ console.log(' 📁 Copying revised template files...');
308
+ const revisedResults = await copyRevisedTemplates(workingDir, {
309
+ force: initForce,
310
+ dryRun: initDryRun,
311
+ verbose: true,
312
+ sparc: initSparc
313
+ });
314
+ if (revisedResults.success) {
315
+ console.log(` ✅ Copied ${revisedResults.copiedFiles.length} template files`);
316
+ if (revisedResults.skippedFiles.length > 0) {
317
+ console.log(` ⏭️ Skipped ${revisedResults.skippedFiles.length} existing files`);
318
+ }
319
+ } else {
320
+ console.log(' ⚠️ Some template files could not be copied:');
321
+ revisedResults.errors.forEach((err)=>console.log(` - ${err}`));
322
+ }
323
+ } else {
324
+ // Fall back to generated templates
325
+ console.log(' ⚠️ Revised templates not available, using generated templates');
326
+ const copyResults = await copyTemplates(workingDir, templateOptions);
327
+ if (!copyResults.success) {
328
+ printError('Failed to copy templates:');
329
+ copyResults.errors.forEach((err)=>console.log(` ❌ ${err}`));
330
+ return;
331
+ }
475
332
  }
476
- } catch (err) {
477
- // Legacy slash command creation - silently skip if it fails
478
- // SPARC slash commands are already created successfully above
479
- }
480
- }
481
- }
482
- }
483
-
484
- if (initDryRun) {
485
- printSuccess("🔍 Dry run completed! Here's what would be created:");
486
- console.log('\n📋 Summary of planned initialization:');
487
- console.log(
488
- ` • Configuration: ${initOptimized ? 'Batchtools-optimized SPARC' : initSparc ? 'SPARC-enhanced' : 'Standard'}`,
489
- );
490
- console.log(
491
- ` • Template type: ${initOptimized ? 'Optimized for parallel processing' : 'Standard'}`,
492
- );
493
- console.log(' • Core files: CLAUDE.md, memory-bank.md, coordination.md');
494
- console.log(' • Directory structure: memory/, coordination/, .claude/');
495
- console.log(' • Local executable: ./claude-flow');
496
- if (initSparc) {
497
- console.log(
498
- ` • Claude Code slash commands: ${selectedModes ? selectedModes.length : 'All'} SPARC mode commands`,
499
- );
500
- console.log(' • SPARC environment with all development modes');
501
- }
502
- if (initOptimized) {
503
- console.log(' • Batchtools optimization: Enabled for parallel processing');
504
- console.log(' • Performance enhancements: Smart batching, concurrent operations');
505
- }
506
- console.log('\n🚀 To proceed with initialization, run the same command without --dry-run');
507
- } else {
508
- printSuccess('🎉 Claude Code integration files initialized successfully!');
509
-
510
- if (initOptimized) {
511
- console.log('\n⚡ Batchtools Optimization Enabled!');
512
- console.log(' • Parallel processing capabilities activated');
513
- console.log(' • Performance improvements: 250-500% faster operations');
514
- console.log(' • Smart batching and concurrent operations available');
515
- }
516
-
517
- console.log('\n📋 What was created:');
518
- console.log(
519
- ` ✅ CLAUDE.md (${initOptimized ? 'Batchtools-optimized' : initSparc ? 'SPARC-enhanced' : 'Standard configuration'})`,
520
- );
521
- console.log(
522
- ` ✅ memory-bank.md (${initOptimized ? 'With parallel processing' : 'Standard memory system'})`,
523
- );
524
- console.log(
525
- ` ✅ coordination.md (${initOptimized ? 'Enhanced with batchtools' : 'Standard coordination'})`,
526
- );
527
- console.log(' ✅ Directory structure with memory/ and coordination/');
528
- console.log(' ✅ Local executable at ./claude-flow');
529
- console.log(' ✅ Persistence database at memory/claude-flow-data.json');
530
- console.log(' ✅ Agent system with 64 specialized agents in .claude/agents/');
531
-
532
- if (initSparc) {
533
- const modeCount = selectedModes ? selectedModes.length : '20+';
534
- console.log(` ✅ Claude Code slash commands (${modeCount} SPARC modes)`);
535
- console.log(' ✅ Complete SPARC development environment');
536
- }
537
-
538
- console.log('\n🚀 Next steps:');
539
- console.log('1. Review and customize the generated files for your project');
540
- console.log("2. Run './claude-flow-novice start' to begin the orchestration system");
541
- console.log("3. Use './claude-flow' instead of 'npx claude-flow' for all commands");
542
- console.log("4. Use 'claude --dangerously-skip-permissions' for unattended operation");
543
-
544
- if (initSparc) {
545
- console.log(
546
- '5. Use Claude Code slash commands: /sparc, /sparc-architect, /sparc-tdd, etc.',
547
- );
548
- console.log("6. Explore SPARC modes with './claude-flow-novice sparc modes'");
549
- console.log('7. Try TDD workflow with \'./claude-flow-novice sparc tdd "your task"\'');
550
-
551
- if (initOptimized) {
552
- console.log('8. Use batchtools commands: /batchtools, /performance for optimization');
553
- console.log('9. Enable parallel processing with --parallel flags');
554
- console.log("10. Monitor performance with './claude-flow-novice performance monitor'");
555
333
  }
556
- }
557
-
558
- // Update .gitignore
559
- const gitignoreResult = await updateGitignore(workingDir, initForce, initDryRun);
560
- if (gitignoreResult.success) {
334
+ // Agent setup moved to end of function where execution is guaranteed
335
+ // Directory structure is created by template copier
336
+ // SPARC files are created by template copier when --sparc flag is used
337
+ // Memory README files and persistence database are created by template copier
338
+ // Create local claude-flow-novice executable wrapper
561
339
  if (!initDryRun) {
562
- console.log(` ✅ ${gitignoreResult.message}`);
340
+ await createLocalExecutable(workingDir);
563
341
  } else {
564
- console.log(` ${gitignoreResult.message}`);
342
+ console.log(' [DRY RUN] Would create local claude-flow-novice executable wrapper');
565
343
  }
566
- } else {
567
- console.log(` ⚠️ ${gitignoreResult.message}`);
568
- }
569
-
570
- console.log('\n💡 Tips:');
571
- console.log(" Type '/' in Claude Code to see all available slash commands");
572
- console.log(" Use './claude-flow-novice status' to check system health");
573
- console.log(" • Store important context with './claude-flow-novice memory store'");
574
-
575
- if (initOptimized) {
576
- console.log(' • Use --parallel flags for concurrent operations');
577
- console.log(' • Enable batch processing for multiple related tasks');
578
- console.log(' • Monitor performance with real-time metrics');
579
- }
580
-
581
- // Initialize hive-mind system for standard init
582
- console.log('\n🧠 Initializing basic hive-mind system...');
583
- try {
584
- const hiveMindOptions = {
585
- config: {
586
- integration: {
587
- claudeCode: { enabled: isClaudeCodeInstalled() },
588
- mcpTools: { enabled: true },
589
- },
590
- monitoring: { enabled: false }, // Basic setup for standard init
591
- },
592
- };
593
-
594
- const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, false);
595
-
596
- if (hiveMindResult.success) {
597
- console.log(' ✅ Basic hive-mind system initialized');
598
- console.log(' 💡 Use "npx claude-flow-novice hive-mind" for advanced features');
599
- } else {
600
- console.log(` ⚠️ Hive-mind setup skipped: ${hiveMindResult.error}`);
344
+ // SPARC initialization
345
+ if (initSparc) {
346
+ console.log('\n🚀 Initializing SPARC development environment...');
347
+ if (initDryRun) {
348
+ console.log(' [DRY RUN] Would run: npx -y create-sparc init --force');
349
+ console.log(' [DRY RUN] Would create SPARC environment with all modes');
350
+ console.log(' [DRY RUN] Would create Claude slash commands' + (initOptimized ? ' (Batchtools-optimized)' : ''));
351
+ if (selectedModes) {
352
+ console.log(` [DRY RUN] Would create commands for selected modes: ${selectedModes.join(', ')}`);
353
+ }
354
+ } else {
355
+ // Check if create-sparc exists and run it
356
+ let sparcInitialized = false;
357
+ try {
358
+ // Use isolated NPX cache to prevent concurrent conflicts
359
+ console.log(' 🔄 Running: npx -y create-sparc init --force');
360
+ const createSparcResult = await runCommand('npx', [
361
+ '-y',
362
+ 'create-sparc',
363
+ 'init',
364
+ '--force'
365
+ ], {
366
+ cwd: workingDir,
367
+ stdout: 'inherit',
368
+ stderr: 'inherit',
369
+ env: getIsolatedNpxEnv({
370
+ PWD: workingDir
371
+ })
372
+ });
373
+ if (createSparcResult.success) {
374
+ console.log(' ✅ SPARC environment initialized successfully');
375
+ sparcInitialized = true;
376
+ } else {
377
+ printWarning('create-sparc failed, creating basic SPARC structure manually...');
378
+ // Fallback: create basic SPARC structure manually
379
+ await createSparcStructureManually();
380
+ sparcInitialized = true; // Manual creation still counts as initialized
381
+ }
382
+ } catch (err) {
383
+ printWarning('create-sparc not available, creating basic SPARC structure manually...');
384
+ // Fallback: create basic SPARC structure manually
385
+ await createSparcStructureManually();
386
+ sparcInitialized = true; // Manual creation still counts as initialized
387
+ }
388
+ // Always create Claude slash commands after SPARC initialization
389
+ if (sparcInitialized) {
390
+ try {
391
+ if (initOptimized) {
392
+ await createOptimizedClaudeSlashCommands(workingDir, selectedModes);
393
+ } else {
394
+ await createClaudeSlashCommands(workingDir);
395
+ }
396
+ } catch (err) {
397
+ // Legacy slash command creation - silently skip if it fails
398
+ // SPARC slash commands are already created successfully above
399
+ }
400
+ }
401
+ }
601
402
  }
602
- } catch (err) {
603
- console.log(` ⚠️ Hive-mind setup skipped: ${err.message}`);
604
- }
605
-
606
- // Check for Claude Code and set up MCP servers (always enabled by default)
607
- if (!initDryRun && isClaudeCodeInstalled()) {
608
- console.log('\n🔍 Claude Code CLI detected!');
609
- const skipMcp = subArgs && subArgs.includes && subArgs.includes('--skip-mcp');
610
-
611
- if (!skipMcp) {
612
- // Use bulletproof MCP setup instead of legacy
613
- const mcpSuccess = await setupBulletproofMcp({
614
- verbose: false,
615
- autoFix: true,
616
- dryRun: initDryRun
617
- });
618
-
619
- if (!mcpSuccess) {
620
- console.log(' 💡 If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
621
- }
403
+ if (initDryRun) {
404
+ printSuccess("🔍 Dry run completed! Here's what would be created:");
405
+ console.log('\n📋 Summary of planned initialization:');
406
+ console.log(` • Configuration: ${initOptimized ? 'Batchtools-optimized SPARC' : initSparc ? 'SPARC-enhanced' : 'Standard'}`);
407
+ console.log(` • Template type: ${initOptimized ? 'Optimized for parallel processing' : 'Standard'}`);
408
+ console.log(' • Core files: CLAUDE.md, memory-bank.md, coordination.md');
409
+ console.log(' Directory structure: memory/, coordination/, .claude/');
410
+ console.log(' • Local executable: ./claude-flow');
411
+ if (initSparc) {
412
+ console.log(` • Claude Code slash commands: ${selectedModes ? selectedModes.length : 'All'} SPARC mode commands`);
413
+ console.log(' • SPARC environment with all development modes');
414
+ }
415
+ if (initOptimized) {
416
+ console.log(' • Batchtools optimization: Enabled for parallel processing');
417
+ console.log(' • Performance enhancements: Smart batching, concurrent operations');
418
+ }
419
+ console.log('\n🚀 To proceed with initialization, run the same command without --dry-run');
622
420
  } else {
623
- console.log(' ℹ️ Skipping MCP setup (--skip-mcp flag used)');
421
+ printSuccess('🎉 Claude Code integration files initialized successfully!');
422
+ if (initOptimized) {
423
+ console.log('\n⚡ Batchtools Optimization Enabled!');
424
+ console.log(' • Parallel processing capabilities activated');
425
+ console.log(' • Performance improvements: 250-500% faster operations');
426
+ console.log(' • Smart batching and concurrent operations available');
427
+ }
428
+ console.log('\n📋 What was created:');
429
+ console.log(` ✅ CLAUDE.md (${initOptimized ? 'Batchtools-optimized' : initSparc ? 'SPARC-enhanced' : 'Standard configuration'})`);
430
+ console.log(` ✅ memory-bank.md (${initOptimized ? 'With parallel processing' : 'Standard memory system'})`);
431
+ console.log(` ✅ coordination.md (${initOptimized ? 'Enhanced with batchtools' : 'Standard coordination'})`);
432
+ console.log(' ✅ Directory structure with memory/ and coordination/');
433
+ console.log(' ✅ Local executable at ./claude-flow');
434
+ console.log(' ✅ Persistence database at memory/claude-flow-data.json');
435
+ console.log(' ✅ Agent system with 64 specialized agents in .claude/agents/');
436
+ if (initSparc) {
437
+ const modeCount = selectedModes ? selectedModes.length : '20+';
438
+ console.log(` ✅ Claude Code slash commands (${modeCount} SPARC modes)`);
439
+ console.log(' ✅ Complete SPARC development environment');
440
+ }
441
+ console.log('\n🚀 Next steps:');
442
+ console.log('1. Review and customize the generated files for your project');
443
+ console.log("2. Run './claude-flow-novice start' to begin the orchestration system");
444
+ console.log("3. Use './claude-flow' instead of 'npx claude-flow' for all commands");
445
+ console.log("4. Use 'claude --dangerously-skip-permissions' for unattended operation");
446
+ if (initSparc) {
447
+ console.log('5. Use Claude Code slash commands: /sparc, /sparc-architect, /sparc-tdd, etc.');
448
+ console.log("6. Explore SPARC modes with './claude-flow-novice sparc modes'");
449
+ console.log('7. Try TDD workflow with \'./claude-flow-novice sparc tdd "your task"\'');
450
+ if (initOptimized) {
451
+ console.log('8. Use batchtools commands: /batchtools, /performance for optimization');
452
+ console.log('9. Enable parallel processing with --parallel flags');
453
+ console.log("10. Monitor performance with './claude-flow-novice performance monitor'");
454
+ }
455
+ }
456
+ // Update .gitignore
457
+ const gitignoreResult = await updateGitignore(workingDir, initForce, initDryRun);
458
+ if (gitignoreResult.success) {
459
+ if (!initDryRun) {
460
+ console.log(` ✅ ${gitignoreResult.message}`);
461
+ } else {
462
+ console.log(` ${gitignoreResult.message}`);
463
+ }
464
+ } else {
465
+ console.log(` ⚠️ ${gitignoreResult.message}`);
466
+ }
467
+ console.log('\n💡 Tips:');
468
+ console.log(" • Type '/' in Claude Code to see all available slash commands");
469
+ console.log(" • Use './claude-flow-novice status' to check system health");
470
+ console.log(" • Store important context with './claude-flow-novice memory store'");
471
+ if (initOptimized) {
472
+ console.log(' • Use --parallel flags for concurrent operations');
473
+ console.log(' • Enable batch processing for multiple related tasks');
474
+ console.log(' • Monitor performance with real-time metrics');
475
+ }
476
+ // Initialize hive-mind system for standard init
477
+ console.log('\n🧠 Initializing basic hive-mind system...');
478
+ try {
479
+ const hiveMindOptions = {
480
+ config: {
481
+ integration: {
482
+ claudeCode: {
483
+ enabled: isClaudeCodeInstalled()
484
+ },
485
+ mcpTools: {
486
+ enabled: true
487
+ }
488
+ },
489
+ monitoring: {
490
+ enabled: false
491
+ }
492
+ }
493
+ };
494
+ const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, false);
495
+ if (hiveMindResult.success) {
496
+ console.log(' ✅ Basic hive-mind system initialized');
497
+ console.log(' 💡 Use "npx claude-flow-novice hive-mind" for advanced features');
498
+ } else {
499
+ console.log(` ⚠️ Hive-mind setup skipped: ${hiveMindResult.error}`);
500
+ }
501
+ } catch (err) {
502
+ console.log(` ⚠️ Hive-mind setup skipped: ${err.message}`);
503
+ }
504
+ // Check for Claude Code and set up MCP servers (always enabled by default)
505
+ if (!initDryRun && isClaudeCodeInstalled()) {
506
+ console.log('\n🔍 Claude Code CLI detected!');
507
+ const skipMcp = subArgs && subArgs.includes && subArgs.includes('--skip-mcp');
508
+ if (!skipMcp) {
509
+ // Use bulletproof MCP setup instead of legacy
510
+ const mcpSuccess = await setupBulletproofMcp({
511
+ verbose: false,
512
+ autoFix: true,
513
+ dryRun: initDryRun
514
+ });
515
+ if (!mcpSuccess) {
516
+ console.log(' 💡 If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
517
+ }
518
+ } else {
519
+ console.log(' ℹ️ Skipping MCP setup (--skip-mcp flag used)');
520
+ }
521
+ } else if (!initDryRun && !isClaudeCodeInstalled()) {
522
+ console.log('\n⚠️ Claude Code CLI not detected!');
523
+ console.log(' 📥 Install with: npm install -g @anthropic-ai/claude-code');
524
+ console.log(' 📋 Then add MCP servers manually with:');
525
+ console.log(' claude mcp add claude-flow-novice claude-flow-novice mcp start');
526
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');
527
+ // Flow-nexus integration removed
528
+ }
624
529
  }
625
- } else if (!initDryRun && !isClaudeCodeInstalled()) {
626
- console.log('\n⚠️ Claude Code CLI not detected!');
627
- console.log(' 📥 Install with: npm install -g @anthropic-ai/claude-code');
628
- console.log(' 📋 Then add MCP servers manually with:');
629
- console.log(' claude mcp add claude-flow-novice claude-flow-novice mcp start');
630
- console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');
631
- // Flow-nexus integration removed
632
- }
530
+ } catch (err) {
531
+ printError(`Failed to initialize files: ${err.message}`);
633
532
  }
634
- } catch (err) {
635
- printError(`Failed to initialize files: ${err.message}`);
636
- }
637
533
  }
638
-
639
534
  // Handle batch initialization
640
535
  async function handleBatchInit(subArgs, flags) {
641
- try {
642
- // Options parsing from flags and subArgs
643
- const options = {
644
- parallel: !flags['no-parallel'] && flags.parallel !== false,
645
- sparc: flags.sparc || flags.s,
646
- minimal: flags.minimal || flags.m,
647
- force: flags.force || flags.f,
648
- maxConcurrency: flags['max-concurrent'] || 5,
649
- progressTracking: true,
650
- template: flags.template,
651
- environments: flags.environments
652
- ? flags.environments.split(',').map((env) => env.trim())
653
- : ['dev'],
654
- };
655
-
656
- // Validate options
657
- const validationErrors = validateBatchOptions(options);
658
- if (validationErrors.length > 0) {
659
- printError('Batch options validation failed:');
660
- validationErrors.forEach((error) => console.error(` - ${error}`));
661
- return;
662
- }
663
-
664
- // Config file mode
665
- if (flags.config) {
666
- const configFile = flags.config;
667
- printSuccess(`Loading batch configuration from: ${configFile}`);
668
- const results = await batchInitFromConfig(configFile, options);
669
- if (results) {
670
- printSuccess('Batch initialization from config completed');
671
- }
672
- return;
673
- }
674
-
675
- // Batch init mode
676
- if (flags['batch-init']) {
677
- const projectsString = flags['batch-init'];
678
- const projects = projectsString.split(',').map((project) => project.trim());
679
-
680
- if (projects.length === 0) {
681
- printError('No projects specified for batch initialization');
682
- return;
683
- }
684
-
685
- printSuccess(`Initializing ${projects.length} projects in batch mode`);
686
- const results = await batchInitCommand(projects, options);
687
-
688
- if (results) {
689
- const successful = results.filter((r) => r.success).length;
690
- const failed = results.filter((r) => !r.success).length;
691
-
692
- if (failed === 0) {
693
- printSuccess(`All ${successful} projects initialized successfully`);
694
- } else {
695
- printWarning(`${successful} projects succeeded, ${failed} failed`);
536
+ try {
537
+ // Options parsing from flags and subArgs
538
+ const options = {
539
+ parallel: !flags['no-parallel'] && flags.parallel !== false,
540
+ sparc: flags.sparc || flags.s,
541
+ minimal: flags.minimal || flags.m,
542
+ force: flags.force || flags.f,
543
+ maxConcurrency: flags['max-concurrent'] || 5,
544
+ progressTracking: true,
545
+ template: flags.template,
546
+ environments: flags.environments ? flags.environments.split(',').map((env)=>env.trim()) : [
547
+ 'dev'
548
+ ]
549
+ };
550
+ // Validate options
551
+ const validationErrors = validateBatchOptions(options);
552
+ if (validationErrors.length > 0) {
553
+ printError('Batch options validation failed:');
554
+ validationErrors.forEach((error)=>console.error(` - ${error}`));
555
+ return;
556
+ }
557
+ // Config file mode
558
+ if (flags.config) {
559
+ const configFile = flags.config;
560
+ printSuccess(`Loading batch configuration from: ${configFile}`);
561
+ const results = await batchInitFromConfig(configFile, options);
562
+ if (results) {
563
+ printSuccess('Batch initialization from config completed');
564
+ }
565
+ return;
696
566
  }
697
- }
698
- return;
567
+ // Batch init mode
568
+ if (flags['batch-init']) {
569
+ const projectsString = flags['batch-init'];
570
+ const projects = projectsString.split(',').map((project)=>project.trim());
571
+ if (projects.length === 0) {
572
+ printError('No projects specified for batch initialization');
573
+ return;
574
+ }
575
+ printSuccess(`Initializing ${projects.length} projects in batch mode`);
576
+ const results = await batchInitCommand(projects, options);
577
+ if (results) {
578
+ const successful = results.filter((r)=>r.success).length;
579
+ const failed = results.filter((r)=>!r.success).length;
580
+ if (failed === 0) {
581
+ printSuccess(`All ${successful} projects initialized successfully`);
582
+ } else {
583
+ printWarning(`${successful} projects succeeded, ${failed} failed`);
584
+ }
585
+ }
586
+ return;
587
+ }
588
+ printError('No batch operation specified. Use --batch-init <projects> or --config <file>');
589
+ } catch (err) {
590
+ printError(`Batch initialization failed: ${err.message}`);
699
591
  }
700
-
701
- printError('No batch operation specified. Use --batch-init <projects> or --config <file>');
702
- } catch (err) {
703
- printError(`Batch initialization failed: ${err.message}`);
704
- }
705
592
  }
706
-
707
593
  /**
708
594
  * Enhanced initialization command with validation and rollback
709
- */
710
- async function enhancedInitCommand(subArgs, flags) {
711
- console.log('🛡️ Starting enhanced initialization with validation and rollback...');
712
-
713
- // Store parameters to avoid scope issues in async context
714
- const args = subArgs || [];
715
- const options = flags || {};
716
-
717
- // Get the working directory
718
- const workingDir = process.env.PWD || process.cwd();
719
-
720
- // Initialize systems
721
- const rollbackSystem = new RollbackSystem(workingDir);
722
- const validationSystem = new ValidationSystem(workingDir);
723
-
724
- let atomicOp = null;
725
-
726
- try {
727
- // Parse options
728
- const initOptions = {
729
- force: args.includes('--force') || args.includes('-f') || options.force,
730
- minimal: args.includes('--minimal') || args.includes('-m') || options.minimal,
731
- sparc: args.includes('--sparc') || args.includes('-s') || options.sparc,
732
- skipPreValidation: args.includes('--skip-pre-validation'),
733
- skipBackup: args.includes('--skip-backup'),
734
- validateOnly: args.includes('--validate-only'),
735
- };
736
-
737
- // Phase 1: Pre-initialization validation
738
- if (!initOptions.skipPreValidation) {
739
- console.log('\n🔍 Phase 1: Pre-initialization validation...');
740
- const preValidation = await validationSystem.validatePreInit(initOptions);
741
-
742
- if (!preValidation.success) {
743
- printError('Pre-initialization validation failed:');
744
- preValidation.errors.forEach((error) => console.error(` ❌ ${error}`));
745
- return;
746
- }
747
-
748
- if (preValidation.warnings.length > 0) {
749
- printWarning('Pre-initialization warnings:');
750
- preValidation.warnings.forEach((warning) => console.warn(` ⚠️ ${warning}`));
751
- }
752
-
753
- printSuccess('Pre-initialization validation passed');
754
- }
755
-
756
- // Stop here if validation-only mode
757
- if (options.validateOnly) {
758
- console.log('\n✅ Validation-only mode completed');
759
- return;
760
- }
761
-
762
- // Phase 2: Create backup
763
- if (!options.skipBackup) {
764
- console.log('\n💾 Phase 2: Creating backup...');
765
- const backupResult = await rollbackSystem.createPreInitBackup();
766
-
767
- if (!backupResult.success) {
768
- printError('Backup creation failed:');
769
- backupResult.errors.forEach((error) => console.error(` ❌ ${error}`));
770
- return;
771
- }
772
- }
773
-
774
- // Phase 3: Initialize with atomic operations
775
- console.log('\n🔧 Phase 3: Atomic initialization...');
776
- atomicOp = createAtomicOperation(rollbackSystem, 'enhanced-init');
777
-
778
- const atomicBegin = await atomicOp.begin();
779
- if (!atomicBegin) {
780
- printError('Failed to begin atomic operation');
781
- return;
782
- }
783
-
784
- // Perform initialization steps with checkpoints
785
- await performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun);
786
-
787
- // Phase 4: Post-initialization validation
788
- console.log('\n✅ Phase 4: Post-initialization validation...');
789
- const postValidation = await validationSystem.validatePostInit();
790
-
791
- if (!postValidation.success) {
792
- printError('Post-initialization validation failed:');
793
- postValidation.errors.forEach((error) => console.error(` ❌ ${error}`));
794
-
795
- // Attempt automatic rollback
796
- console.log('\n🔄 Attempting automatic rollback...');
797
- await atomicOp.rollback();
798
- printWarning('Initialization rolled back due to validation failure');
799
- return;
800
- }
801
-
802
- // Phase 5: Configuration validation
803
- console.log('\n🔧 Phase 5: Configuration validation...');
804
- const configValidation = await validationSystem.validateConfiguration();
805
-
806
- if (configValidation.warnings.length > 0) {
807
- printWarning('Configuration warnings:');
808
- configValidation.warnings.forEach((warning) => console.warn(` ⚠️ ${warning}`));
809
- }
810
-
811
- // Phase 6: Health checks
812
- console.log('\n🏥 Phase 6: System health checks...');
813
- const healthChecks = await validationSystem.runHealthChecks();
814
-
815
- if (healthChecks.warnings.length > 0) {
816
- printWarning('Health check warnings:');
817
- healthChecks.warnings.forEach((warning) => console.warn(` ⚠️ ${warning}`));
818
- }
819
-
820
- // Commit atomic operation
821
- await atomicOp.commit();
822
-
823
- // Generate and display validation report
824
- const fullValidation = await runFullValidation(workingDir, {
825
- postInit: true,
826
- skipPreInit: options.skipPreValidation,
827
- });
828
-
829
- console.log('\n📊 Validation Report:');
830
- console.log(fullValidation.report);
831
-
832
- printSuccess('🎉 Enhanced initialization completed successfully!');
833
- console.log('\n✨ Your SPARC environment is fully validated and ready to use');
834
- } catch (error) {
835
- printError(`Enhanced initialization failed: ${error.message}`);
836
-
837
- // Attempt rollback if atomic operation is active
838
- if (atomicOp && !atomicOp.completed) {
839
- console.log('\n🔄 Performing emergency rollback...');
840
- try {
841
- await atomicOp.rollback();
842
- printWarning('Emergency rollback completed');
843
- } catch (rollbackError) {
844
- printError(`Rollback also failed: ${rollbackError.message}`);
845
- }
595
+ */ async function enhancedInitCommand(subArgs, flags) {
596
+ console.log('🛡️ Starting enhanced initialization with validation and rollback...');
597
+ // Store parameters to avoid scope issues in async context
598
+ const args = subArgs || [];
599
+ const options = flags || {};
600
+ // Get the working directory
601
+ const workingDir = process.env.PWD || process.cwd();
602
+ // Initialize systems
603
+ const rollbackSystem = new RollbackSystem(workingDir);
604
+ const validationSystem = new ValidationSystem(workingDir);
605
+ let atomicOp = null;
606
+ try {
607
+ // Parse options
608
+ const initOptions = {
609
+ force: args.includes('--force') || args.includes('-f') || options.force,
610
+ minimal: args.includes('--minimal') || args.includes('-m') || options.minimal,
611
+ sparc: args.includes('--sparc') || args.includes('-s') || options.sparc,
612
+ skipPreValidation: args.includes('--skip-pre-validation'),
613
+ skipBackup: args.includes('--skip-backup'),
614
+ validateOnly: args.includes('--validate-only')
615
+ };
616
+ // Phase 1: Pre-initialization validation
617
+ if (!initOptions.skipPreValidation) {
618
+ console.log('\n🔍 Phase 1: Pre-initialization validation...');
619
+ const preValidation = await validationSystem.validatePreInit(initOptions);
620
+ if (!preValidation.success) {
621
+ printError('Pre-initialization validation failed:');
622
+ preValidation.errors.forEach((error)=>console.error(` ❌ ${error}`));
623
+ return;
624
+ }
625
+ if (preValidation.warnings.length > 0) {
626
+ printWarning('Pre-initialization warnings:');
627
+ preValidation.warnings.forEach((warning)=>console.warn(` ⚠️ ${warning}`));
628
+ }
629
+ printSuccess('Pre-initialization validation passed');
630
+ }
631
+ // Stop here if validation-only mode
632
+ if (options.validateOnly) {
633
+ console.log('\n✅ Validation-only mode completed');
634
+ return;
635
+ }
636
+ // Phase 2: Create backup
637
+ if (!options.skipBackup) {
638
+ console.log('\n💾 Phase 2: Creating backup...');
639
+ const backupResult = await rollbackSystem.createPreInitBackup();
640
+ if (!backupResult.success) {
641
+ printError('Backup creation failed:');
642
+ backupResult.errors.forEach((error)=>console.error(` ❌ ${error}`));
643
+ return;
644
+ }
645
+ }
646
+ // Phase 3: Initialize with atomic operations
647
+ console.log('\n🔧 Phase 3: Atomic initialization...');
648
+ atomicOp = createAtomicOperation(rollbackSystem, 'enhanced-init');
649
+ const atomicBegin = await atomicOp.begin();
650
+ if (!atomicBegin) {
651
+ printError('Failed to begin atomic operation');
652
+ return;
653
+ }
654
+ // Perform initialization steps with checkpoints
655
+ await performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun);
656
+ // Phase 4: Post-initialization validation
657
+ console.log('\n✅ Phase 4: Post-initialization validation...');
658
+ const postValidation = await validationSystem.validatePostInit();
659
+ if (!postValidation.success) {
660
+ printError('Post-initialization validation failed:');
661
+ postValidation.errors.forEach((error)=>console.error(` ❌ ${error}`));
662
+ // Attempt automatic rollback
663
+ console.log('\n🔄 Attempting automatic rollback...');
664
+ await atomicOp.rollback();
665
+ printWarning('Initialization rolled back due to validation failure');
666
+ return;
667
+ }
668
+ // Phase 5: Configuration validation
669
+ console.log('\n🔧 Phase 5: Configuration validation...');
670
+ const configValidation = await validationSystem.validateConfiguration();
671
+ if (configValidation.warnings.length > 0) {
672
+ printWarning('Configuration warnings:');
673
+ configValidation.warnings.forEach((warning)=>console.warn(` ⚠️ ${warning}`));
674
+ }
675
+ // Phase 6: Health checks
676
+ console.log('\n🏥 Phase 6: System health checks...');
677
+ const healthChecks = await validationSystem.runHealthChecks();
678
+ if (healthChecks.warnings.length > 0) {
679
+ printWarning('Health check warnings:');
680
+ healthChecks.warnings.forEach((warning)=>console.warn(` ⚠️ ${warning}`));
681
+ }
682
+ // Commit atomic operation
683
+ await atomicOp.commit();
684
+ // Generate and display validation report
685
+ const fullValidation = await runFullValidation(workingDir, {
686
+ postInit: true,
687
+ skipPreInit: options.skipPreValidation
688
+ });
689
+ console.log('\n📊 Validation Report:');
690
+ console.log(fullValidation.report);
691
+ printSuccess('🎉 Enhanced initialization completed successfully!');
692
+ console.log('\n✨ Your SPARC environment is fully validated and ready to use');
693
+ } catch (error) {
694
+ printError(`Enhanced initialization failed: ${error.message}`);
695
+ // Attempt rollback if atomic operation is active
696
+ if (atomicOp && !atomicOp.completed) {
697
+ console.log('\n🔄 Performing emergency rollback...');
698
+ try {
699
+ await atomicOp.rollback();
700
+ printWarning('Emergency rollback completed');
701
+ } catch (rollbackError) {
702
+ printError(`Rollback also failed: ${rollbackError.message}`);
703
+ }
704
+ }
846
705
  }
847
- }
848
706
  }
849
-
850
707
  /**
851
708
  * Handle validation commands
852
- */
853
- async function handleValidationCommand(subArgs, flags) {
854
- const workingDir = process.env.PWD || process.cwd();
855
-
856
- console.log('🔍 Running validation checks...');
857
-
858
- const options = {
859
- skipPreInit: subArgs.includes('--skip-pre-init'),
860
- skipConfig: subArgs.includes('--skip-config'),
861
- skipModeTest: subArgs.includes('--skip-mode-test'),
862
- postInit: !subArgs.includes('--pre-init-only'),
863
- };
864
-
865
- try {
866
- const validationResults = await runFullValidation(workingDir, options);
867
-
868
- console.log('\n📊 Validation Results:');
869
- console.log(validationResults.report);
870
-
871
- if (validationResults.success) {
872
- printSuccess('✅ All validation checks passed');
873
- } else {
874
- printError('❌ Some validation checks failed');
875
- process.exit(1);
709
+ */ async function handleValidationCommand(subArgs, flags) {
710
+ const workingDir = process.env.PWD || process.cwd();
711
+ console.log('🔍 Running validation checks...');
712
+ const options = {
713
+ skipPreInit: subArgs.includes('--skip-pre-init'),
714
+ skipConfig: subArgs.includes('--skip-config'),
715
+ skipModeTest: subArgs.includes('--skip-mode-test'),
716
+ postInit: !subArgs.includes('--pre-init-only')
717
+ };
718
+ try {
719
+ const validationResults = await runFullValidation(workingDir, options);
720
+ console.log('\n📊 Validation Results:');
721
+ console.log(validationResults.report);
722
+ if (validationResults.success) {
723
+ printSuccess('✅ All validation checks passed');
724
+ } else {
725
+ printError(' Some validation checks failed');
726
+ process.exit(1);
727
+ }
728
+ } catch (error) {
729
+ printError(`Validation failed: ${error.message}`);
730
+ process.exit(1);
876
731
  }
877
- } catch (error) {
878
- printError(`Validation failed: ${error.message}`);
879
- process.exit(1);
880
- }
881
732
  }
882
-
883
733
  /**
884
734
  * Handle rollback commands
885
- */
886
- async function handleRollbackCommand(subArgs, flags) {
887
- const workingDir = process.env.PWD || process.cwd();
888
- const rollbackSystem = new RollbackSystem(workingDir);
889
-
890
- try {
891
- // Check for specific rollback options
892
- if (subArgs.includes('--full')) {
893
- console.log('🔄 Performing full rollback...');
894
- const result = await rollbackSystem.performFullRollback();
895
-
896
- if (result.success) {
897
- printSuccess('Full rollback completed successfully');
898
- } else {
899
- printError('Full rollback failed:');
900
- result.errors.forEach((error) => console.error(` ❌ ${error}`));
901
- }
902
- } else if (subArgs.includes('--partial')) {
903
- const phaseIndex = subArgs.findIndex((arg) => arg === '--phase');
904
- if (phaseIndex !== -1 && subArgs[phaseIndex + 1]) {
905
- const phase = subArgs[phaseIndex + 1];
906
- console.log(`🔄 Performing partial rollback for phase: ${phase}`);
907
-
908
- const result = await rollbackSystem.performPartialRollback(phase);
909
-
910
- if (result.success) {
911
- printSuccess(`Partial rollback completed for phase: ${phase}`);
912
- } else {
913
- printError(`Partial rollback failed for phase: ${phase}`);
914
- result.errors.forEach((error) => console.error(` ❌ ${error}`));
915
- }
916
- } else {
917
- printError('Partial rollback requires --phase <phase-name>');
918
- }
919
- } else {
920
- // Interactive rollback point selection
921
- const rollbackPoints = await rollbackSystem.listRollbackPoints();
922
-
923
- if (rollbackPoints.rollbackPoints.length === 0) {
924
- printWarning('No rollback points available');
925
- return;
926
- }
927
-
928
- console.log('\n📋 Available rollback points:');
929
- rollbackPoints.rollbackPoints.forEach((point, index) => {
930
- const date = new Date(point.timestamp).toLocaleString();
931
- console.log(` ${index + 1}. ${point.type} - ${date}`);
932
- });
933
-
934
- // For now, rollback to the most recent point
935
- const latest = rollbackPoints.rollbackPoints[0];
936
- if (latest) {
937
- console.log(
938
- `\n🔄 Rolling back to: ${latest.type} (${new Date(latest.timestamp).toLocaleString()})`,
939
- );
940
- const result = await rollbackSystem.performFullRollback(latest.backupId);
941
-
942
- if (result.success) {
943
- printSuccess('Rollback completed successfully');
735
+ */ async function handleRollbackCommand(subArgs, flags) {
736
+ const workingDir = process.env.PWD || process.cwd();
737
+ const rollbackSystem = new RollbackSystem(workingDir);
738
+ try {
739
+ // Check for specific rollback options
740
+ if (subArgs.includes('--full')) {
741
+ console.log('🔄 Performing full rollback...');
742
+ const result = await rollbackSystem.performFullRollback();
743
+ if (result.success) {
744
+ printSuccess('Full rollback completed successfully');
745
+ } else {
746
+ printError('Full rollback failed:');
747
+ result.errors.forEach((error)=>console.error(` ❌ ${error}`));
748
+ }
749
+ } else if (subArgs.includes('--partial')) {
750
+ const phaseIndex = subArgs.findIndex((arg)=>arg === '--phase');
751
+ if (phaseIndex !== -1 && subArgs[phaseIndex + 1]) {
752
+ const phase = subArgs[phaseIndex + 1];
753
+ console.log(`🔄 Performing partial rollback for phase: ${phase}`);
754
+ const result = await rollbackSystem.performPartialRollback(phase);
755
+ if (result.success) {
756
+ printSuccess(`Partial rollback completed for phase: ${phase}`);
757
+ } else {
758
+ printError(`Partial rollback failed for phase: ${phase}`);
759
+ result.errors.forEach((error)=>console.error(` ❌ ${error}`));
760
+ }
761
+ } else {
762
+ printError('Partial rollback requires --phase <phase-name>');
763
+ }
944
764
  } else {
945
- printError('Rollback failed');
765
+ // Interactive rollback point selection
766
+ const rollbackPoints = await rollbackSystem.listRollbackPoints();
767
+ if (rollbackPoints.rollbackPoints.length === 0) {
768
+ printWarning('No rollback points available');
769
+ return;
770
+ }
771
+ console.log('\n📋 Available rollback points:');
772
+ rollbackPoints.rollbackPoints.forEach((point, index)=>{
773
+ const date = new Date(point.timestamp).toLocaleString();
774
+ console.log(` ${index + 1}. ${point.type} - ${date}`);
775
+ });
776
+ // For now, rollback to the most recent point
777
+ const latest = rollbackPoints.rollbackPoints[0];
778
+ if (latest) {
779
+ console.log(`\n🔄 Rolling back to: ${latest.type} (${new Date(latest.timestamp).toLocaleString()})`);
780
+ const result = await rollbackSystem.performFullRollback(latest.backupId);
781
+ if (result.success) {
782
+ printSuccess('Rollback completed successfully');
783
+ } else {
784
+ printError('Rollback failed');
785
+ }
786
+ }
946
787
  }
947
- }
788
+ } catch (error) {
789
+ printError(`Rollback operation failed: ${error.message}`);
948
790
  }
949
- } catch (error) {
950
- printError(`Rollback operation failed: ${error.message}`);
951
- }
952
791
  }
953
-
954
792
  /**
955
793
  * Handle list backups command
956
- */
957
- async function handleListBackups(subArgs, flags) {
958
- const workingDir = process.env.PWD || process.cwd();
959
- const rollbackSystem = new RollbackSystem(workingDir);
960
-
961
- try {
962
- const rollbackPoints = await rollbackSystem.listRollbackPoints();
963
-
964
- console.log('\n📋 Rollback Points and Backups:');
965
-
966
- if (rollbackPoints.rollbackPoints.length === 0) {
967
- console.log(' No rollback points available');
968
- } else {
969
- console.log('\n🔄 Rollback Points:');
970
- rollbackPoints.rollbackPoints.forEach((point, index) => {
971
- const date = new Date(point.timestamp).toLocaleString();
972
- console.log(` ${index + 1}. ${point.type} - ${date} (${point.backupId || 'No backup'})`);
973
- });
974
- }
975
-
976
- if (rollbackPoints.checkpoints.length > 0) {
977
- console.log('\n📍 Checkpoints:');
978
- rollbackPoints.checkpoints.slice(-5).forEach((checkpoint, index) => {
979
- const date = new Date(checkpoint.timestamp).toLocaleString();
980
- console.log(` ${index + 1}. ${checkpoint.phase} - ${date} (${checkpoint.status})`);
981
- });
794
+ */ async function handleListBackups(subArgs, flags) {
795
+ const workingDir = process.env.PWD || process.cwd();
796
+ const rollbackSystem = new RollbackSystem(workingDir);
797
+ try {
798
+ const rollbackPoints = await rollbackSystem.listRollbackPoints();
799
+ console.log('\n📋 Rollback Points and Backups:');
800
+ if (rollbackPoints.rollbackPoints.length === 0) {
801
+ console.log(' No rollback points available');
802
+ } else {
803
+ console.log('\n🔄 Rollback Points:');
804
+ rollbackPoints.rollbackPoints.forEach((point, index)=>{
805
+ const date = new Date(point.timestamp).toLocaleString();
806
+ console.log(` ${index + 1}. ${point.type} - ${date} (${point.backupId || 'No backup'})`);
807
+ });
808
+ }
809
+ if (rollbackPoints.checkpoints.length > 0) {
810
+ console.log('\n📍 Checkpoints:');
811
+ rollbackPoints.checkpoints.slice(-5).forEach((checkpoint, index)=>{
812
+ const date = new Date(checkpoint.timestamp).toLocaleString();
813
+ console.log(` ${index + 1}. ${checkpoint.phase} - ${date} (${checkpoint.status})`);
814
+ });
815
+ }
816
+ } catch (error) {
817
+ printError(`Failed to list backups: ${error.message}`);
982
818
  }
983
- } catch (error) {
984
- printError(`Failed to list backups: ${error.message}`);
985
- }
986
819
  }
987
-
988
820
  /**
989
821
  * Perform initialization with checkpoints
990
- */
991
- async function performInitializationWithCheckpoints(
992
- rollbackSystem,
993
- options,
994
- workingDir,
995
- dryRun = false,
996
- ) {
997
- const phases = [
998
- { name: 'file-creation', action: () => createInitialFiles(options, workingDir, dryRun) },
999
- { name: 'directory-structure', action: () => createDirectoryStructure(workingDir, dryRun) },
1000
- { name: 'memory-setup', action: () => setupMemorySystem(workingDir, dryRun) },
1001
- { name: 'agent-system', action: () => setupAgentSystem(workingDir, dryRun, options) },
1002
- { name: 'mcp-config', action: () => setupMcpConfiguration(workingDir, dryRun) },
1003
- { name: 'hooks-system', action: () => setupHooksSystem(workingDir, dryRun) },
1004
- { name: 'coordination-setup', action: () => setupCoordinationSystem(workingDir, dryRun) },
1005
- { name: 'executable-creation', action: () => createLocalExecutable(workingDir, dryRun) },
1006
- ];
1007
-
1008
- if (options.sparc) {
1009
- phases.push(
1010
- { name: 'sparc-init', action: () => createSparcStructureManually() },
1011
- { name: 'claude-commands', action: () => createClaudeSlashCommands(workingDir) },
1012
- );
1013
- }
1014
-
1015
- for (const phase of phases) {
1016
- console.log(` 🔧 ${phase.name}...`);
1017
-
1018
- // Create checkpoint before phase
1019
- await rollbackSystem.createCheckpoint(phase.name, {
1020
- timestamp: Date.now(),
1021
- phase: phase.name,
1022
- });
1023
-
1024
- try {
1025
- await phase.action();
1026
- console.log(` ✅ ${phase.name} completed`);
1027
- } catch (error) {
1028
- console.error(` ❌ ${phase.name} failed: ${error.message}`);
1029
- throw error;
822
+ */ async function performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun1 = false) {
823
+ const phases = [
824
+ {
825
+ name: 'file-creation',
826
+ action: ()=>createInitialFiles(options, workingDir, dryRun1)
827
+ },
828
+ {
829
+ name: 'directory-structure',
830
+ action: ()=>createDirectoryStructure(workingDir, dryRun1)
831
+ },
832
+ {
833
+ name: 'memory-setup',
834
+ action: ()=>setupMemorySystem(workingDir, dryRun1)
835
+ },
836
+ {
837
+ name: 'agent-system',
838
+ action: ()=>setupAgentSystem(workingDir, dryRun1, options)
839
+ },
840
+ {
841
+ name: 'mcp-config',
842
+ action: ()=>setupMcpConfiguration(workingDir, dryRun1)
843
+ },
844
+ {
845
+ name: 'hooks-system',
846
+ action: ()=>setupHooksSystem(workingDir, dryRun1)
847
+ },
848
+ {
849
+ name: 'coordination-setup',
850
+ action: ()=>setupCoordinationSystem(workingDir, dryRun1)
851
+ },
852
+ {
853
+ name: 'executable-creation',
854
+ action: ()=>createLocalExecutable(workingDir, dryRun1)
855
+ }
856
+ ];
857
+ if (options.sparc) {
858
+ phases.push({
859
+ name: 'sparc-init',
860
+ action: ()=>createSparcStructureManually()
861
+ }, {
862
+ name: 'claude-commands',
863
+ action: ()=>createClaudeSlashCommands(workingDir)
864
+ });
865
+ }
866
+ for (const phase of phases){
867
+ console.log(` 🔧 ${phase.name}...`);
868
+ // Create checkpoint before phase
869
+ await rollbackSystem.createCheckpoint(phase.name, {
870
+ timestamp: Date.now(),
871
+ phase: phase.name
872
+ });
873
+ try {
874
+ await phase.action();
875
+ console.log(` ✅ ${phase.name} completed`);
876
+ } catch (error) {
877
+ console.error(` ❌ ${phase.name} failed: ${error.message}`);
878
+ throw error;
879
+ }
1030
880
  }
1031
- }
1032
881
  }
1033
-
1034
882
  // Helper functions for atomic initialization
1035
- async function createInitialFiles(options, workingDir, dryRun = false) {
1036
- if (!dryRun) {
1037
- // Use template file instead of generation
1038
- const claudeMd = await readClaudeMdTemplate();
1039
- await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMd, 'utf8');
1040
-
1041
- const memoryBankMd = options.minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();
1042
- await fs.writeFile(`${workingDir}/memory-bank.md`, memoryBankMd, 'utf8');
1043
-
1044
- const coordinationMd = options.minimal
1045
- ? createMinimalCoordinationMd()
1046
- : createFullCoordinationMd();
1047
- await fs.writeFile(`${workingDir}/coordination.md`, coordinationMd, 'utf8');
1048
- }
1049
- }
1050
-
1051
- async function createDirectoryStructure(workingDir, dryRun = false) {
1052
- const directories = [
1053
- 'memory',
1054
- 'memory/agents',
1055
- 'memory/sessions',
1056
- 'coordination',
1057
- 'coordination/memory_bank',
1058
- 'coordination/subtasks',
1059
- 'coordination/orchestration',
1060
- '.claude',
1061
- '.claude/commands',
1062
- '.claude/logs',
1063
- ];
1064
-
1065
- if (!dryRun) {
1066
- for (const dir of directories) {
1067
- await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });
883
+ async function createInitialFiles(options, workingDir, dryRun1 = false) {
884
+ if (!dryRun1) {
885
+ // Use template file instead of generation
886
+ const claudeMd = await readClaudeMdTemplate();
887
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMd, 'utf8');
888
+ const memoryBankMd = options.minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();
889
+ await fs.writeFile(`${workingDir}/memory-bank.md`, memoryBankMd, 'utf8');
890
+ const coordinationMd = options.minimal ? createMinimalCoordinationMd() : createFullCoordinationMd();
891
+ await fs.writeFile(`${workingDir}/coordination.md`, coordinationMd, 'utf8');
1068
892
  }
1069
- }
1070
893
  }
1071
-
1072
- async function setupMemorySystem(workingDir, dryRun = false) {
1073
- if (!dryRun) {
1074
- const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };
1075
- await fs.writeFile(
1076
- `${workingDir}/memory/claude-flow-data.json`,
1077
- JSON.stringify(initialData, null, 2),
1078
- 'utf8',
1079
- );
1080
-
1081
- await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
1082
- await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1083
- }
894
+ async function createDirectoryStructure(workingDir, dryRun1 = false) {
895
+ const directories = [
896
+ 'memory',
897
+ 'memory/agents',
898
+ 'memory/sessions',
899
+ 'coordination',
900
+ 'coordination/memory_bank',
901
+ 'coordination/subtasks',
902
+ 'coordination/orchestration',
903
+ '.claude',
904
+ '.claude/commands',
905
+ '.claude/logs'
906
+ ];
907
+ if (!dryRun1) {
908
+ for (const dir of directories){
909
+ await fs.mkdir(`${workingDir}/${dir}`, {
910
+ recursive: true
911
+ });
912
+ }
913
+ }
1084
914
  }
1085
-
1086
- async function setupAgentSystem(workingDir, dryRun = false, options = {}) {
1087
- if (!dryRun) {
1088
- console.log('🤖 Setting up agent system...');
1089
-
1090
- // Create agent directories
1091
- await createAgentDirectories(workingDir, dryRun);
1092
-
1093
- // Copy all agent files (80+ agents)
1094
- const agentResult = await copyAgentFiles(workingDir, {
1095
- force: options.force || false,
1096
- dryRun: dryRun,
1097
- });
1098
-
1099
- if (agentResult.success) {
1100
- await validateAgentSystem(workingDir);
1101
-
1102
- // Copy command files
1103
- const commandResult = await copyCommandFiles(workingDir, {
1104
- force: options.force || false,
1105
- dryRun: dryRun,
1106
- });
1107
-
1108
- if (commandResult.success) {
1109
- console.log(' ✅ Agent system setup complete with 80+ specialized agents');
1110
- } else {
1111
- console.log(' ⚠️ Command system setup failed:', commandResult.error);
1112
- }
1113
- } else {
1114
- console.log(' ⚠️ Agent system setup failed:', agentResult.error);
915
+ async function setupMemorySystem(workingDir, dryRun1 = false) {
916
+ if (!dryRun1) {
917
+ const initialData = {
918
+ agents: [],
919
+ tasks: [],
920
+ lastUpdated: Date.now()
921
+ };
922
+ await fs.writeFile(`${workingDir}/memory/claude-flow-data.json`, JSON.stringify(initialData, null, 2), 'utf8');
923
+ await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
924
+ await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1115
925
  }
1116
- }
1117
926
  }
1118
-
1119
- async function setupMcpConfiguration(workingDir, dryRun = false) {
1120
- if (!dryRun) {
1121
- console.log('🔌 Setting up MCP configuration...');
1122
-
1123
- const mcpConfig = {
1124
- "mcpServers": {
1125
- "claude-flow-novice": {
1126
- "command": "npx",
1127
- "args": ["claude-flow-novice", "mcp", "start"],
1128
- "env": {
1129
- "CLAUDE_FLOW_NOVICE_MODE": "novice",
1130
- "CLAUDE_FLOW_NOVICE_SIMPLIFIED": "true"
1131
- }
927
+ async function setupAgentSystem(workingDir, dryRun1 = false, options = {}) {
928
+ if (!dryRun1) {
929
+ console.log('🤖 Setting up agent system...');
930
+ // Create agent directories
931
+ await createAgentDirectories(workingDir, dryRun1);
932
+ // Copy all agent files (80+ agents)
933
+ const agentResult = await copyAgentFiles(workingDir, {
934
+ force: options.force || false,
935
+ dryRun: dryRun1
936
+ });
937
+ if (agentResult.success) {
938
+ await validateAgentSystem(workingDir);
939
+ // Copy command files
940
+ const commandResult = await copyCommandFiles(workingDir, {
941
+ force: options.force || false,
942
+ dryRun: dryRun1
943
+ });
944
+ if (commandResult.success) {
945
+ console.log(' ✅ Agent system setup complete with 80+ specialized agents');
946
+ } else {
947
+ console.log(' ⚠️ Command system setup failed:', commandResult.error);
948
+ }
949
+ } else {
950
+ console.log(' ⚠️ Agent system setup failed:', agentResult.error);
1132
951
  }
1133
- }
1134
- };
1135
-
1136
- await fs.writeFile(
1137
- `${workingDir}/.mcp.json`,
1138
- JSON.stringify(mcpConfig, null, 2),
1139
- 'utf8'
1140
- );
1141
- console.log(' ✅ Created .mcp.json configuration');
1142
- }
952
+ }
1143
953
  }
1144
-
1145
- async function setupHooksSystem(workingDir, dryRun = false) {
1146
- if (!dryRun) {
1147
- console.log('🪝 Setting up hooks system...');
1148
-
1149
- // Create .claude/settings.json with hooks configuration
1150
- const settingsConfig = {
1151
- "hooks": {
1152
- "pre-tool": {
1153
- "command": "npx claude-flow-novice hooks pre-task --description \"{{description}}\"",
1154
- "enabled": true
1155
- },
1156
- "post-tool": {
1157
- "command": "npx claude-flow-novice hooks post-task --task-id \"{{taskId}}\"",
1158
- "enabled": true
1159
- },
1160
- "pre-edit": {
1161
- "command": "npx claude-flow-novice hooks pre-edit --file \"{{file}}\"",
1162
- "enabled": true
1163
- },
1164
- "post-edit": {
1165
- "command": "npx claude-flow-novice hooks post-edit --file \"{{file}}\" --memory-key \"swarm/{{agent}}/{{step}}\"",
1166
- "enabled": true
1167
- }
1168
- },
1169
- "coordination": {
1170
- "autoSpawn": true,
1171
- "memoryPersistence": true,
1172
- "swarmOrchestration": true
1173
- }
1174
- };
1175
-
1176
- await fs.writeFile(
1177
- `${workingDir}/.claude/settings.json`,
1178
- JSON.stringify(settingsConfig, null, 2),
1179
- 'utf8'
1180
- );
1181
- console.log(' ✅ Created hooks configuration');
1182
- }
954
+ async function setupMcpConfiguration(workingDir, dryRun1 = false) {
955
+ if (!dryRun1) {
956
+ console.log('🔌 Setting up MCP configuration...');
957
+ const mcpConfig = {
958
+ "mcpServers": {
959
+ "claude-flow-novice": {
960
+ "command": "npx",
961
+ "args": [
962
+ "claude-flow-novice",
963
+ "mcp",
964
+ "start"
965
+ ],
966
+ "env": {
967
+ "CLAUDE_FLOW_NOVICE_MODE": "novice",
968
+ "CLAUDE_FLOW_NOVICE_SIMPLIFIED": "true"
969
+ }
970
+ }
971
+ }
972
+ };
973
+ await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2), 'utf8');
974
+ console.log(' ✅ Created .mcp.json configuration');
975
+ }
1183
976
  }
1184
-
1185
- async function setupCoordinationSystem(workingDir, dryRun = false) {
1186
- // Coordination system is already set up by createDirectoryStructure
1187
- // This is a placeholder for future coordination setup logic
977
+ async function setupHooksSystem(workingDir, dryRun1 = false) {
978
+ if (!dryRun1) {
979
+ console.log('🪝 Setting up hooks system...');
980
+ // Create .claude/settings.json with hooks configuration
981
+ const settingsConfig = {
982
+ "hooks": {
983
+ "pre-tool": {
984
+ "command": "npx claude-flow-novice hooks pre-task --description \"{{description}}\"",
985
+ "enabled": true
986
+ },
987
+ "post-tool": {
988
+ "command": "npx claude-flow-novice hooks post-task --task-id \"{{taskId}}\"",
989
+ "enabled": true
990
+ },
991
+ "pre-edit": {
992
+ "command": "npx claude-flow-novice hooks pre-edit --file \"{{file}}\"",
993
+ "enabled": true
994
+ },
995
+ "post-edit": {
996
+ "command": "npx claude-flow-novice hooks post-edit --file \"{{file}}\" --memory-key \"swarm/{{agent}}/{{step}}\"",
997
+ "enabled": true
998
+ }
999
+ },
1000
+ "coordination": {
1001
+ "autoSpawn": true,
1002
+ "memoryPersistence": true,
1003
+ "swarmOrchestration": true
1004
+ }
1005
+ };
1006
+ await fs.writeFile(`${workingDir}/.claude/settings.json`, JSON.stringify(settingsConfig, null, 2), 'utf8');
1007
+ console.log(' ✅ Created hooks configuration');
1008
+ }
1009
+ }
1010
+ async function setupCoordinationSystem(workingDir, dryRun1 = false) {
1011
+ // Coordination system is already set up by createDirectoryStructure
1012
+ // This is a placeholder for future coordination setup logic
1188
1013
  }
1189
-
1190
1014
  /**
1191
1015
  * Setup monitoring and telemetry for token tracking
1192
- */
1193
- async function setupMonitoring(workingDir) {
1194
- console.log(' 📈 Configuring token usage tracking...');
1195
-
1196
- const fs = await import('fs/promises');
1197
- const path = await import('path');
1198
-
1199
- try {
1200
- // Create .claude-flow-novice directory for tracking data
1201
- const trackingDir = path.join(workingDir, '.claude-flow');
1202
- await fs.mkdir(trackingDir, { recursive: true });
1203
-
1204
- // Create initial token usage file
1205
- const tokenUsageFile = path.join(trackingDir, 'token-usage.json');
1206
- const initialData = {
1207
- total: 0,
1208
- input: 0,
1209
- output: 0,
1210
- byAgent: {},
1211
- lastUpdated: new Date().toISOString(),
1212
- };
1213
-
1214
- await fs.writeFile(tokenUsageFile, JSON.stringify(initialData, null, 2));
1215
- printSuccess(' ✓ Created token usage tracking file');
1216
-
1217
- // Add telemetry configuration to .claude/settings.json if it exists
1218
- const settingsPath = path.join(workingDir, '.claude', 'settings.json');
1016
+ */ async function setupMonitoring(workingDir) {
1017
+ console.log(' 📈 Configuring token usage tracking...');
1018
+ const fs = await import("node:fs/promises");
1019
+ const path = await import("path");
1219
1020
  try {
1220
- const settingsContent = await fs.readFile(settingsPath, 'utf8');
1221
- const settings = JSON.parse(settingsContent);
1222
-
1223
- // Add telemetry hook
1224
- if (!settings.hooks) settings.hooks = {};
1225
- if (!settings.hooks['post-task']) settings.hooks['post-task'] = [];
1226
-
1227
- // Add token tracking hook
1228
- const tokenTrackingHook =
1229
- 'npx claude-flow-novice internal track-tokens --session-id {{session_id}} --tokens {{token_usage}}';
1230
- if (!settings.hooks['post-task'].includes(tokenTrackingHook)) {
1231
- settings.hooks['post-task'].push(tokenTrackingHook);
1232
- }
1233
-
1234
- await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
1235
- printSuccess(' ✓ Added token tracking hooks to settings');
1236
- } catch (err) {
1237
- console.log(' ⚠️ Could not update settings.json:', err.message);
1238
- }
1239
-
1240
- // Create monitoring configuration
1241
- const monitoringConfig = {
1242
- enabled: true,
1243
- telemetry: {
1244
- claudeCode: {
1245
- env: 'CLAUDE_CODE_ENABLE_TELEMETRY',
1246
- value: '1',
1247
- description: 'Enable Claude Code OpenTelemetry metrics',
1248
- },
1249
- },
1250
- tracking: {
1251
- tokens: true,
1252
- costs: true,
1253
- agents: true,
1254
- sessions: true,
1255
- },
1256
- storage: {
1257
- location: '.claude-flow/token-usage.json',
1258
- format: 'json',
1259
- rotation: 'monthly',
1260
- },
1261
- };
1262
-
1263
- const configPath = path.join(trackingDir, 'monitoring.config.json');
1264
- await fs.writeFile(configPath, JSON.stringify(monitoringConfig, null, 2));
1265
- printSuccess(' ✓ Created monitoring configuration');
1266
-
1267
- // Create shell profile snippet for environment variable
1268
- const envSnippet = `
1021
+ // Create .claude-flow-novice directory for tracking data
1022
+ const trackingDir = path.join(workingDir, '.claude-flow');
1023
+ await fs.mkdir(trackingDir, {
1024
+ recursive: true
1025
+ });
1026
+ // Create initial token usage file
1027
+ const tokenUsageFile = path.join(trackingDir, 'token-usage.json');
1028
+ const initialData = {
1029
+ total: 0,
1030
+ input: 0,
1031
+ output: 0,
1032
+ byAgent: {},
1033
+ lastUpdated: new Date().toISOString()
1034
+ };
1035
+ await fs.writeFile(tokenUsageFile, JSON.stringify(initialData, null, 2));
1036
+ printSuccess(' ✓ Created token usage tracking file');
1037
+ // Add telemetry configuration to .claude/settings.json if it exists
1038
+ const settingsPath = path.join(workingDir, '.claude', 'settings.json');
1039
+ try {
1040
+ const settingsContent = await fs.readFile(settingsPath, 'utf8');
1041
+ const settings = JSON.parse(settingsContent);
1042
+ // Add telemetry hook
1043
+ if (!settings.hooks) settings.hooks = {};
1044
+ if (!settings.hooks['post-task']) settings.hooks['post-task'] = [];
1045
+ // Add token tracking hook
1046
+ const tokenTrackingHook = 'npx claude-flow-novice internal track-tokens --session-id {{session_id}} --tokens {{token_usage}}';
1047
+ if (!settings.hooks['post-task'].includes(tokenTrackingHook)) {
1048
+ settings.hooks['post-task'].push(tokenTrackingHook);
1049
+ }
1050
+ await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
1051
+ printSuccess(' ✓ Added token tracking hooks to settings');
1052
+ } catch (err) {
1053
+ console.log(' ⚠️ Could not update settings.json:', err.message);
1054
+ }
1055
+ // Create monitoring configuration
1056
+ const monitoringConfig = {
1057
+ enabled: true,
1058
+ telemetry: {
1059
+ claudeCode: {
1060
+ env: 'CLAUDE_CODE_ENABLE_TELEMETRY',
1061
+ value: '1',
1062
+ description: 'Enable Claude Code OpenTelemetry metrics'
1063
+ }
1064
+ },
1065
+ tracking: {
1066
+ tokens: true,
1067
+ costs: true,
1068
+ agents: true,
1069
+ sessions: true
1070
+ },
1071
+ storage: {
1072
+ location: '.claude-flow/token-usage.json',
1073
+ format: 'json',
1074
+ rotation: 'monthly'
1075
+ }
1076
+ };
1077
+ const configPath = path.join(trackingDir, 'monitoring.config.json');
1078
+ await fs.writeFile(configPath, JSON.stringify(monitoringConfig, null, 2));
1079
+ printSuccess(' ✓ Created monitoring configuration');
1080
+ // Create shell profile snippet for environment variable
1081
+ const envSnippet = `
1269
1082
  # Claude Flow Token Tracking
1270
1083
  # Add this to your shell profile (.bashrc, .zshrc, etc.)
1271
1084
  export CLAUDE_CODE_ENABLE_TELEMETRY=1
@@ -1273,606 +1086,544 @@ export CLAUDE_CODE_ENABLE_TELEMETRY=1
1273
1086
  # Optional: Set custom metrics path
1274
1087
  # export CLAUDE_METRICS_PATH="$HOME/.claude/metrics"
1275
1088
  `;
1276
-
1277
- const envPath = path.join(trackingDir, 'env-setup.sh');
1278
- await fs.writeFile(envPath, envSnippet.trim());
1279
- printSuccess(' Created environment setup script');
1280
-
1281
- console.log('\n 📋 To enable Claude Code telemetry:');
1282
- console.log(' 1. Add to your shell profile: export CLAUDE_CODE_ENABLE_TELEMETRY=1');
1283
- console.log(' 2. Or run: source .claude-flow/env-setup.sh');
1284
- console.log('\n 💡 Token usage will be tracked in .claude-flow/token-usage.json');
1285
- console.log(' Run: claude-flow-novice analysis token-usage --breakdown --cost-analysis');
1286
- } catch (err) {
1287
- printError(` Failed to setup monitoring: ${err.message}`);
1288
- }
1089
+ const envPath = path.join(trackingDir, 'env-setup.sh');
1090
+ await fs.writeFile(envPath, envSnippet.trim());
1091
+ printSuccess(' ✓ Created environment setup script');
1092
+ console.log('\n 📋 To enable Claude Code telemetry:');
1093
+ console.log(' 1. Add to your shell profile: export CLAUDE_CODE_ENABLE_TELEMETRY=1');
1094
+ console.log(' 2. Or run: source .claude-flow/env-setup.sh');
1095
+ console.log('\n 💡 Token usage will be tracked in .claude-flow/token-usage.json');
1096
+ console.log(' Run: claude-flow-novice analysis token-usage --breakdown --cost-analysis');
1097
+ } catch (err) {
1098
+ printError(` Failed to setup monitoring: ${err.message}`);
1099
+ }
1289
1100
  }
1290
-
1291
1101
  /**
1292
1102
  * Enhanced Claude Flow v2.0.0 initialization
1293
- */
1294
- async function enhancedClaudeFlowInit(flags, subArgs = []) {
1295
- console.log('🚀 Initializing Claude Flow v2.0.0 with enhanced features...');
1296
-
1297
- const workingDir = process.cwd();
1298
- const force = flags.force || flags.f;
1299
- const dryRun = flags.dryRun || flags['dry-run'] || flags.d;
1300
- const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag
1301
-
1302
- // Store parameters to avoid scope issues in async context
1303
- const args = subArgs || [];
1304
- const options = flags || {};
1305
-
1306
- // Import fs module for Node.js
1307
- const fs = await import('fs/promises');
1308
- const { chmod } = fs;
1309
-
1310
- try {
1311
- // Check existing files
1312
- const existingFiles = [];
1313
- const filesToCheck = [
1314
- 'CLAUDE.md',
1315
- '.claude/settings.json',
1316
- '.mcp.json',
1317
- 'claude-flow.config.json',
1318
- ];
1319
-
1320
- for (const file of filesToCheck) {
1321
- if (existsSync(`${workingDir}/${file}`)) {
1322
- existingFiles.push(file);
1323
- }
1324
- }
1325
-
1326
- if (existingFiles.length > 0 && !force) {
1327
- printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
1328
- console.log('Use --force to overwrite existing files');
1329
- return;
1330
- }
1331
-
1332
- // Create CLAUDE.md from template
1333
- if (!dryRun) {
1334
- const claudeMdContent = await readClaudeMdTemplate();
1335
- await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMdContent, 'utf8');
1336
- printSuccess('✓ Created CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1337
- } else {
1338
- console.log('[DRY RUN] Would create CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1339
- }
1340
-
1341
- // Create .claude directory structure
1342
- const claudeDir = `${workingDir}/.claude`;
1343
- if (!dryRun) {
1344
- await fs.mkdir(claudeDir, { recursive: true });
1345
- await fs.mkdir(`${claudeDir}/commands`, { recursive: true });
1346
- await fs.mkdir(`${claudeDir}/helpers`, { recursive: true });
1347
- printSuccess('✓ Created .claude directory structure');
1348
- } else {
1349
- console.log('[DRY RUN] Would create .claude directory structure');
1350
- }
1351
-
1352
- // Create settings.json
1353
- if (!dryRun) {
1354
- await fs.writeFile(`${claudeDir}/settings.json`, createEnhancedSettingsJson(), 'utf8');
1355
- printSuccess('✓ Created .claude/settings.json with hooks and MCP configuration');
1356
- } else {
1357
- console.log('[DRY RUN] Would create .claude/settings.json');
1358
- }
1359
-
1360
- // Create settings.local.json with default MCP permissions
1361
- const settingsLocal = {
1362
- permissions: {
1363
- allow: ['mcp__ruv-swarm', 'mcp__claude-flow'],
1364
- deny: [],
1365
- },
1366
- };
1367
-
1368
- if (!dryRun) {
1369
- await fs.writeFile(
1370
- `${claudeDir}/settings.local.json`,
1371
- JSON.stringify(settingsLocal, null, 2, 'utf8'),
1372
- );
1373
- printSuccess('✓ Created .claude/settings.local.json with default MCP permissions');
1374
- } else {
1375
- console.log(
1376
- '[DRY RUN] Would create .claude/settings.local.json with default MCP permissions',
1377
- );
1378
- }
1379
-
1380
- // Setup bulletproof MCP configuration instead of legacy approach
1381
- console.log('\n🛡️ Setting up bulletproof MCP configuration...');
1382
-
1383
- const mcpOptions = {
1384
- verbose: flags.verbose || false,
1385
- autoFix: flags['auto-fix'] !== false && !flags['no-auto-fix'], // Default true unless explicitly disabled
1386
- dryRun: dryRun,
1387
- enhancedUx: true, // Enable enhanced user experience
1388
- showEducation: flags['show-education'] || false,
1389
- serverConfig: {
1390
- mcpServers: {
1391
- 'claude-flow-novice': {
1392
- command: 'npx',
1393
- args: ['claude-flow-novice', 'mcp', 'start'],
1394
- env: {
1395
- NODE_ENV: 'production',
1396
- CLAUDE_FLOW_NOVICE_MODE: 'novice'
1103
+ */ async function enhancedClaudeFlowInit(flags, subArgs = []) {
1104
+ console.log('🚀 Initializing Claude Flow v2.0.0 with enhanced features...');
1105
+ const workingDir = process.cwd();
1106
+ const force = flags.force || flags.f;
1107
+ const dryRun1 = flags.dryRun || flags['dry-run'] || flags.d;
1108
+ const initSparc = flags.roo || subArgs && subArgs.includes('--roo'); // SPARC only with --roo flag
1109
+ // Store parameters to avoid scope issues in async context
1110
+ const args = subArgs || [];
1111
+ const options = flags || {};
1112
+ // Import fs module for Node.js
1113
+ const fs = await import("node:fs/promises");
1114
+ const { chmod } = fs;
1115
+ try {
1116
+ // Check existing files
1117
+ const existingFiles = [];
1118
+ const filesToCheck = [
1119
+ 'CLAUDE.md',
1120
+ '.claude/settings.json',
1121
+ '.mcp.json',
1122
+ 'claude-flow.config.json'
1123
+ ];
1124
+ for (const file of filesToCheck){
1125
+ if (existsSync(`${workingDir}/${file}`)) {
1126
+ existingFiles.push(file);
1397
1127
  }
1398
- }
1399
1128
  }
1400
- }
1401
- };
1402
-
1403
- let mcpSuccess = false;
1404
- try {
1405
- const { enhancedMcpInit } = await import('../../mcp/mcp-config-manager.js');
1406
- const result = await enhancedMcpInit(mcpOptions);
1407
-
1408
- if (result.success) {
1409
- printSuccess('✓ Bulletproof MCP configuration completed successfully');
1410
- if (result.details) {
1411
- console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
1412
- console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
1129
+ if (existingFiles.length > 0 && !force) {
1130
+ printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
1131
+ console.log('Use --force to overwrite existing files');
1132
+ return;
1413
1133
  }
1414
- mcpSuccess = true;
1415
- } else {
1416
- printWarning(`⚠️ MCP configuration had issues: ${result.error || 'Unknown error'}`);
1417
- if (result.rollbackAvailable) {
1418
- console.log(' 🔄 Automatic rollback was performed');
1134
+ // Create CLAUDE.md from template
1135
+ if (!dryRun1) {
1136
+ const claudeMdContent = await readClaudeMdTemplate();
1137
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMdContent, 'utf8');
1138
+ printSuccess(' Created CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1139
+ } else {
1140
+ console.log('[DRY RUN] Would create CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1419
1141
  }
1420
- }
1421
- } catch (error) {
1422
- printWarning(`⚠️ Bulletproof MCP setup failed: ${error.message}`);
1423
- printWarning(' 📞 Falling back to legacy MCP configuration...');
1424
-
1425
- // Fallback to legacy config creation
1426
- const mcpConfig = {
1427
- mcpServers: {
1428
- 'claude-flow-novice': {
1429
- command: 'npx',
1430
- args: ['claude-flow-novice', 'mcp', 'start'],
1431
- env: {
1432
- NODE_ENV: 'production',
1433
- CLAUDE_FLOW_NOVICE_MODE: 'novice'
1142
+ // Create .claude directory structure
1143
+ const claudeDir = `${workingDir}/.claude`;
1144
+ if (!dryRun1) {
1145
+ await fs.mkdir(claudeDir, {
1146
+ recursive: true
1147
+ });
1148
+ await fs.mkdir(`${claudeDir}/commands`, {
1149
+ recursive: true
1150
+ });
1151
+ await fs.mkdir(`${claudeDir}/helpers`, {
1152
+ recursive: true
1153
+ });
1154
+ printSuccess('✓ Created .claude directory structure');
1155
+ } else {
1156
+ console.log('[DRY RUN] Would create .claude directory structure');
1157
+ }
1158
+ // Create settings.json
1159
+ if (!dryRun1) {
1160
+ await fs.writeFile(`${claudeDir}/settings.json`, createEnhancedSettingsJson(), 'utf8');
1161
+ printSuccess('✓ Created .claude/settings.json with hooks and MCP configuration');
1162
+ } else {
1163
+ console.log('[DRY RUN] Would create .claude/settings.json');
1164
+ }
1165
+ // Create settings.local.json with default MCP permissions
1166
+ const settingsLocal = {
1167
+ permissions: {
1168
+ allow: [
1169
+ 'mcp__ruv-swarm',
1170
+ 'mcp__claude-flow'
1171
+ ],
1172
+ deny: []
1434
1173
  }
1435
- }
1174
+ };
1175
+ if (!dryRun1) {
1176
+ await fs.writeFile(`${claudeDir}/settings.local.json`, JSON.stringify(settingsLocal, null, 2, 'utf8'));
1177
+ printSuccess('✓ Created .claude/settings.local.json with default MCP permissions');
1178
+ } else {
1179
+ console.log('[DRY RUN] Would create .claude/settings.local.json with default MCP permissions');
1436
1180
  }
1437
- };
1438
-
1439
- if (!dryRun) {
1440
- await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2), 'utf8');
1441
- printSuccess(' Created .mcp.json with legacy configuration');
1442
- } else {
1443
- console.log('[DRY RUN] Would create .mcp.json with legacy configuration');
1444
- }
1445
- mcpSuccess = true; // Consider legacy success for continuation
1446
- }
1447
-
1448
- // Create claude-flow.config.json for Claude Flow specific settings
1449
- const claudeFlowConfig = {
1450
- features: {
1451
- autoTopologySelection: true,
1452
- parallelExecution: true,
1453
- neuralTraining: true,
1454
- bottleneckAnalysis: true,
1455
- smartAutoSpawning: true,
1456
- selfHealingWorkflows: true,
1457
- crossSessionMemory: true,
1458
- githubIntegration: true,
1459
- },
1460
- performance: {
1461
- maxAgents: 10,
1462
- defaultTopology: 'hierarchical',
1463
- executionStrategy: 'parallel',
1464
- tokenOptimization: true,
1465
- cacheEnabled: true,
1466
- telemetryLevel: 'detailed',
1467
- },
1468
- };
1469
-
1470
- if (!dryRun) {
1471
- await fs.writeFile(
1472
- `${workingDir}/claude-flow.config.json`,
1473
- JSON.stringify(claudeFlowConfig, null, 2, 'utf8'),
1474
- );
1475
- printSuccess('✓ Created claude-flow.config.json for Claude Flow settings');
1476
- } else {
1477
- console.log('[DRY RUN] Would create claude-flow.config.json for Claude Flow settings');
1478
- }
1479
-
1480
- // Create command documentation
1481
- for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)) {
1482
- const categoryDir = `${claudeDir}/commands/${category}`;
1483
-
1484
- if (!dryRun) {
1485
- await fs.mkdir(categoryDir, { recursive: true });
1486
-
1487
- // Create category README
1488
- const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands
1181
+ // Setup bulletproof MCP configuration instead of legacy approach
1182
+ console.log('\n🛡️ Setting up bulletproof MCP configuration...');
1183
+ const mcpOptions = {
1184
+ verbose: flags.verbose || false,
1185
+ autoFix: flags['auto-fix'] !== false && !flags['no-auto-fix'],
1186
+ dryRun: dryRun1,
1187
+ enhancedUx: true,
1188
+ showEducation: flags['show-education'] || false,
1189
+ serverConfig: {
1190
+ mcpServers: {
1191
+ 'claude-flow-novice': {
1192
+ command: 'npx',
1193
+ args: [
1194
+ 'claude-flow-novice',
1195
+ 'mcp',
1196
+ 'start'
1197
+ ],
1198
+ env: {
1199
+ NODE_ENV: 'production',
1200
+ CLAUDE_FLOW_NOVICE_MODE: 'novice'
1201
+ }
1202
+ }
1203
+ }
1204
+ }
1205
+ };
1206
+ let mcpSuccess = false;
1207
+ try {
1208
+ const { enhancedMcpInit } = await import("../../mcp/mcp-config-manager.js");
1209
+ const result = await enhancedMcpInit(mcpOptions);
1210
+ if (result.success) {
1211
+ printSuccess('✓ Bulletproof MCP configuration completed successfully');
1212
+ if (result.details) {
1213
+ console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
1214
+ console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
1215
+ }
1216
+ mcpSuccess = true;
1217
+ } else {
1218
+ printWarning(`⚠️ MCP configuration had issues: ${result.error || 'Unknown error'}`);
1219
+ if (result.rollbackAvailable) {
1220
+ console.log(' 🔄 Automatic rollback was performed');
1221
+ }
1222
+ }
1223
+ } catch (error) {
1224
+ printWarning(`⚠️ Bulletproof MCP setup failed: ${error.message}`);
1225
+ printWarning(' 📞 Falling back to legacy MCP configuration...');
1226
+ // Fallback to legacy config creation
1227
+ const mcpConfig = {
1228
+ mcpServers: {
1229
+ 'claude-flow-novice': {
1230
+ command: 'npx',
1231
+ args: [
1232
+ 'claude-flow-novice',
1233
+ 'mcp',
1234
+ 'start'
1235
+ ],
1236
+ env: {
1237
+ NODE_ENV: 'production',
1238
+ CLAUDE_FLOW_NOVICE_MODE: 'novice'
1239
+ }
1240
+ }
1241
+ }
1242
+ };
1243
+ if (!dryRun1) {
1244
+ await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2), 'utf8');
1245
+ printSuccess('✓ Created .mcp.json with legacy configuration');
1246
+ } else {
1247
+ console.log('[DRY RUN] Would create .mcp.json with legacy configuration');
1248
+ }
1249
+ mcpSuccess = true; // Consider legacy success for continuation
1250
+ }
1251
+ // Create claude-flow.config.json for Claude Flow specific settings
1252
+ const claudeFlowConfig = {
1253
+ features: {
1254
+ autoTopologySelection: true,
1255
+ parallelExecution: true,
1256
+ neuralTraining: true,
1257
+ bottleneckAnalysis: true,
1258
+ smartAutoSpawning: true,
1259
+ selfHealingWorkflows: true,
1260
+ crossSessionMemory: true,
1261
+ githubIntegration: true
1262
+ },
1263
+ performance: {
1264
+ maxAgents: 10,
1265
+ defaultTopology: 'hierarchical',
1266
+ executionStrategy: 'parallel',
1267
+ tokenOptimization: true,
1268
+ cacheEnabled: true,
1269
+ telemetryLevel: 'detailed'
1270
+ }
1271
+ };
1272
+ if (!dryRun1) {
1273
+ await fs.writeFile(`${workingDir}/claude-flow.config.json`, JSON.stringify(claudeFlowConfig, null, 2, 'utf8'));
1274
+ printSuccess('✓ Created claude-flow.config.json for Claude Flow settings');
1275
+ } else {
1276
+ console.log('[DRY RUN] Would create claude-flow.config.json for Claude Flow settings');
1277
+ }
1278
+ // Create command documentation
1279
+ for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)){
1280
+ const categoryDir = `${claudeDir}/commands/${category}`;
1281
+ if (!dryRun1) {
1282
+ await fs.mkdir(categoryDir, {
1283
+ recursive: true
1284
+ });
1285
+ // Create category README
1286
+ const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands
1489
1287
 
1490
1288
  Commands for ${category} operations in Claude Flow.
1491
1289
 
1492
1290
  ## Available Commands
1493
1291
 
1494
- ${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\n')}
1292
+ ${commands.map((cmd)=>`- [${cmd}](./${cmd}.md)`).join('\n')}
1495
1293
  `;
1496
- await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');
1497
-
1498
- // Create individual command docs
1499
- for (const command of commands) {
1500
- const doc = createCommandDoc(category, command);
1501
- if (doc) {
1502
- await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');
1503
- }
1294
+ await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');
1295
+ // Create individual command docs
1296
+ for (const command of commands){
1297
+ const doc = createCommandDoc(category, command);
1298
+ if (doc) {
1299
+ await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');
1300
+ }
1301
+ }
1302
+ console.log(` ✓ Created ${commands.length} ${category} command docs`);
1303
+ } else {
1304
+ console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);
1305
+ }
1504
1306
  }
1505
-
1506
- console.log(` ✓ Created ${commands.length} ${category} command docs`);
1507
- } else {
1508
- console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);
1509
- }
1510
- }
1511
-
1512
- // Create wrapper scripts
1513
- if (!dryRun) {
1514
- // Unix wrapper - now uses universal ES module compatible wrapper
1515
- const unixWrapper = createWrapperScript('unix');
1516
- await fs.writeFile(`${workingDir}/claude-flow`, unixWrapper, 'utf8');
1517
- await fs.chmod(`${workingDir}/claude-flow`, 0o755);
1518
-
1519
- // Windows wrapper
1520
- await fs.writeFile(`${workingDir}/claude-flow.bat`, createWrapperScript('windows', 'utf8'));
1521
-
1522
- // PowerShell wrapper
1523
- await fs.writeFile(
1524
- `${workingDir}/claude-flow.ps1`,
1525
- createWrapperScript('powershell', 'utf8'),
1526
- );
1527
-
1528
- printSuccess('✓ Created platform-specific wrapper scripts');
1529
- } else {
1530
- console.log('[DRY RUN] Would create wrapper scripts');
1531
- }
1532
-
1533
- // Create helper scripts
1534
- const helpers = [
1535
- 'setup-mcp.sh',
1536
- 'quick-start.sh',
1537
- 'github-setup.sh',
1538
- 'github-safe.js',
1539
- 'standard-checkpoint-hooks.sh',
1540
- 'checkpoint-manager.sh',
1541
- ];
1542
- for (const helper of helpers) {
1543
- if (!dryRun) {
1544
- const content = createHelperScript(helper);
1545
- if (content) {
1546
- await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');
1547
- await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);
1307
+ // Create wrapper scripts
1308
+ if (!dryRun1) {
1309
+ // Unix wrapper - now uses universal ES module compatible wrapper
1310
+ const unixWrapper = createWrapperScript('unix');
1311
+ await fs.writeFile(`${workingDir}/claude-flow`, unixWrapper, 'utf8');
1312
+ await fs.chmod(`${workingDir}/claude-flow`, 0o755);
1313
+ // Windows wrapper
1314
+ await fs.writeFile(`${workingDir}/claude-flow.bat`, createWrapperScript('windows', 'utf8'));
1315
+ // PowerShell wrapper
1316
+ await fs.writeFile(`${workingDir}/claude-flow.ps1`, createWrapperScript('powershell', 'utf8'));
1317
+ printSuccess('✓ Created platform-specific wrapper scripts');
1318
+ } else {
1319
+ console.log('[DRY RUN] Would create wrapper scripts');
1548
1320
  }
1549
- }
1550
- }
1551
-
1552
- if (!dryRun) {
1553
- printSuccess(`✓ Created ${helpers.length} helper scripts`);
1554
- } else {
1555
- console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);
1556
- }
1557
-
1558
- // Create standard directories from original init
1559
- const standardDirs = [
1560
- 'memory',
1561
- 'memory/agents',
1562
- 'memory/sessions',
1563
- 'coordination',
1564
- 'coordination/memory_bank',
1565
- 'coordination/subtasks',
1566
- 'coordination/orchestration',
1567
- '.swarm', // Add .swarm directory for shared memory
1568
- '.hive-mind', // Add .hive-mind directory for hive-mind system
1569
- '.claude/checkpoints', // Add checkpoints directory for Git checkpoint system
1570
- ];
1571
-
1572
- for (const dir of standardDirs) {
1573
- if (!dryRun) {
1574
- await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });
1575
- }
1576
- }
1577
-
1578
- if (!dryRun) {
1579
- printSuccess('✓ Created standard directory structure');
1580
-
1581
- // Initialize memory system
1582
- const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };
1583
- await fs.writeFile(
1584
- `${workingDir}/memory/claude-flow-data.json`,
1585
- JSON.stringify(initialData, null, 2, 'utf8'),
1586
- );
1587
-
1588
- // Create README files
1589
- await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
1590
- await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1591
-
1592
- printSuccess('✓ Initialized memory system');
1593
-
1594
- // Initialize memory database with fallback support
1595
- try {
1596
- // Import and initialize FallbackMemoryStore to create the database
1597
- const { FallbackMemoryStore } = await import('../../../memory/fallback-store.js');
1598
- const memoryStore = new FallbackMemoryStore();
1599
- await memoryStore.initialize();
1600
-
1601
- if (memoryStore.isUsingFallback()) {
1602
- printSuccess('✓ Initialized memory system (in-memory fallback for npx compatibility)');
1603
- console.log(
1604
- ' 💡 For persistent storage, install locally: npm install claude-flow@alpha',
1605
- );
1321
+ // Create helper scripts
1322
+ const helpers = [
1323
+ 'setup-mcp.sh',
1324
+ 'quick-start.sh',
1325
+ 'github-setup.sh',
1326
+ 'github-safe.js',
1327
+ 'standard-checkpoint-hooks.sh',
1328
+ 'checkpoint-manager.sh'
1329
+ ];
1330
+ for (const helper of helpers){
1331
+ if (!dryRun1) {
1332
+ const content = createHelperScript(helper);
1333
+ if (content) {
1334
+ await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');
1335
+ await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);
1336
+ }
1337
+ }
1338
+ }
1339
+ if (!dryRun1) {
1340
+ printSuccess(`✓ Created ${helpers.length} helper scripts`);
1606
1341
  } else {
1607
- printSuccess('✓ Initialized memory database (.swarm/memory.db)');
1342
+ console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);
1608
1343
  }
1609
-
1610
- memoryStore.close();
1611
- } catch (err) {
1612
- console.log(` ⚠️ Could not initialize memory system: ${err.message}`);
1613
- console.log(' Memory will be initialized on first use');
1614
- }
1615
-
1616
- // Initialize comprehensive hive-mind system
1617
- console.log('\n🧠 Initializing Hive Mind System...');
1618
- try {
1619
- const hiveMindOptions = {
1620
- config: {
1621
- integration: {
1622
- claudeCode: { enabled: isClaudeCodeInstalled() },
1623
- mcpTools: { enabled: true },
1624
- },
1625
- monitoring: { enabled: flags.monitoring || false },
1626
- },
1627
- };
1628
-
1629
- const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, dryRun);
1630
-
1631
- if (hiveMindResult.success) {
1632
- printSuccess(
1633
- `✓ Hive Mind System initialized with ${hiveMindResult.features.length} features`,
1634
- );
1635
-
1636
- // Log individual features
1637
- hiveMindResult.features.forEach((feature) => {
1638
- console.log(` • ${feature}`);
1639
- });
1344
+ // Create standard directories from original init
1345
+ const standardDirs = [
1346
+ 'memory',
1347
+ 'memory/agents',
1348
+ 'memory/sessions',
1349
+ 'coordination',
1350
+ 'coordination/memory_bank',
1351
+ 'coordination/subtasks',
1352
+ 'coordination/orchestration',
1353
+ '.swarm',
1354
+ '.hive-mind',
1355
+ '.claude/checkpoints'
1356
+ ];
1357
+ for (const dir of standardDirs){
1358
+ if (!dryRun1) {
1359
+ await fs.mkdir(`${workingDir}/${dir}`, {
1360
+ recursive: true
1361
+ });
1362
+ }
1363
+ }
1364
+ if (!dryRun1) {
1365
+ printSuccess('✓ Created standard directory structure');
1366
+ // Initialize memory system
1367
+ const initialData = {
1368
+ agents: [],
1369
+ tasks: [],
1370
+ lastUpdated: Date.now()
1371
+ };
1372
+ await fs.writeFile(`${workingDir}/memory/claude-flow-data.json`, JSON.stringify(initialData, null, 2, 'utf8'));
1373
+ // Create README files
1374
+ await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
1375
+ await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1376
+ printSuccess('✓ Initialized memory system');
1377
+ // Initialize memory database with fallback support
1378
+ try {
1379
+ // Import and initialize FallbackMemoryStore to create the database
1380
+ const { FallbackMemoryStore } = await import("../../../memory/fallback-store.js");
1381
+ const memoryStore = new FallbackMemoryStore();
1382
+ await memoryStore.initialize();
1383
+ if (memoryStore.isUsingFallback()) {
1384
+ printSuccess('✓ Initialized memory system (in-memory fallback for npx compatibility)');
1385
+ console.log(' 💡 For persistent storage, install locally: npm install claude-flow@alpha');
1386
+ } else {
1387
+ printSuccess('✓ Initialized memory database (.swarm/memory.db)');
1388
+ }
1389
+ memoryStore.close();
1390
+ } catch (err) {
1391
+ console.log(` ⚠️ Could not initialize memory system: ${err.message}`);
1392
+ console.log(' Memory will be initialized on first use');
1393
+ }
1394
+ // Initialize comprehensive hive-mind system
1395
+ console.log('\n🧠 Initializing Hive Mind System...');
1396
+ try {
1397
+ const hiveMindOptions = {
1398
+ config: {
1399
+ integration: {
1400
+ claudeCode: {
1401
+ enabled: isClaudeCodeInstalled()
1402
+ },
1403
+ mcpTools: {
1404
+ enabled: true
1405
+ }
1406
+ },
1407
+ monitoring: {
1408
+ enabled: flags.monitoring || false
1409
+ }
1410
+ }
1411
+ };
1412
+ const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, dryRun1);
1413
+ if (hiveMindResult.success) {
1414
+ printSuccess(`✓ Hive Mind System initialized with ${hiveMindResult.features.length} features`);
1415
+ // Log individual features
1416
+ hiveMindResult.features.forEach((feature)=>{
1417
+ console.log(` • ${feature}`);
1418
+ });
1419
+ } else {
1420
+ console.log(` ⚠️ Hive Mind initialization failed: ${hiveMindResult.error}`);
1421
+ if (hiveMindResult.rollbackRequired) {
1422
+ console.log(' 🔄 Automatic rollback may be required');
1423
+ }
1424
+ }
1425
+ } catch (err) {
1426
+ console.log(` ⚠️ Could not initialize hive-mind system: ${err.message}`);
1427
+ }
1428
+ }
1429
+ // Update .gitignore with Claude Flow entries
1430
+ const gitignoreResult = await updateGitignore(workingDir, force, dryRun1);
1431
+ if (gitignoreResult.success) {
1432
+ if (!dryRun1) {
1433
+ printSuccess(`✓ ${gitignoreResult.message}`);
1434
+ } else {
1435
+ console.log(gitignoreResult.message);
1436
+ }
1640
1437
  } else {
1641
- console.log(` ⚠️ Hive Mind initialization failed: ${hiveMindResult.error}`);
1642
- if (hiveMindResult.rollbackRequired) {
1643
- console.log(' 🔄 Automatic rollback may be required');
1644
- }
1438
+ console.log(` ⚠️ ${gitignoreResult.message}`);
1645
1439
  }
1646
- } catch (err) {
1647
- console.log(` ⚠️ Could not initialize hive-mind system: ${err.message}`);
1648
- }
1649
- }
1650
-
1651
- // Update .gitignore with Claude Flow entries
1652
- const gitignoreResult = await updateGitignore(workingDir, force, dryRun);
1653
- if (gitignoreResult.success) {
1654
- if (!dryRun) {
1655
- printSuccess(`✓ ${gitignoreResult.message}`);
1656
- } else {
1657
- console.log(gitignoreResult.message);
1658
- }
1659
- } else {
1660
- console.log(` ⚠️ ${gitignoreResult.message}`);
1661
- }
1662
-
1663
- // SPARC initialization (only with --roo flag)
1664
- let sparcInitialized = false;
1665
- if (initSparc) {
1666
- console.log('\n🚀 Initializing SPARC development environment...');
1667
- try {
1668
- // Run create-sparc
1669
- console.log(' 🔄 Running: npx -y create-sparc init --force');
1670
- execSync('npx -y create-sparc init --force', {
1671
- cwd: workingDir,
1672
- stdio: 'inherit',
1673
- });
1674
- sparcInitialized = true;
1675
- printSuccess('✅ SPARC environment initialized successfully');
1676
- } catch (err) {
1677
- console.log(` ⚠️ Could not run create-sparc: ${err.message}`);
1678
- console.log(' SPARC features will be limited to basic functionality');
1679
- }
1680
- }
1681
-
1682
- // Create Claude slash commands for SPARC
1683
- if (sparcInitialized && !dryRun) {
1684
- console.log('\n📝 Creating Claude Code slash commands...');
1685
- await createClaudeSlashCommands(workingDir);
1686
- }
1687
-
1688
- // Check for Claude Code and set up MCP servers (always enabled by default)
1689
- if (!dryRun && isClaudeCodeInstalled()) {
1690
- console.log('\n🔍 Claude Code CLI detected!');
1691
- const skipMcp =
1692
- (options && options['skip-mcp']) ||
1693
- (subArgs && subArgs.includes && subArgs.includes('--skip-mcp'));
1694
-
1695
- if (!skipMcp) {
1696
- // Use bulletproof MCP setup for enhanced init
1697
- const mcpSuccess = await setupBulletproofMcp({
1698
- verbose: true,
1699
- autoFix: true,
1700
- dryRun: dryRun
1701
- });
1702
-
1703
- if (!mcpSuccess) {
1704
- console.log(' 💡 If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
1440
+ // SPARC initialization (only with --roo flag)
1441
+ let sparcInitialized = false;
1442
+ if (initSparc) {
1443
+ console.log('\n🚀 Initializing SPARC development environment...');
1444
+ try {
1445
+ // Run create-sparc
1446
+ console.log(' 🔄 Running: npx -y create-sparc init --force');
1447
+ execSync('npx -y create-sparc init --force', {
1448
+ cwd: workingDir,
1449
+ stdio: 'inherit'
1450
+ });
1451
+ sparcInitialized = true;
1452
+ printSuccess('✅ SPARC environment initialized successfully');
1453
+ } catch (err) {
1454
+ console.log(` ⚠️ Could not run create-sparc: ${err.message}`);
1455
+ console.log(' SPARC features will be limited to basic functionality');
1456
+ }
1705
1457
  }
1706
- } else {
1707
- console.log(' ℹ️ Skipping MCP setup (--skip-mcp flag used)');
1708
- console.log('\n 📋 To add MCP servers manually:');
1709
- console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1710
- console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1711
- // Flow-nexus integration removed
1712
- console.log('\n 💡 MCP servers are defined in .mcp.json (project scope)');
1713
- }
1714
- } else if (!dryRun && !isClaudeCodeInstalled()) {
1715
- console.log('\n⚠️ Claude Code CLI not detected!');
1716
- console.log('\n 📥 To install Claude Code:');
1717
- console.log(' npm install -g @anthropic-ai/claude-code');
1718
- console.log('\n 📋 After installing, add MCP servers:');
1719
- console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1720
- console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1721
- // Flow-nexus integration removed
1722
- console.log('\n 💡 MCP servers are defined in .mcp.json (project scope)');
1723
- }
1724
-
1725
- // Create agent directories and copy all agent files
1726
- console.log('\n🤖 Setting up agent system...');
1727
- if (!dryRun) {
1728
- await createAgentDirectories(workingDir, dryRun);
1729
- const agentResult = await copyAgentFiles(workingDir, {
1730
- force: force,
1731
- dryRun: dryRun,
1732
- });
1733
-
1734
- if (agentResult.success) {
1735
- await validateAgentSystem(workingDir);
1736
-
1737
- // Copy command files including Flow Nexus commands
1738
- console.log('\n📚 Setting up command system...');
1739
- const commandResult = await copyCommandFiles(workingDir, {
1740
- force: force,
1741
- dryRun: dryRun,
1742
- });
1743
-
1744
- if (commandResult.success) {
1745
- console.log('✅ ✓ Command system setup complete with Flow Nexus integration');
1458
+ // Create Claude slash commands for SPARC
1459
+ if (sparcInitialized && !dryRun1) {
1460
+ console.log('\n📝 Creating Claude Code slash commands...');
1461
+ await createClaudeSlashCommands(workingDir);
1462
+ }
1463
+ // Check for Claude Code and set up MCP servers (always enabled by default)
1464
+ if (!dryRun1 && isClaudeCodeInstalled()) {
1465
+ console.log('\n🔍 Claude Code CLI detected!');
1466
+ const skipMcp = options && options['skip-mcp'] || subArgs && subArgs.includes && subArgs.includes('--skip-mcp');
1467
+ if (!skipMcp) {
1468
+ // Use bulletproof MCP setup for enhanced init
1469
+ const mcpSuccess = await setupBulletproofMcp({
1470
+ verbose: true,
1471
+ autoFix: true,
1472
+ dryRun: dryRun1
1473
+ });
1474
+ if (!mcpSuccess) {
1475
+ console.log(' 💡 If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
1476
+ }
1477
+ } else {
1478
+ console.log(' ℹ️ Skipping MCP setup (--skip-mcp flag used)');
1479
+ console.log('\n 📋 To add MCP servers manually:');
1480
+ console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1481
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1482
+ // Flow-nexus integration removed
1483
+ console.log('\n 💡 MCP servers are defined in .mcp.json (project scope)');
1484
+ }
1485
+ } else if (!dryRun1 && !isClaudeCodeInstalled()) {
1486
+ console.log('\n⚠️ Claude Code CLI not detected!');
1487
+ console.log('\n 📥 To install Claude Code:');
1488
+ console.log(' npm install -g @anthropic-ai/claude-code');
1489
+ console.log('\n 📋 After installing, add MCP servers:');
1490
+ console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1491
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1492
+ // Flow-nexus integration removed
1493
+ console.log('\n 💡 MCP servers are defined in .mcp.json (project scope)');
1494
+ }
1495
+ // Create agent directories and copy all agent files
1496
+ console.log('\n🤖 Setting up agent system...');
1497
+ if (!dryRun1) {
1498
+ await createAgentDirectories(workingDir, dryRun1);
1499
+ const agentResult = await copyAgentFiles(workingDir, {
1500
+ force: force,
1501
+ dryRun: dryRun1
1502
+ });
1503
+ if (agentResult.success) {
1504
+ await validateAgentSystem(workingDir);
1505
+ // Copy command files including Flow Nexus commands
1506
+ console.log('\n📚 Setting up command system...');
1507
+ const commandResult = await copyCommandFiles(workingDir, {
1508
+ force: force,
1509
+ dryRun: dryRun1
1510
+ });
1511
+ if (commandResult.success) {
1512
+ console.log('✅ ✓ Command system setup complete with Flow Nexus integration');
1513
+ } else {
1514
+ console.log('⚠️ Command system setup failed:', commandResult.error);
1515
+ }
1516
+ console.log('✅ ✓ Agent system setup complete with 64 specialized agents');
1517
+ } else {
1518
+ console.log('⚠️ Agent system setup failed:', agentResult.error);
1519
+ }
1520
+ // Setup hooks system for novice users
1521
+ console.log('\n🪝 Setting up hooks system...');
1522
+ const hooksConfig = {
1523
+ hooks: {
1524
+ pre_task: {
1525
+ enabled: true,
1526
+ command: "npx claude-flow-novice hooks pre-task --description \"$TASK_DESCRIPTION\"",
1527
+ description: "Pre-task coordination hook"
1528
+ },
1529
+ post_edit: {
1530
+ enabled: true,
1531
+ command: "npx claude-flow-novice hooks post-edit --file \"$FILE_PATH\" --memory-key \"swarm/$AGENT_ID/$STEP\"",
1532
+ description: "Post-edit memory storage hook"
1533
+ },
1534
+ post_task: {
1535
+ enabled: true,
1536
+ command: "npx claude-flow-novice hooks post-task --task-id \"$TASK_ID\"",
1537
+ description: "Post-task completion hook"
1538
+ }
1539
+ },
1540
+ memory: {
1541
+ enabled: true,
1542
+ persistence: "local",
1543
+ namespace: "claude-flow-novice"
1544
+ }
1545
+ };
1546
+ const hooksConfigPath = `${claudeDir}/hooks.json`;
1547
+ await fs.writeFile(hooksConfigPath, JSON.stringify(hooksConfig, null, 2), 'utf8');
1548
+ console.log('✅ ✓ Hooks system setup complete with automated coordination');
1746
1549
  } else {
1747
- console.log('⚠️ Command system setup failed:', commandResult.error);
1550
+ console.log(' [DRY RUN] Would create agent system with 64 specialized agents');
1551
+ console.log(' [DRY RUN] Would create hooks system with automated coordination');
1748
1552
  }
1749
-
1750
- console.log('✅ Agent system setup complete with 64 specialized agents');
1751
- } else {
1752
- console.log('⚠️ Agent system setup failed:', agentResult.error);
1753
- }
1754
-
1755
- // Setup hooks system for novice users
1756
- console.log('\n🪝 Setting up hooks system...');
1757
- const hooksConfig = {
1758
- hooks: {
1759
- pre_task: {
1760
- enabled: true,
1761
- command: "npx claude-flow-novice hooks pre-task --description \"$TASK_DESCRIPTION\"",
1762
- description: "Pre-task coordination hook"
1763
- },
1764
- post_edit: {
1765
- enabled: true,
1766
- command: "npx claude-flow-novice hooks post-edit --file \"$FILE_PATH\" --memory-key \"swarm/$AGENT_ID/$STEP\"",
1767
- description: "Post-edit memory storage hook"
1768
- },
1769
- post_task: {
1770
- enabled: true,
1771
- command: "npx claude-flow-novice hooks post-task --task-id \"$TASK_ID\"",
1772
- description: "Post-task completion hook"
1773
- }
1774
- },
1775
- memory: {
1776
- enabled: true,
1777
- persistence: "local",
1778
- namespace: "claude-flow-novice"
1553
+ // Optional: Setup monitoring and telemetry
1554
+ const enableMonitoring = flags.monitoring || flags['enable-monitoring'];
1555
+ if (enableMonitoring && !dryRun1) {
1556
+ console.log('\n📊 Setting up monitoring and telemetry...');
1557
+ await setupMonitoring(workingDir);
1779
1558
  }
1780
- };
1781
-
1782
- const hooksConfigPath = `${claudeDir}/hooks.json`;
1783
- await fs.writeFile(hooksConfigPath, JSON.stringify(hooksConfig, null, 2), 'utf8');
1784
- console.log(' Hooks system setup complete with automated coordination');
1785
-
1786
- } else {
1787
- console.log(' [DRY RUN] Would create agent system with 64 specialized agents');
1788
- console.log(' [DRY RUN] Would create hooks system with automated coordination');
1789
- }
1790
-
1791
- // Optional: Setup monitoring and telemetry
1792
- const enableMonitoring = flags.monitoring || flags['enable-monitoring'];
1793
- if (enableMonitoring && !dryRun) {
1794
- console.log('\n📊 Setting up monitoring and telemetry...');
1795
- await setupMonitoring(workingDir);
1796
- }
1797
-
1798
- // Final instructions with hive-mind status
1799
- console.log('\n🎉 Claude Flow v2.0.0 initialization complete!');
1800
-
1801
- // Display MCP setup status prominently
1802
- if (mcpSuccess) {
1803
- console.log('\n🛡️ Bulletproof MCP Configuration Status:');
1804
- console.log(' MCP server successfully configured with auto-recovery');
1805
- console.log(' Conflict detection and resolution enabled');
1806
- console.log(' Automatic backup and rollback capability active');
1807
- console.log(' ✅ Project-specific configuration created (.mcp.json)');
1808
- } else {
1809
- console.log('\n⚠️ MCP Configuration Status:');
1810
- console.log(' ⚠️ MCP setup completed with fallback configuration');
1811
- console.log(' 💡 Run health check: npx claude-flow-novice mcp health');
1812
- }
1813
-
1814
- // Display hive-mind status
1815
- const hiveMindStatus = getHiveMindStatus(workingDir);
1816
- console.log('\n🧠 Hive Mind System Status:');
1817
- console.log(` Configuration: ${hiveMindStatus.configured ? '✅ Ready' : '❌ Missing'}`);
1818
- console.log(
1819
- ` Database: ${hiveMindStatus.database === 'sqlite' ? '✅ SQLite' : hiveMindStatus.database === 'fallback' ? '⚠️ JSON Fallback' : '❌ Not initialized'}`,
1820
- );
1821
- console.log(
1822
- ` Directory Structure: ${hiveMindStatus.directories ? '✅ Created' : '❌ Missing'}`,
1823
- );
1824
-
1825
- console.log('\n📚 Quick Start:');
1826
- if (isClaudeCodeInstalled()) {
1827
- console.log('1. Verify MCP setup: claude mcp list');
1828
- console.log('2. View available commands: ls .claude/commands/');
1829
- console.log('3. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1830
- console.log('4. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1831
- console.log('5. Use enhanced MCP tools in Claude Code for bulletproof coordination');
1832
- if (hiveMindStatus.configured) {
1833
- console.log('5. Initialize first swarm: npx claude-flow-novice hive-mind init');
1834
- }
1835
- } else {
1836
- console.log('1. Install Claude Code: npm install -g @anthropic-ai/claude-code');
1837
- console.log('2. Add MCP servers (see instructions above)');
1838
- console.log('3. View available commands: ls .claude/commands/');
1839
- console.log('4. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1840
- console.log('5. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1841
- if (hiveMindStatus.configured) {
1842
- console.log('6. Initialize first swarm: npx claude-flow-novice hive-mind init');
1843
- }
1844
- }
1845
- console.log('\n💡 Tips:');
1846
- console.log('• Check .claude/commands/ for detailed documentation');
1847
- console.log('• Use --help with any command for options');
1848
- console.log('• Run commands with --claude flag for best Claude Code integration');
1849
- if (mcpSuccess) {
1850
- console.log('• MCP health check: npx claude-flow-novice mcp health');
1851
- console.log('• Configuration backups are automatically created for safety');
1852
- console.log('• Project-specific .mcp.json prevents conflicts with other projects');
1853
- }
1854
- console.log('• Enable GitHub integration with .claude/helpers/github-setup.sh');
1855
- console.log('• Git checkpoints are automatically enabled in settings.json');
1856
- console.log('• Use .claude/helpers/checkpoint-manager.sh for easy rollback');
1857
- } catch (err) {
1858
- printError(`Failed to initialize Claude Flow v2.0.0: ${err.message}`);
1859
-
1860
- // Attempt hive-mind rollback if it was partially initialized
1861
- try {
1862
- const hiveMindStatus = getHiveMindStatus(workingDir);
1863
- if (hiveMindStatus.directories || hiveMindStatus.configured) {
1864
- console.log('\n🔄 Attempting hive-mind system rollback...');
1865
- const rollbackResult = await rollbackHiveMindInit(workingDir);
1866
- if (rollbackResult.success) {
1867
- console.log(' ✅ Hive-mind rollback completed');
1559
+ // Final instructions with hive-mind status
1560
+ console.log('\n🎉 Claude Flow v2.0.0 initialization complete!');
1561
+ // Display MCP setup status prominently
1562
+ if (mcpSuccess) {
1563
+ console.log('\n🛡️ Bulletproof MCP Configuration Status:');
1564
+ console.log(' ✅ MCP server successfully configured with auto-recovery');
1565
+ console.log(' ✅ Conflict detection and resolution enabled');
1566
+ console.log(' Automatic backup and rollback capability active');
1567
+ console.log(' Project-specific configuration created (.mcp.json)');
1568
+ } else {
1569
+ console.log('\n⚠️ MCP Configuration Status:');
1570
+ console.log(' ⚠️ MCP setup completed with fallback configuration');
1571
+ console.log(' 💡 Run health check: npx claude-flow-novice mcp health');
1572
+ }
1573
+ // Display hive-mind status
1574
+ const hiveMindStatus = getHiveMindStatus(workingDir);
1575
+ console.log('\n🧠 Hive Mind System Status:');
1576
+ console.log(` Configuration: ${hiveMindStatus.configured ? '✅ Ready' : '❌ Missing'}`);
1577
+ console.log(` Database: ${hiveMindStatus.database === 'sqlite' ? '✅ SQLite' : hiveMindStatus.database === 'fallback' ? '⚠️ JSON Fallback' : '❌ Not initialized'}`);
1578
+ console.log(` Directory Structure: ${hiveMindStatus.directories ? '✅ Created' : '❌ Missing'}`);
1579
+ console.log('\n📚 Quick Start:');
1580
+ if (isClaudeCodeInstalled()) {
1581
+ console.log('1. Verify MCP setup: claude mcp list');
1582
+ console.log('2. View available commands: ls .claude/commands/');
1583
+ console.log('3. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1584
+ console.log('4. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1585
+ console.log('5. Use enhanced MCP tools in Claude Code for bulletproof coordination');
1586
+ if (hiveMindStatus.configured) {
1587
+ console.log('5. Initialize first swarm: npx claude-flow-novice hive-mind init');
1588
+ }
1868
1589
  } else {
1869
- console.log(` ⚠️ Hive-mind rollback failed: ${rollbackResult.error}`);
1590
+ console.log('1. Install Claude Code: npm install -g @anthropic-ai/claude-code');
1591
+ console.log('2. Add MCP servers (see instructions above)');
1592
+ console.log('3. View available commands: ls .claude/commands/');
1593
+ console.log('4. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1594
+ console.log('5. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1595
+ if (hiveMindStatus.configured) {
1596
+ console.log('6. Initialize first swarm: npx claude-flow-novice hive-mind init');
1597
+ }
1598
+ }
1599
+ console.log('\n💡 Tips:');
1600
+ console.log('• Check .claude/commands/ for detailed documentation');
1601
+ console.log('• Use --help with any command for options');
1602
+ console.log('• Run commands with --claude flag for best Claude Code integration');
1603
+ if (mcpSuccess) {
1604
+ console.log('• MCP health check: npx claude-flow-novice mcp health');
1605
+ console.log('• Configuration backups are automatically created for safety');
1606
+ console.log('• Project-specific .mcp.json prevents conflicts with other projects');
1607
+ }
1608
+ console.log('• Enable GitHub integration with .claude/helpers/github-setup.sh');
1609
+ console.log('• Git checkpoints are automatically enabled in settings.json');
1610
+ console.log('• Use .claude/helpers/checkpoint-manager.sh for easy rollback');
1611
+ } catch (err) {
1612
+ printError(`Failed to initialize Claude Flow v2.0.0: ${err.message}`);
1613
+ // Attempt hive-mind rollback if it was partially initialized
1614
+ try {
1615
+ const hiveMindStatus = getHiveMindStatus(workingDir);
1616
+ if (hiveMindStatus.directories || hiveMindStatus.configured) {
1617
+ console.log('\n🔄 Attempting hive-mind system rollback...');
1618
+ const rollbackResult = await rollbackHiveMindInit(workingDir);
1619
+ if (rollbackResult.success) {
1620
+ console.log(' ✅ Hive-mind rollback completed');
1621
+ } else {
1622
+ console.log(` ⚠️ Hive-mind rollback failed: ${rollbackResult.error}`);
1623
+ }
1624
+ }
1625
+ } catch (rollbackErr) {
1626
+ console.log(` ⚠️ Rollback error: ${rollbackErr.message}`);
1870
1627
  }
1871
- }
1872
- } catch (rollbackErr) {
1873
- console.log(` ⚠️ Rollback error: ${rollbackErr.message}`);
1874
1628
  }
1875
- }
1876
- }
1877
-
1878
- // Flow Nexus initialization removed
1629
+ } // Flow Nexus initialization removed