moflo 4.8.31 → 4.8.33

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 (415) hide show
  1. package/package.json +13 -10
  2. package/src/@claude-flow/cli/dist/src/commands/doctor.js +1298 -1107
  3. package/src/@claude-flow/cli/dist/src/memory/memory-initializer.js +4 -7
  4. package/src/@claude-flow/cli/package.json +106 -106
  5. package/src/@claude-flow/neural/README.md +260 -0
  6. package/src/@claude-flow/neural/dist/algorithms/a2c.js +361 -0
  7. package/src/@claude-flow/neural/dist/algorithms/curiosity.js +392 -0
  8. package/src/@claude-flow/neural/dist/algorithms/decision-transformer.js +415 -0
  9. package/src/@claude-flow/neural/dist/algorithms/dqn.js +303 -0
  10. package/src/@claude-flow/neural/dist/algorithms/index.js +74 -0
  11. package/src/@claude-flow/neural/dist/algorithms/ppo.js +331 -0
  12. package/src/@claude-flow/neural/dist/algorithms/q-learning.js +259 -0
  13. package/src/@claude-flow/neural/dist/algorithms/sarsa.js +297 -0
  14. package/src/@claude-flow/neural/dist/application/index.js +7 -0
  15. package/src/@claude-flow/neural/dist/application/services/neural-application-service.js +161 -0
  16. package/src/@claude-flow/neural/dist/domain/entities/pattern.js +134 -0
  17. package/src/@claude-flow/neural/dist/domain/index.js +8 -0
  18. package/src/@claude-flow/neural/dist/domain/services/learning-service.js +195 -0
  19. package/src/@claude-flow/neural/dist/index.js +201 -0
  20. package/src/@claude-flow/neural/dist/modes/balanced.js +234 -0
  21. package/src/@claude-flow/neural/dist/modes/base.js +77 -0
  22. package/src/@claude-flow/neural/dist/modes/batch.js +316 -0
  23. package/src/@claude-flow/neural/dist/modes/edge.js +310 -0
  24. package/src/@claude-flow/neural/dist/modes/index.js +13 -0
  25. package/src/@claude-flow/neural/dist/modes/real-time.js +196 -0
  26. package/src/@claude-flow/neural/dist/modes/research.js +389 -0
  27. package/src/@claude-flow/neural/dist/pattern-learner.js +603 -0
  28. package/src/@claude-flow/neural/dist/reasoning-bank.js +993 -0
  29. package/src/@claude-flow/neural/dist/reasoningbank-adapter.js +463 -0
  30. package/src/@claude-flow/neural/dist/sona-integration.js +316 -0
  31. package/src/@claude-flow/neural/dist/sona-manager.js +695 -0
  32. package/src/@claude-flow/neural/dist/types.js +11 -0
  33. package/src/@claude-flow/neural/package.json +26 -0
  34. package/.claude/agents/browser/browser-agent.yaml +0 -182
  35. package/.claude/agents/database-specialist.yaml +0 -21
  36. package/.claude/agents/index.yaml +0 -17
  37. package/.claude/agents/project-coordinator.yaml +0 -15
  38. package/.claude/agents/python-specialist.yaml +0 -21
  39. package/.claude/agents/security-auditor.yaml +0 -20
  40. package/.claude/agents/typescript-specialist.yaml +0 -21
  41. package/.claude/checkpoints/1767754460.json +0 -8
  42. package/.claude/config/v3-dependency-optimization.json +0 -266
  43. package/.claude/config/v3-performance-targets.json +0 -251
  44. package/.claude/guidance/moflo-bootstrap.md +0 -129
  45. package/.claude/mcp.json +0 -13
  46. package/.claude/settings.json +0 -351
  47. package/.claude/settings.local.json +0 -18
  48. package/.claude/skills/agentdb-advanced/SKILL.md +0 -550
  49. package/.claude/skills/agentdb-learning/SKILL.md +0 -545
  50. package/.claude/skills/agentdb-memory-patterns/SKILL.md +0 -339
  51. package/.claude/skills/agentdb-optimization/SKILL.md +0 -509
  52. package/.claude/skills/agentdb-vector-search/SKILL.md +0 -339
  53. package/.claude/skills/browser/SKILL.md +0 -204
  54. package/.claude/skills/fl/SKILL.md +0 -583
  55. package/.claude/skills/flo/SKILL.md +0 -583
  56. package/.claude/skills/github-code-review/SKILL.md +0 -1140
  57. package/.claude/skills/github-multi-repo/SKILL.md +0 -874
  58. package/.claude/skills/github-project-management/SKILL.md +0 -1277
  59. package/.claude/skills/github-release-management/SKILL.md +0 -1081
  60. package/.claude/skills/github-workflow-automation/SKILL.md +0 -1065
  61. package/.claude/skills/hive-mind-advanced/SKILL.md +0 -712
  62. package/.claude/skills/hooks-automation/SKILL.md +0 -1201
  63. package/.claude/skills/pair-programming/SKILL.md +0 -1202
  64. package/.claude/skills/performance-analysis/SKILL.md +0 -563
  65. package/.claude/skills/reasoningbank-agentdb/SKILL.md +0 -446
  66. package/.claude/skills/reasoningbank-intelligence/SKILL.md +0 -201
  67. package/.claude/skills/skill-builder/SKILL.md +0 -910
  68. package/.claude/skills/sparc-methodology/SKILL.md +0 -1115
  69. package/.claude/skills/stream-chain/SKILL.md +0 -563
  70. package/.claude/skills/swarm-advanced/SKILL.md +0 -973
  71. package/.claude/skills/swarm-orchestration/SKILL.md +0 -179
  72. package/.claude/skills/v3-cli-modernization/SKILL.md +0 -872
  73. package/.claude/skills/v3-core-implementation/SKILL.md +0 -797
  74. package/.claude/skills/v3-ddd-architecture/SKILL.md +0 -442
  75. package/.claude/skills/v3-integration-deep/SKILL.md +0 -241
  76. package/.claude/skills/v3-mcp-optimization/SKILL.md +0 -777
  77. package/.claude/skills/v3-memory-unification/SKILL.md +0 -174
  78. package/.claude/skills/v3-performance-optimization/SKILL.md +0 -390
  79. package/.claude/skills/v3-security-overhaul/SKILL.md +0 -82
  80. package/.claude/skills/v3-swarm-coordination/SKILL.md +0 -340
  81. package/.claude/skills/verification-quality/SKILL.md +0 -649
  82. package/.claude/skills/worker-benchmarks/skill.md +0 -135
  83. package/.claude/skills/worker-integration/skill.md +0 -154
  84. package/.claude/workflow-state.json +0 -9
  85. package/src/@claude-flow/cli/dist/src/appliance/gguf-engine.d.ts +0 -91
  86. package/src/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.d.ts +0 -102
  87. package/src/@claude-flow/cli/dist/src/appliance/rvfa-builder.d.ts +0 -44
  88. package/src/@claude-flow/cli/dist/src/appliance/rvfa-distribution.d.ts +0 -97
  89. package/src/@claude-flow/cli/dist/src/appliance/rvfa-format.d.ts +0 -111
  90. package/src/@claude-flow/cli/dist/src/appliance/rvfa-runner.d.ts +0 -69
  91. package/src/@claude-flow/cli/dist/src/appliance/rvfa-signing.d.ts +0 -123
  92. package/src/@claude-flow/cli/dist/src/benchmarks/pretrain/index.d.ts +0 -58
  93. package/src/@claude-flow/cli/dist/src/commands/agent.d.ts +0 -8
  94. package/src/@claude-flow/cli/dist/src/commands/analyze.d.ts +0 -19
  95. package/src/@claude-flow/cli/dist/src/commands/appliance-advanced.d.ts +0 -9
  96. package/src/@claude-flow/cli/dist/src/commands/appliance.d.ts +0 -8
  97. package/src/@claude-flow/cli/dist/src/commands/benchmark.d.ts +0 -10
  98. package/src/@claude-flow/cli/dist/src/commands/claims.d.ts +0 -10
  99. package/src/@claude-flow/cli/dist/src/commands/completions.d.ts +0 -10
  100. package/src/@claude-flow/cli/dist/src/commands/config.d.ts +0 -8
  101. package/src/@claude-flow/cli/dist/src/commands/daemon.d.ts +0 -8
  102. package/src/@claude-flow/cli/dist/src/commands/deployment.d.ts +0 -10
  103. package/src/@claude-flow/cli/dist/src/commands/diagnose.d.ts +0 -16
  104. package/src/@claude-flow/cli/dist/src/commands/doctor.d.ts +0 -10
  105. package/src/@claude-flow/cli/dist/src/commands/embeddings.d.ts +0 -18
  106. package/src/@claude-flow/cli/dist/src/commands/gate.d.ts +0 -23
  107. package/src/@claude-flow/cli/dist/src/commands/github.d.ts +0 -12
  108. package/src/@claude-flow/cli/dist/src/commands/guidance.d.ts +0 -8
  109. package/src/@claude-flow/cli/dist/src/commands/hive-mind.d.ts +0 -11
  110. package/src/@claude-flow/cli/dist/src/commands/hooks.d.ts +0 -8
  111. package/src/@claude-flow/cli/dist/src/commands/index.d.ts +0 -115
  112. package/src/@claude-flow/cli/dist/src/commands/init.d.ts +0 -8
  113. package/src/@claude-flow/cli/dist/src/commands/issues.d.ts +0 -21
  114. package/src/@claude-flow/cli/dist/src/commands/mcp.d.ts +0 -11
  115. package/src/@claude-flow/cli/dist/src/commands/memory.d.ts +0 -8
  116. package/src/@claude-flow/cli/dist/src/commands/migrate.d.ts +0 -8
  117. package/src/@claude-flow/cli/dist/src/commands/neural.d.ts +0 -10
  118. package/src/@claude-flow/cli/dist/src/commands/orc.d.ts +0 -21
  119. package/src/@claude-flow/cli/dist/src/commands/performance.d.ts +0 -10
  120. package/src/@claude-flow/cli/dist/src/commands/plugins.d.ts +0 -11
  121. package/src/@claude-flow/cli/dist/src/commands/process.d.ts +0 -10
  122. package/src/@claude-flow/cli/dist/src/commands/progress.d.ts +0 -11
  123. package/src/@claude-flow/cli/dist/src/commands/providers.d.ts +0 -10
  124. package/src/@claude-flow/cli/dist/src/commands/route.d.ts +0 -16
  125. package/src/@claude-flow/cli/dist/src/commands/ruvector/backup.d.ts +0 -11
  126. package/src/@claude-flow/cli/dist/src/commands/ruvector/benchmark.d.ts +0 -11
  127. package/src/@claude-flow/cli/dist/src/commands/ruvector/import.d.ts +0 -18
  128. package/src/@claude-flow/cli/dist/src/commands/ruvector/index.d.ts +0 -29
  129. package/src/@claude-flow/cli/dist/src/commands/ruvector/init.d.ts +0 -11
  130. package/src/@claude-flow/cli/dist/src/commands/ruvector/migrate.d.ts +0 -11
  131. package/src/@claude-flow/cli/dist/src/commands/ruvector/optimize.d.ts +0 -11
  132. package/src/@claude-flow/cli/dist/src/commands/ruvector/setup.d.ts +0 -18
  133. package/src/@claude-flow/cli/dist/src/commands/ruvector/status.d.ts +0 -11
  134. package/src/@claude-flow/cli/dist/src/commands/security.d.ts +0 -10
  135. package/src/@claude-flow/cli/dist/src/commands/session.d.ts +0 -8
  136. package/src/@claude-flow/cli/dist/src/commands/start.d.ts +0 -8
  137. package/src/@claude-flow/cli/dist/src/commands/status.d.ts +0 -8
  138. package/src/@claude-flow/cli/dist/src/commands/swarm.d.ts +0 -8
  139. package/src/@claude-flow/cli/dist/src/commands/task.d.ts +0 -8
  140. package/src/@claude-flow/cli/dist/src/commands/transfer-store.d.ts +0 -13
  141. package/src/@claude-flow/cli/dist/src/commands/update.d.ts +0 -8
  142. package/src/@claude-flow/cli/dist/src/commands/workflow.d.ts +0 -8
  143. package/src/@claude-flow/cli/dist/src/config/moflo-config.d.ts +0 -93
  144. package/src/@claude-flow/cli/dist/src/config-adapter.d.ts +0 -15
  145. package/src/@claude-flow/cli/dist/src/index.d.ts +0 -81
  146. package/src/@claude-flow/cli/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  147. package/src/@claude-flow/cli/dist/src/init/claudemd-generator.d.ts +0 -30
  148. package/src/@claude-flow/cli/dist/src/init/executor.d.ts +0 -41
  149. package/src/@claude-flow/cli/dist/src/init/helpers-generator.d.ts +0 -51
  150. package/src/@claude-flow/cli/dist/src/init/index.d.ts +0 -13
  151. package/src/@claude-flow/cli/dist/src/init/mcp-generator.d.ts +0 -29
  152. package/src/@claude-flow/cli/dist/src/init/moflo-init.d.ts +0 -31
  153. package/src/@claude-flow/cli/dist/src/init/settings-generator.d.ts +0 -14
  154. package/src/@claude-flow/cli/dist/src/init/statusline-generator.d.ts +0 -28
  155. package/src/@claude-flow/cli/dist/src/init/types.d.ts +0 -285
  156. package/src/@claude-flow/cli/dist/src/mcp-client.d.ts +0 -92
  157. package/src/@claude-flow/cli/dist/src/mcp-server.d.ts +0 -161
  158. package/src/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +0 -9
  159. package/src/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.d.ts +0 -30
  160. package/src/@claude-flow/cli/dist/src/mcp-tools/analyze-tools.d.ts +0 -38
  161. package/src/@claude-flow/cli/dist/src/mcp-tools/auto-install.d.ts +0 -83
  162. package/src/@claude-flow/cli/dist/src/mcp-tools/browser-tools.d.ts +0 -13
  163. package/src/@claude-flow/cli/dist/src/mcp-tools/claims-tools.d.ts +0 -12
  164. package/src/@claude-flow/cli/dist/src/mcp-tools/config-tools.d.ts +0 -8
  165. package/src/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.d.ts +0 -13
  166. package/src/@claude-flow/cli/dist/src/mcp-tools/daa-tools.d.ts +0 -13
  167. package/src/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.d.ts +0 -9
  168. package/src/@claude-flow/cli/dist/src/mcp-tools/github-tools.d.ts +0 -13
  169. package/src/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.d.ts +0 -8
  170. package/src/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.d.ts +0 -44
  171. package/src/@claude-flow/cli/dist/src/mcp-tools/index.d.ts +0 -23
  172. package/src/@claude-flow/cli/dist/src/mcp-tools/memory-tools.d.ts +0 -14
  173. package/src/@claude-flow/cli/dist/src/mcp-tools/neural-tools.d.ts +0 -16
  174. package/src/@claude-flow/cli/dist/src/mcp-tools/performance-tools.d.ts +0 -16
  175. package/src/@claude-flow/cli/dist/src/mcp-tools/progress-tools.d.ts +0 -14
  176. package/src/@claude-flow/cli/dist/src/mcp-tools/security-tools.d.ts +0 -18
  177. package/src/@claude-flow/cli/dist/src/mcp-tools/session-tools.d.ts +0 -8
  178. package/src/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.d.ts +0 -8
  179. package/src/@claude-flow/cli/dist/src/mcp-tools/system-tools.d.ts +0 -13
  180. package/src/@claude-flow/cli/dist/src/mcp-tools/task-tools.d.ts +0 -8
  181. package/src/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.d.ts +0 -13
  182. package/src/@claude-flow/cli/dist/src/mcp-tools/transfer-tools.d.ts +0 -14
  183. package/src/@claude-flow/cli/dist/src/mcp-tools/types.d.ts +0 -31
  184. package/src/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  185. package/src/@claude-flow/cli/dist/src/memory/ewc-consolidation.d.ts +0 -271
  186. package/src/@claude-flow/cli/dist/src/memory/intelligence.d.ts +0 -285
  187. package/src/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +0 -413
  188. package/src/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +0 -405
  189. package/src/@claude-flow/cli/dist/src/memory/sona-optimizer.d.ts +0 -227
  190. package/src/@claude-flow/cli/dist/src/output.d.ts +0 -133
  191. package/src/@claude-flow/cli/dist/src/parser.d.ts +0 -51
  192. package/src/@claude-flow/cli/dist/src/plugins/manager.d.ts +0 -133
  193. package/src/@claude-flow/cli/dist/src/plugins/store/discovery.d.ts +0 -88
  194. package/src/@claude-flow/cli/dist/src/plugins/store/index.d.ts +0 -76
  195. package/src/@claude-flow/cli/dist/src/plugins/store/search.d.ts +0 -46
  196. package/src/@claude-flow/cli/dist/src/plugins/store/types.d.ts +0 -274
  197. package/src/@claude-flow/cli/dist/src/plugins/tests/demo-plugin-store.d.ts +0 -7
  198. package/src/@claude-flow/cli/dist/src/plugins/tests/standalone-test.d.ts +0 -12
  199. package/src/@claude-flow/cli/dist/src/plugins/tests/test-plugin-store.d.ts +0 -7
  200. package/src/@claude-flow/cli/dist/src/production/circuit-breaker.d.ts +0 -101
  201. package/src/@claude-flow/cli/dist/src/production/error-handler.d.ts +0 -92
  202. package/src/@claude-flow/cli/dist/src/production/index.d.ts +0 -23
  203. package/src/@claude-flow/cli/dist/src/production/monitoring.d.ts +0 -161
  204. package/src/@claude-flow/cli/dist/src/production/rate-limiter.d.ts +0 -80
  205. package/src/@claude-flow/cli/dist/src/production/retry.d.ts +0 -48
  206. package/src/@claude-flow/cli/dist/src/prompt.d.ts +0 -44
  207. package/src/@claude-flow/cli/dist/src/runtime/headless.d.ts +0 -60
  208. package/src/@claude-flow/cli/dist/src/ruvector/ast-analyzer.d.ts +0 -67
  209. package/src/@claude-flow/cli/dist/src/ruvector/coverage-router.d.ts +0 -160
  210. package/src/@claude-flow/cli/dist/src/ruvector/coverage-tools.d.ts +0 -33
  211. package/src/@claude-flow/cli/dist/src/ruvector/diff-classifier.d.ts +0 -175
  212. package/src/@claude-flow/cli/dist/src/ruvector/enhanced-model-router.d.ts +0 -146
  213. package/src/@claude-flow/cli/dist/src/ruvector/flash-attention.d.ts +0 -195
  214. package/src/@claude-flow/cli/dist/src/ruvector/graph-analyzer.d.ts +0 -187
  215. package/src/@claude-flow/cli/dist/src/ruvector/index.d.ts +0 -34
  216. package/src/@claude-flow/cli/dist/src/ruvector/lora-adapter.d.ts +0 -218
  217. package/src/@claude-flow/cli/dist/src/ruvector/model-router.d.ts +0 -220
  218. package/src/@claude-flow/cli/dist/src/ruvector/moe-router.d.ts +0 -206
  219. package/src/@claude-flow/cli/dist/src/ruvector/q-learning-router.d.ts +0 -211
  220. package/src/@claude-flow/cli/dist/src/ruvector/semantic-router.d.ts +0 -77
  221. package/src/@claude-flow/cli/dist/src/ruvector/vector-db.d.ts +0 -69
  222. package/src/@claude-flow/cli/dist/src/services/agent-router.d.ts +0 -63
  223. package/src/@claude-flow/cli/dist/src/services/agentic-flow-bridge.d.ts +0 -50
  224. package/src/@claude-flow/cli/dist/src/services/claim-service.d.ts +0 -204
  225. package/src/@claude-flow/cli/dist/src/services/container-worker-pool.d.ts +0 -197
  226. package/src/@claude-flow/cli/dist/src/services/daemon-lock.d.ts +0 -60
  227. package/src/@claude-flow/cli/dist/src/services/headless-worker-executor.d.ts +0 -304
  228. package/src/@claude-flow/cli/dist/src/services/index.d.ts +0 -13
  229. package/src/@claude-flow/cli/dist/src/services/learning-service.d.ts +0 -161
  230. package/src/@claude-flow/cli/dist/src/services/moflo-require.d.ts +0 -34
  231. package/src/@claude-flow/cli/dist/src/services/registry-api.d.ts +0 -58
  232. package/src/@claude-flow/cli/dist/src/services/ruvector-training.d.ts +0 -214
  233. package/src/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +0 -225
  234. package/src/@claude-flow/cli/dist/src/services/worker-queue.d.ts +0 -194
  235. package/src/@claude-flow/cli/dist/src/services/workflow-gate.d.ts +0 -88
  236. package/src/@claude-flow/cli/dist/src/suggest.d.ts +0 -53
  237. package/src/@claude-flow/cli/dist/src/transfer/anonymization/index.d.ts +0 -25
  238. package/src/@claude-flow/cli/dist/src/transfer/deploy-seraphine.d.ts +0 -13
  239. package/src/@claude-flow/cli/dist/src/transfer/export.d.ts +0 -25
  240. package/src/@claude-flow/cli/dist/src/transfer/index.d.ts +0 -12
  241. package/src/@claude-flow/cli/dist/src/transfer/ipfs/client.d.ts +0 -109
  242. package/src/@claude-flow/cli/dist/src/transfer/ipfs/upload.d.ts +0 -95
  243. package/src/@claude-flow/cli/dist/src/transfer/models/seraphine.d.ts +0 -72
  244. package/src/@claude-flow/cli/dist/src/transfer/serialization/cfp.d.ts +0 -49
  245. package/src/@claude-flow/cli/dist/src/transfer/storage/gcs.d.ts +0 -82
  246. package/src/@claude-flow/cli/dist/src/transfer/storage/index.d.ts +0 -6
  247. package/src/@claude-flow/cli/dist/src/transfer/store/discovery.d.ts +0 -84
  248. package/src/@claude-flow/cli/dist/src/transfer/store/download.d.ts +0 -70
  249. package/src/@claude-flow/cli/dist/src/transfer/store/index.d.ts +0 -84
  250. package/src/@claude-flow/cli/dist/src/transfer/store/publish.d.ts +0 -76
  251. package/src/@claude-flow/cli/dist/src/transfer/store/registry.d.ts +0 -58
  252. package/src/@claude-flow/cli/dist/src/transfer/store/search.d.ts +0 -54
  253. package/src/@claude-flow/cli/dist/src/transfer/store/tests/standalone-test.d.ts +0 -12
  254. package/src/@claude-flow/cli/dist/src/transfer/store/types.d.ts +0 -193
  255. package/src/@claude-flow/cli/dist/src/transfer/test-seraphine.d.ts +0 -6
  256. package/src/@claude-flow/cli/dist/src/transfer/tests/test-store.d.ts +0 -7
  257. package/src/@claude-flow/cli/dist/src/transfer/types.d.ts +0 -245
  258. package/src/@claude-flow/cli/dist/src/types.d.ts +0 -198
  259. package/src/@claude-flow/cli/dist/src/update/checker.d.ts +0 -34
  260. package/src/@claude-flow/cli/dist/src/update/executor.d.ts +0 -32
  261. package/src/@claude-flow/cli/dist/src/update/index.d.ts +0 -33
  262. package/src/@claude-flow/cli/dist/src/update/rate-limiter.d.ts +0 -20
  263. package/src/@claude-flow/cli/dist/src/update/validator.d.ts +0 -17
  264. package/src/@claude-flow/guidance/dist/adversarial.d.ts +0 -284
  265. package/src/@claude-flow/guidance/dist/analyzer.d.ts +0 -530
  266. package/src/@claude-flow/guidance/dist/artifacts.d.ts +0 -283
  267. package/src/@claude-flow/guidance/dist/authority.d.ts +0 -290
  268. package/src/@claude-flow/guidance/dist/capabilities.d.ts +0 -209
  269. package/src/@claude-flow/guidance/dist/coherence.d.ts +0 -233
  270. package/src/@claude-flow/guidance/dist/compiler.d.ts +0 -87
  271. package/src/@claude-flow/guidance/dist/conformance-kit.d.ts +0 -225
  272. package/src/@claude-flow/guidance/dist/continue-gate.d.ts +0 -214
  273. package/src/@claude-flow/guidance/dist/crypto-utils.d.ts +0 -17
  274. package/src/@claude-flow/guidance/dist/evolution.d.ts +0 -282
  275. package/src/@claude-flow/guidance/dist/gates.d.ts +0 -79
  276. package/src/@claude-flow/guidance/dist/gateway.d.ts +0 -206
  277. package/src/@claude-flow/guidance/dist/generators.d.ts +0 -153
  278. package/src/@claude-flow/guidance/dist/headless.d.ts +0 -177
  279. package/src/@claude-flow/guidance/dist/hooks.d.ts +0 -109
  280. package/src/@claude-flow/guidance/dist/index.d.ts +0 -205
  281. package/src/@claude-flow/guidance/dist/ledger.d.ts +0 -162
  282. package/src/@claude-flow/guidance/dist/manifest-validator.d.ts +0 -289
  283. package/src/@claude-flow/guidance/dist/memory-gate.d.ts +0 -222
  284. package/src/@claude-flow/guidance/dist/meta-governance.d.ts +0 -265
  285. package/src/@claude-flow/guidance/dist/optimizer.d.ts +0 -104
  286. package/src/@claude-flow/guidance/dist/persistence.d.ts +0 -189
  287. package/src/@claude-flow/guidance/dist/proof.d.ts +0 -185
  288. package/src/@claude-flow/guidance/dist/retriever.d.ts +0 -116
  289. package/src/@claude-flow/guidance/dist/ruvbot-integration.d.ts +0 -370
  290. package/src/@claude-flow/guidance/dist/temporal.d.ts +0 -426
  291. package/src/@claude-flow/guidance/dist/trust.d.ts +0 -283
  292. package/src/@claude-flow/guidance/dist/truth-anchors.d.ts +0 -276
  293. package/src/@claude-flow/guidance/dist/types.d.ts +0 -378
  294. package/src/@claude-flow/guidance/dist/uncertainty.d.ts +0 -372
  295. package/src/@claude-flow/guidance/dist/wasm-kernel.d.ts +0 -48
  296. package/src/@claude-flow/memory/dist/agent-memory-scope.d.ts +0 -131
  297. package/src/@claude-flow/memory/dist/agent-memory-scope.test.d.ts +0 -8
  298. package/src/@claude-flow/memory/dist/agentdb-adapter.d.ts +0 -165
  299. package/src/@claude-flow/memory/dist/agentdb-backend.d.ts +0 -212
  300. package/src/@claude-flow/memory/dist/agentdb-backend.test.d.ts +0 -7
  301. package/src/@claude-flow/memory/dist/application/commands/delete-memory.command.d.ts +0 -65
  302. package/src/@claude-flow/memory/dist/application/commands/store-memory.command.d.ts +0 -48
  303. package/src/@claude-flow/memory/dist/application/index.d.ts +0 -12
  304. package/src/@claude-flow/memory/dist/application/queries/search-memory.query.d.ts +0 -72
  305. package/src/@claude-flow/memory/dist/application/services/memory-application-service.d.ts +0 -121
  306. package/src/@claude-flow/memory/dist/auto-memory-bridge.d.ts +0 -226
  307. package/src/@claude-flow/memory/dist/auto-memory-bridge.test.d.ts +0 -8
  308. package/src/@claude-flow/memory/dist/benchmark.test.d.ts +0 -2
  309. package/src/@claude-flow/memory/dist/cache-manager.d.ts +0 -134
  310. package/src/@claude-flow/memory/dist/controller-registry.d.ts +0 -216
  311. package/src/@claude-flow/memory/dist/controller-registry.test.d.ts +0 -14
  312. package/src/@claude-flow/memory/dist/database-provider.d.ts +0 -87
  313. package/src/@claude-flow/memory/dist/database-provider.test.d.ts +0 -7
  314. package/src/@claude-flow/memory/dist/domain/entities/memory-entry.d.ts +0 -143
  315. package/src/@claude-flow/memory/dist/domain/index.d.ts +0 -11
  316. package/src/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.d.ts +0 -102
  317. package/src/@claude-flow/memory/dist/domain/services/memory-domain-service.d.ts +0 -105
  318. package/src/@claude-flow/memory/dist/hnsw-index.d.ts +0 -111
  319. package/src/@claude-flow/memory/dist/hnsw-lite.d.ts +0 -23
  320. package/src/@claude-flow/memory/dist/hybrid-backend.d.ts +0 -245
  321. package/src/@claude-flow/memory/dist/hybrid-backend.test.d.ts +0 -8
  322. package/src/@claude-flow/memory/dist/index.d.ts +0 -204
  323. package/src/@claude-flow/memory/dist/infrastructure/index.d.ts +0 -17
  324. package/src/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.d.ts +0 -66
  325. package/src/@claude-flow/memory/dist/learning-bridge.d.ts +0 -137
  326. package/src/@claude-flow/memory/dist/learning-bridge.test.d.ts +0 -8
  327. package/src/@claude-flow/memory/dist/memory-graph.d.ts +0 -100
  328. package/src/@claude-flow/memory/dist/memory-graph.test.d.ts +0 -8
  329. package/src/@claude-flow/memory/dist/migration.d.ts +0 -68
  330. package/src/@claude-flow/memory/dist/persistent-sona.d.ts +0 -144
  331. package/src/@claude-flow/memory/dist/query-builder.d.ts +0 -211
  332. package/src/@claude-flow/memory/dist/rvf-backend.d.ts +0 -51
  333. package/src/@claude-flow/memory/dist/rvf-learning-store.d.ts +0 -139
  334. package/src/@claude-flow/memory/dist/rvf-migration.d.ts +0 -45
  335. package/src/@claude-flow/memory/dist/sqlite-backend.d.ts +0 -121
  336. package/src/@claude-flow/memory/dist/sqljs-backend.d.ts +0 -127
  337. package/src/@claude-flow/memory/dist/types.d.ts +0 -484
  338. package/src/@claude-flow/shared/dist/core/config/defaults.d.ts +0 -41
  339. package/src/@claude-flow/shared/dist/core/config/index.d.ts +0 -8
  340. package/src/@claude-flow/shared/dist/core/config/loader.d.ts +0 -45
  341. package/src/@claude-flow/shared/dist/core/config/schema.d.ts +0 -1134
  342. package/src/@claude-flow/shared/dist/core/config/validator.d.ts +0 -92
  343. package/src/@claude-flow/shared/dist/core/event-bus.d.ts +0 -31
  344. package/src/@claude-flow/shared/dist/core/index.d.ts +0 -15
  345. package/src/@claude-flow/shared/dist/core/interfaces/agent.interface.d.ts +0 -200
  346. package/src/@claude-flow/shared/dist/core/interfaces/coordinator.interface.d.ts +0 -310
  347. package/src/@claude-flow/shared/dist/core/interfaces/event.interface.d.ts +0 -224
  348. package/src/@claude-flow/shared/dist/core/interfaces/index.d.ts +0 -10
  349. package/src/@claude-flow/shared/dist/core/interfaces/memory.interface.d.ts +0 -298
  350. package/src/@claude-flow/shared/dist/core/interfaces/task.interface.d.ts +0 -185
  351. package/src/@claude-flow/shared/dist/core/orchestrator/event-coordinator.d.ts +0 -35
  352. package/src/@claude-flow/shared/dist/core/orchestrator/health-monitor.d.ts +0 -60
  353. package/src/@claude-flow/shared/dist/core/orchestrator/index.d.ts +0 -46
  354. package/src/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.d.ts +0 -56
  355. package/src/@claude-flow/shared/dist/core/orchestrator/session-manager.d.ts +0 -83
  356. package/src/@claude-flow/shared/dist/core/orchestrator/task-manager.d.ts +0 -49
  357. package/src/@claude-flow/shared/dist/events/domain-events.d.ts +0 -282
  358. package/src/@claude-flow/shared/dist/events/event-store.d.ts +0 -126
  359. package/src/@claude-flow/shared/dist/events/event-store.test.d.ts +0 -8
  360. package/src/@claude-flow/shared/dist/events/example-usage.d.ts +0 -10
  361. package/src/@claude-flow/shared/dist/events/index.d.ts +0 -21
  362. package/src/@claude-flow/shared/dist/events/projections.d.ts +0 -177
  363. package/src/@claude-flow/shared/dist/events/rvf-event-log.d.ts +0 -82
  364. package/src/@claude-flow/shared/dist/events/state-reconstructor.d.ts +0 -101
  365. package/src/@claude-flow/shared/dist/events.d.ts +0 -80
  366. package/src/@claude-flow/shared/dist/hooks/example-usage.d.ts +0 -42
  367. package/src/@claude-flow/shared/dist/hooks/executor.d.ts +0 -100
  368. package/src/@claude-flow/shared/dist/hooks/hooks.test.d.ts +0 -9
  369. package/src/@claude-flow/shared/dist/hooks/index.d.ts +0 -52
  370. package/src/@claude-flow/shared/dist/hooks/registry.d.ts +0 -133
  371. package/src/@claude-flow/shared/dist/hooks/safety/bash-safety.d.ts +0 -105
  372. package/src/@claude-flow/shared/dist/hooks/safety/file-organization.d.ts +0 -144
  373. package/src/@claude-flow/shared/dist/hooks/safety/git-commit.d.ts +0 -158
  374. package/src/@claude-flow/shared/dist/hooks/safety/index.d.ts +0 -17
  375. package/src/@claude-flow/shared/dist/hooks/session-hooks.d.ts +0 -234
  376. package/src/@claude-flow/shared/dist/hooks/task-hooks.d.ts +0 -163
  377. package/src/@claude-flow/shared/dist/hooks/types.d.ts +0 -267
  378. package/src/@claude-flow/shared/dist/hooks/verify-exports.test.d.ts +0 -9
  379. package/src/@claude-flow/shared/dist/index.d.ts +0 -20
  380. package/src/@claude-flow/shared/dist/mcp/connection-pool.d.ts +0 -98
  381. package/src/@claude-flow/shared/dist/mcp/index.d.ts +0 -69
  382. package/src/@claude-flow/shared/dist/mcp/server.d.ts +0 -166
  383. package/src/@claude-flow/shared/dist/mcp/session-manager.d.ts +0 -136
  384. package/src/@claude-flow/shared/dist/mcp/tool-registry.d.ts +0 -178
  385. package/src/@claude-flow/shared/dist/mcp/transport/http.d.ts +0 -104
  386. package/src/@claude-flow/shared/dist/mcp/transport/index.d.ts +0 -102
  387. package/src/@claude-flow/shared/dist/mcp/transport/stdio.d.ts +0 -104
  388. package/src/@claude-flow/shared/dist/mcp/transport/websocket.d.ts +0 -133
  389. package/src/@claude-flow/shared/dist/mcp/types.d.ts +0 -438
  390. package/src/@claude-flow/shared/dist/plugin-interface.d.ts +0 -544
  391. package/src/@claude-flow/shared/dist/plugin-loader.d.ts +0 -139
  392. package/src/@claude-flow/shared/dist/plugin-registry.d.ts +0 -183
  393. package/src/@claude-flow/shared/dist/plugins/index.d.ts +0 -10
  394. package/src/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.d.ts +0 -106
  395. package/src/@claude-flow/shared/dist/plugins/official/index.d.ts +0 -10
  396. package/src/@claude-flow/shared/dist/plugins/official/maestro-plugin.d.ts +0 -121
  397. package/src/@claude-flow/shared/dist/plugins/types.d.ts +0 -93
  398. package/src/@claude-flow/shared/dist/resilience/bulkhead.d.ts +0 -105
  399. package/src/@claude-flow/shared/dist/resilience/circuit-breaker.d.ts +0 -132
  400. package/src/@claude-flow/shared/dist/resilience/index.d.ts +0 -19
  401. package/src/@claude-flow/shared/dist/resilience/rate-limiter.d.ts +0 -168
  402. package/src/@claude-flow/shared/dist/resilience/retry.d.ts +0 -91
  403. package/src/@claude-flow/shared/dist/security/index.d.ts +0 -10
  404. package/src/@claude-flow/shared/dist/security/input-validation.d.ts +0 -73
  405. package/src/@claude-flow/shared/dist/security/secure-random.d.ts +0 -92
  406. package/src/@claude-flow/shared/dist/services/index.d.ts +0 -7
  407. package/src/@claude-flow/shared/dist/services/v3-progress.service.d.ts +0 -124
  408. package/src/@claude-flow/shared/dist/types/agent.types.d.ts +0 -137
  409. package/src/@claude-flow/shared/dist/types/index.d.ts +0 -11
  410. package/src/@claude-flow/shared/dist/types/mcp.types.d.ts +0 -266
  411. package/src/@claude-flow/shared/dist/types/memory.types.d.ts +0 -236
  412. package/src/@claude-flow/shared/dist/types/swarm.types.d.ts +0 -186
  413. package/src/@claude-flow/shared/dist/types/task.types.d.ts +0 -178
  414. package/src/@claude-flow/shared/dist/types.d.ts +0 -197
  415. package/src/@claude-flow/shared/dist/utils/secure-logger.d.ts +0 -69
@@ -1,1108 +1,1299 @@
1
- /**
2
- * V3 CLI Doctor Command
3
- * System diagnostics, dependency checks, config validation
4
- *
5
- * Created with motailz.com
6
- */
7
- import { output } from '../output.js';
8
- import { existsSync, readFileSync, writeFileSync, unlinkSync, statSync, mkdirSync } from 'fs';
9
- import { join, dirname } from 'path';
10
- import { fileURLToPath } from 'url';
11
- import { execSync, exec } from 'child_process';
12
- import { promisify } from 'util';
13
- import { getDaemonLockHolder, releaseDaemonLock, isDaemonProcess } from '../services/daemon-lock.js';
14
- // Promisified exec with proper shell and env inheritance for cross-platform support
15
- const execAsync = promisify(exec);
16
- /**
17
- * Execute command asynchronously with proper environment inheritance
18
- * Critical for Windows where PATH may not be inherited properly
19
- */
20
- async function runCommand(command, timeoutMs = 5000) {
21
- const { stdout } = await execAsync(command, {
22
- encoding: 'utf8',
23
- timeout: timeoutMs,
24
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh', // Use proper shell per platform
25
- env: { ...process.env }, // Explicitly inherit full environment
26
- windowsHide: true, // Hide window on Windows
27
- });
28
- return stdout.trim();
29
- }
30
- // Check Node.js version
31
- async function checkNodeVersion() {
32
- const requiredMajor = 20;
33
- const version = process.version;
34
- const major = parseInt(version.slice(1).split('.')[0], 10);
35
- if (major >= requiredMajor) {
36
- return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` };
37
- }
38
- else if (major >= 18) {
39
- return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' };
40
- }
41
- else {
42
- return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' };
43
- }
44
- }
45
- // Check npm version (async with proper env inheritance)
46
- async function checkNpmVersion() {
47
- try {
48
- const version = await runCommand('npm --version');
49
- const major = parseInt(version.split('.')[0], 10);
50
- if (major >= 9) {
51
- return { name: 'npm Version', status: 'pass', message: `v${version}` };
52
- }
53
- else {
54
- return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' };
55
- }
56
- }
57
- catch {
58
- return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' };
59
- }
60
- }
61
- // Check config file
62
- async function checkConfigFile() {
63
- // JSON configs (parse-validated)
64
- const jsonPaths = [
65
- '.claude-flow/config.json',
66
- 'claude-flow.config.json',
67
- '.claude-flow.json'
68
- ];
69
- for (const configPath of jsonPaths) {
70
- if (existsSync(configPath)) {
71
- try {
72
- const content = readFileSync(configPath, 'utf8');
73
- JSON.parse(content);
74
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
75
- }
76
- catch (e) {
77
- return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' };
78
- }
79
- }
80
- }
81
- // YAML configs (existence-checked only — no heavy yaml parser dependency)
82
- const yamlPaths = [
83
- '.claude-flow/config.yaml',
84
- '.claude-flow/config.yml',
85
- 'claude-flow.config.yaml'
86
- ];
87
- for (const configPath of yamlPaths) {
88
- if (existsSync(configPath)) {
89
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
90
- }
91
- }
92
- return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' };
93
- }
94
- // Check daemon status — delegates to daemon-lock module for proper
95
- // PID + command-line verification (avoids Windows PID-recycling false positives).
96
- async function checkDaemonStatus() {
97
- try {
98
- // Retry up to 5 times with 1s delay — the daemon starts in the background
99
- // during session-start and may not have acquired its lock file yet.
100
- const MAX_RETRIES = 5;
101
- const RETRY_DELAY_MS = 1000;
102
- let holderPid = null;
103
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
104
- holderPid = getDaemonLockHolder(process.cwd());
105
- if (holderPid)
106
- break;
107
- if (attempt < MAX_RETRIES - 1) {
108
- await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
109
- }
110
- }
111
- if (holderPid) {
112
- return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${holderPid})` };
113
- }
114
- // getDaemonLockHolder auto-cleans stale locks, but check for legacy PID file
115
- const lockFile = '.claude-flow/daemon.lock';
116
- if (existsSync(lockFile)) {
117
- // Lock exists but holder is null — getDaemonLockHolder already cleaned it,
118
- // but if it persists it means cleanup failed (permissions, etc.)
119
- return { name: 'Daemon Status', status: 'warn', message: 'Stale lock file', fix: 'rm .claude-flow/daemon.lock && claude-flow daemon start' };
120
- }
121
- // Also check legacy PID file
122
- const pidFile = '.claude-flow/daemon.pid';
123
- if (existsSync(pidFile)) {
124
- return { name: 'Daemon Status', status: 'warn', message: 'Legacy PID file found', fix: 'rm .claude-flow/daemon.pid && claude-flow daemon start' };
125
- }
126
- return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' };
127
- }
128
- catch {
129
- return { name: 'Daemon Status', status: 'warn', message: 'Unable to check', fix: 'claude-flow daemon status' };
130
- }
131
- }
132
- // Check memory database
133
- async function checkMemoryDatabase() {
134
- const dbPaths = [
135
- '.claude-flow/memory.db',
136
- '.swarm/memory.db',
137
- 'data/memory.db'
138
- ];
139
- for (const dbPath of dbPaths) {
140
- if (existsSync(dbPath)) {
141
- try {
142
- const stats = statSync(dbPath);
143
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
144
- return { name: 'Memory Database', status: 'pass', message: `${dbPath} (${sizeMB} MB)` };
145
- }
146
- catch {
147
- return { name: 'Memory Database', status: 'warn', message: `${dbPath} (unable to stat)` };
148
- }
149
- }
150
- }
151
- return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
152
- }
153
- // Check git (async with proper env inheritance)
154
- async function checkGit() {
155
- try {
156
- const version = await runCommand('git --version');
157
- return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') };
158
- }
159
- catch {
160
- return { name: 'Git', status: 'warn', message: 'Not installed', fix: 'Install git from https://git-scm.com' };
161
- }
162
- }
163
- // Check if in git repo (async with proper env inheritance)
164
- async function checkGitRepo() {
165
- try {
166
- await runCommand('git rev-parse --git-dir');
167
- return { name: 'Git Repository', status: 'pass', message: 'In a git repository' };
168
- }
169
- catch {
170
- return { name: 'Git Repository', status: 'warn', message: 'Not a git repository', fix: 'git init' };
171
- }
172
- }
173
- // Check MCP servers
174
- async function checkMcpServers() {
175
- const mcpConfigPaths = [
176
- join(process.env.HOME || '', '.claude/claude_desktop_config.json'),
177
- join(process.env.HOME || '', '.config/claude/mcp.json'),
178
- '.mcp.json'
179
- ];
180
- for (const configPath of mcpConfigPaths) {
181
- if (existsSync(configPath)) {
182
- try {
183
- const content = JSON.parse(readFileSync(configPath, 'utf8'));
184
- const servers = content.mcpServers || content.servers || {};
185
- const count = Object.keys(servers).length;
186
- const hasClaudeFlow = 'moflo' in servers || 'claude-flow' in servers || 'claude-flow_alpha' in servers || 'ruflo' in servers || 'ruflo_alpha' in servers;
187
- if (hasClaudeFlow) {
188
- return { name: 'MCP Servers', status: 'pass', message: `${count} servers (flo configured)` };
189
- }
190
- else {
191
- return { name: 'MCP Servers', status: 'warn', message: `${count} servers (flo not found)`, fix: 'claude mcp add ruflo -- npx -y ruflo@latest mcp start' };
192
- }
193
- }
194
- catch {
195
- // continue to next path
196
- }
197
- }
198
- }
199
- return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add moflo npx moflo mcp start' };
200
- }
201
- // Check disk space (async with proper env inheritance)
202
- async function checkDiskSpace() {
203
- try {
204
- if (process.platform === 'win32') {
205
- return { name: 'Disk Space', status: 'pass', message: 'Check skipped on Windows' };
206
- }
207
- // Use df -Ph for POSIX mode (guarantees single-line output even with long device names)
208
- const output_str = await runCommand('df -Ph . | tail -1');
209
- const parts = output_str.split(/\s+/);
210
- // POSIX format: Filesystem Size Used Avail Capacity Mounted
211
- const available = parts[3];
212
- const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10);
213
- if (isNaN(usePercent)) {
214
- return { name: 'Disk Space', status: 'warn', message: `${available || 'unknown'} available (unable to parse usage)` };
215
- }
216
- if (usePercent > 90) {
217
- return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' };
218
- }
219
- else if (usePercent > 80) {
220
- return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` };
221
- }
222
- return { name: 'Disk Space', status: 'pass', message: `${available} available` };
223
- }
224
- catch {
225
- return { name: 'Disk Space', status: 'warn', message: 'Unable to check' };
226
- }
227
- }
228
- // Check TypeScript/build (async with proper env inheritance)
229
- async function checkBuildTools() {
230
- try {
231
- const tscVersion = await runCommand('npx tsc --version', 10000); // tsc can be slow
232
- if (!tscVersion || tscVersion.includes('not found')) {
233
- return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
234
- }
235
- return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') };
236
- }
237
- catch {
238
- return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
239
- }
240
- }
241
- // Check for stale npx cache (version freshness)
242
- async function checkVersionFreshness() {
243
- try {
244
- // Get current CLI version from package.json
245
- // Use import.meta.url to reliably locate our own package.json,
246
- // regardless of how deep the compiled file sits (e.g. dist/src/commands/).
247
- let currentVersion = '0.0.0';
248
- try {
249
- const thisFile = fileURLToPath(import.meta.url);
250
- let dir = dirname(thisFile);
251
- // Walk up from the current file's directory until we find the
252
- // package.json that belongs to @claude-flow/cli (or claude-flow/cli).
253
- // Walk until dirname(dir) === dir (filesystem root on any platform).
254
- for (;;) {
255
- const candidate = join(dir, 'package.json');
256
- try {
257
- if (existsSync(candidate)) {
258
- const pkg = JSON.parse(readFileSync(candidate, 'utf8'));
259
- if (pkg.version &&
260
- typeof pkg.name === 'string' &&
261
- (pkg.name === '@claude-flow/cli' || pkg.name === 'claude-flow' || pkg.name === 'ruflo' || pkg.name === 'moflo' || pkg.name === '@moflo/cli')) {
262
- currentVersion = pkg.version;
263
- break;
264
- }
265
- }
266
- }
267
- catch {
268
- // Unreadable/invalid JSON -- skip and keep walking up
269
- }
270
- const parent = dirname(dir);
271
- if (parent === dir)
272
- break; // reached root
273
- dir = parent;
274
- }
275
- }
276
- catch {
277
- // Fall back to a default
278
- currentVersion = '0.0.0';
279
- }
280
- // Check if running via npx (look for _npx in process path or argv)
281
- const isNpx = process.argv[1]?.includes('_npx') ||
282
- process.env.npm_execpath?.includes('npx') ||
283
- process.cwd().includes('_npx');
284
- // Query npm for latest version (using alpha tag since that's what we publish to)
285
- let latestVersion = currentVersion;
286
- try {
287
- const npmInfo = await runCommand('npm view moflo version', 5000);
288
- latestVersion = npmInfo.trim();
289
- }
290
- catch {
291
- // Can't reach npm registry - skip check
292
- return {
293
- name: 'Version Freshness',
294
- status: 'warn',
295
- message: `v${currentVersion} (cannot check registry)`
296
- };
297
- }
298
- // Parse version numbers for comparison (handle prerelease like 3.0.0-alpha.84)
299
- const parseVersion = (v) => {
300
- const match = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-[a-zA-Z]+\.(\d+))?/);
301
- if (!match)
302
- return { major: 0, minor: 0, patch: 0, prerelease: 0 };
303
- return {
304
- major: parseInt(match[1], 10) || 0,
305
- minor: parseInt(match[2], 10) || 0,
306
- patch: parseInt(match[3], 10) || 0,
307
- prerelease: parseInt(match[4], 10) || 0
308
- };
309
- };
310
- const current = parseVersion(currentVersion);
311
- const latest = parseVersion(latestVersion);
312
- // Compare versions (including prerelease number)
313
- const isOutdated = (latest.major > current.major ||
314
- (latest.major === current.major && latest.minor > current.minor) ||
315
- (latest.major === current.major && latest.minor === current.minor && latest.patch > current.patch) ||
316
- (latest.major === current.major && latest.minor === current.minor && latest.patch === current.patch && latest.prerelease > current.prerelease));
317
- if (isOutdated) {
318
- const fix = isNpx
319
- ? 'rm -rf ~/.npm/_npx/* && npx -y moflo'
320
- : 'npm update moflo';
321
- return {
322
- name: 'Version Freshness',
323
- status: 'warn',
324
- message: `v${currentVersion} (latest: v${latestVersion})${isNpx ? ' [npx cache stale]' : ''}`,
325
- fix
326
- };
327
- }
328
- return {
329
- name: 'Version Freshness',
330
- status: 'pass',
331
- message: `v${currentVersion} (up to date)`
332
- };
333
- }
334
- catch (error) {
335
- return {
336
- name: 'Version Freshness',
337
- status: 'warn',
338
- message: 'Unable to check version freshness'
339
- };
340
- }
341
- }
342
- // Check Claude Code CLI (async with proper env inheritance)
343
- async function checkClaudeCode() {
344
- try {
345
- const version = await runCommand('claude --version');
346
- // Parse version from output like "claude 1.0.0" or "Claude Code v1.0.0"
347
- const versionMatch = version.match(/v?(\d+\.\d+\.\d+)/);
348
- const versionStr = versionMatch ? `v${versionMatch[1]}` : version;
349
- return { name: 'Claude Code CLI', status: 'pass', message: versionStr };
350
- }
351
- catch {
352
- return {
353
- name: 'Claude Code CLI',
354
- status: 'warn',
355
- message: 'Not installed',
356
- fix: 'npm install -g @anthropic-ai/claude-code'
357
- };
358
- }
359
- }
360
- // Install Claude Code CLI
361
- async function installClaudeCode() {
362
- try {
363
- output.writeln();
364
- output.writeln(output.bold('Installing Claude Code CLI...'));
365
- execSync('npm install -g @anthropic-ai/claude-code', {
366
- encoding: 'utf8',
367
- stdio: 'inherit',
368
- windowsHide: true
369
- });
370
- output.writeln(output.success('Claude Code CLI installed successfully!'));
371
- return true;
372
- }
373
- catch (error) {
374
- output.writeln(output.error('Failed to install Claude Code CLI'));
375
- if (error instanceof Error) {
376
- output.writeln(output.dim(error.message));
377
- }
378
- return false;
379
- }
380
- }
381
- // Check embeddings / vector index health
382
- async function checkEmbeddings() {
383
- const dbPaths = [
384
- join(process.cwd(), '.swarm', 'memory.db'),
385
- join(process.cwd(), '.claude-flow', 'memory.db'),
386
- join(process.cwd(), 'data', 'memory.db'),
387
- ];
388
- // 1. Fast path: read cached vector-stats.json if available
389
- const statsPath = join(process.cwd(), '.claude-flow', 'vector-stats.json');
390
- try {
391
- if (existsSync(statsPath)) {
392
- const stats = JSON.parse(readFileSync(statsPath, 'utf8'));
393
- const count = stats.vectorCount ?? 0;
394
- const hasHnsw = stats.hasHnsw ?? false;
395
- const dbSizeKB = stats.dbSizeKB ?? 0;
396
- if (count === 0) {
397
- return {
398
- name: 'Embeddings',
399
- status: 'warn',
400
- message: `Memory DB exists (${dbSizeKB} KB) but 0 vectors indexed — documents not embedded`,
401
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
402
- };
403
- }
404
- const hnswLabel = hasHnsw ? ', HNSW' : '';
405
- return {
406
- name: 'Embeddings',
407
- status: 'pass',
408
- message: `${count} vectors indexed (${dbSizeKB} KB${hnswLabel})`
409
- };
410
- }
411
- }
412
- catch {
413
- // Stats file unreadable — fall through to DB check
414
- }
415
- // 2. Check if memory DB file exists at all
416
- let foundDbPath = null;
417
- for (const p of dbPaths) {
418
- if (existsSync(p)) {
419
- foundDbPath = p;
420
- break;
421
- }
422
- }
423
- if (!foundDbPath) {
424
- return {
425
- name: 'Embeddings',
426
- status: 'warn',
427
- message: 'No memory database — embeddings not initialized',
428
- fix: 'npx moflo memory init --force'
429
- };
430
- }
431
- // 3. DB exists but no stats cache — try querying the DB for entry count
432
- try {
433
- const { checkMemoryInitialization } = await import('../memory/memory-initializer.js');
434
- const info = await checkMemoryInitialization(foundDbPath);
435
- if (!info.initialized) {
436
- return {
437
- name: 'Embeddings',
438
- status: 'warn',
439
- message: 'Memory DB exists but not properly initialized',
440
- fix: 'npx moflo memory init --force'
441
- };
442
- }
443
- const hasVectors = info.features?.vectorEmbeddings ?? false;
444
- if (!hasVectors) {
445
- return {
446
- name: 'Embeddings',
447
- status: 'warn',
448
- message: `Memory DB initialized (v${info.version}) but no vector_indexes table`,
449
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
450
- };
451
- }
452
- return {
453
- name: 'Embeddings',
454
- status: 'pass',
455
- message: `Memory DB initialized (v${info.version}, vectors enabled)`
456
- };
457
- }
458
- catch {
459
- // sql.js not available — fall back to file-size heuristic
460
- try {
461
- const stats = statSync(foundDbPath);
462
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
463
- return {
464
- name: 'Embeddings',
465
- status: 'warn',
466
- message: `Memory DB exists (${sizeMB} MB) — cannot verify vectors (sql.js not available)`,
467
- fix: 'npm install sql.js && npx moflo embeddings init'
468
- };
469
- }
470
- catch {
471
- return { name: 'Embeddings', status: 'warn', message: 'Unable to check' };
472
- }
473
- }
474
- }
475
- /**
476
- * Auto-fix: execute fix commands for a failed/warned health check.
477
- * Returns true if the fix succeeded (re-check should pass).
478
- */
479
- async function autoFixCheck(check) {
480
- if (!check.fix)
481
- return false;
482
- // Map checks to programmatic fixes (not just shell commands)
483
- const fixActions = {
484
- 'Memory Database': async () => {
485
- try {
486
- const swarmDir = join(process.cwd(), '.swarm');
487
- if (!existsSync(swarmDir))
488
- mkdirSync(swarmDir, { recursive: true });
489
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
490
- const result = await initializeMemoryDatabase({ force: true, verbose: false });
491
- return result.success;
492
- }
493
- catch {
494
- // Fall back to CLI
495
- return runFixCommand('npx moflo memory init --force');
496
- }
497
- },
498
- 'Embeddings': async () => {
499
- try {
500
- // Step 1: ensure memory DB exists
501
- const swarmDir = join(process.cwd(), '.swarm');
502
- if (!existsSync(swarmDir))
503
- mkdirSync(swarmDir, { recursive: true });
504
- const dbPath = join(swarmDir, 'memory.db');
505
- if (!existsSync(dbPath)) {
506
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
507
- await initializeMemoryDatabase({ force: true, verbose: false });
508
- }
509
- // Step 2: attempt embeddings init via CLI
510
- return runFixCommand('npx moflo embeddings init --force');
511
- }
512
- catch {
513
- return runFixCommand('npx moflo memory init --force');
514
- }
515
- },
516
- 'Config File': async () => {
517
- try {
518
- const cfDir = join(process.cwd(), '.claude-flow');
519
- if (!existsSync(cfDir))
520
- mkdirSync(cfDir, { recursive: true });
521
- return runFixCommand('npx moflo config init');
522
- }
523
- catch {
524
- return false;
525
- }
526
- },
527
- 'Daemon Status': async () => {
528
- // Clean stale locks, then try to start daemon
529
- const lockFile = join(process.cwd(), '.claude-flow', 'daemon.lock');
530
- const pidFile = join(process.cwd(), '.claude-flow', 'daemon.pid');
531
- try {
532
- if (existsSync(lockFile)) {
533
- const { unlinkSync } = await import('fs');
534
- unlinkSync(lockFile);
535
- }
536
- if (existsSync(pidFile)) {
537
- const { unlinkSync } = await import('fs');
538
- unlinkSync(pidFile);
539
- }
540
- }
541
- catch { /* best effort */ }
542
- return runFixCommand('npx moflo daemon start');
543
- },
544
- 'MCP Servers': async () => {
545
- return runFixCommand('claude mcp add moflo -- npx -y moflo mcp start');
546
- },
547
- 'Claude Code CLI': async () => {
548
- return installClaudeCode();
549
- },
550
- 'Zombie Processes': async () => {
551
- const result = await findZombieProcesses(true);
552
- return result.killed > 0 || result.found === 0;
553
- },
554
- };
555
- const fixFn = fixActions[check.name];
556
- if (fixFn) {
557
- try {
558
- output.writeln(output.dim(` Fixing: ${check.name}...`));
559
- const success = await fixFn();
560
- if (success) {
561
- output.writeln(output.success(` Fixed: ${check.name}`));
562
- }
563
- else {
564
- output.writeln(output.warning(` Fix attempted but may need manual action: ${check.fix}`));
565
- }
566
- return success;
567
- }
568
- catch (e) {
569
- output.writeln(output.warning(` Fix failed: ${e instanceof Error ? e.message : String(e)}`));
570
- return false;
571
- }
572
- }
573
- // Generic: try running the fix command directly if it looks like a shell command
574
- if (check.fix.startsWith('npx ') || check.fix.startsWith('npm ') || check.fix.startsWith('claude ')) {
575
- return runFixCommand(check.fix);
576
- }
577
- return false;
578
- }
579
- /**
580
- * Run a shell command as a fix action. Returns true on exit code 0.
581
- */
582
- async function runFixCommand(cmd) {
583
- try {
584
- await execAsync(cmd, {
585
- encoding: 'utf8',
586
- timeout: 30000,
587
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh',
588
- env: { ...process.env },
589
- windowsHide: true,
590
- });
591
- return true;
592
- }
593
- catch {
594
- return false;
595
- }
596
- }
597
- // Check test directories configured in moflo.yaml
598
- async function checkTestDirs() {
599
- const yamlPath = join(process.cwd(), 'moflo.yaml');
600
- if (!existsSync(yamlPath)) {
601
- return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
602
- }
603
- try {
604
- const content = readFileSync(yamlPath, 'utf-8');
605
- // Check if tests section exists
606
- const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
607
- if (!testsBlock) {
608
- return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
609
- }
610
- // Extract configured directories
611
- const items = testsBlock[1].match(/-\s+(.+)/g);
612
- if (!items || items.length === 0) {
613
- return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
614
- }
615
- const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
616
- const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
617
- const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
618
- // Check auto_index.tests flag
619
- const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
620
- const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
621
- const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
622
- if (missing.length > 0 && existing.length === 0) {
623
- return {
624
- name: 'Test Directories',
625
- status: 'warn',
626
- message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
627
- };
628
- }
629
- if (missing.length > 0) {
630
- return {
631
- name: 'Test Directories',
632
- status: 'warn',
633
- message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
634
- };
635
- }
636
- return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
637
- }
638
- catch {
639
- return { name: 'Test Directories', status: 'warn', message: 'Unable to parse moflo.yaml' };
640
- }
641
- }
642
- // Check agentic-flow v3 integration (filesystem-based to avoid slow WASM/DB init)
643
- async function checkAgenticFlow() {
644
- try {
645
- // Walk common node_modules paths to find agentic-flow/package.json
646
- const candidates = [
647
- join(process.cwd(), 'node_modules', 'agentic-flow', 'package.json'),
648
- join(process.cwd(), '..', 'node_modules', 'agentic-flow', 'package.json'),
649
- ];
650
- let pkgJsonPath = null;
651
- for (const p of candidates) {
652
- if (existsSync(p)) {
653
- pkgJsonPath = p;
654
- break;
655
- }
656
- }
657
- if (!pkgJsonPath) {
658
- return {
659
- name: 'agentic-flow',
660
- status: 'warn',
661
- message: 'Not installed (optional — embeddings/routing will use fallbacks)',
662
- fix: 'npm install agentic-flow@latest'
663
- };
664
- }
665
- const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
666
- const version = pkg.version || 'unknown';
667
- const exports = pkg.exports || {};
668
- const features = [
669
- exports['./reasoningbank'] ? 'ReasoningBank' : null,
670
- exports['./router'] ? 'Router' : null,
671
- exports['./transport/quic'] ? 'QUIC' : null,
672
- ].filter(Boolean);
673
- return {
674
- name: 'agentic-flow',
675
- status: 'pass',
676
- message: `v${version} (${features.join(', ')})`
677
- };
678
- }
679
- catch {
680
- return { name: 'agentic-flow', status: 'warn', message: 'Check failed' };
681
- }
682
- }
683
- // Check whether a given PID is still running.
684
- // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
685
- // needing PowerShell or /proc — Node handles the platform abstraction.
686
- function isProcessAlive(pid) {
687
- try {
688
- process.kill(pid, 0);
689
- return true;
690
- }
691
- catch {
692
- return false;
693
- }
694
- }
695
- // Fast path: kill processes tracked in the shared ProcessManager registry.
696
- // This avoids the expensive OS-level process scan for known background tasks.
697
- function killTrackedProcesses() {
698
- const registryFile = join(process.cwd(), '.claude-flow', 'background-pids.json');
699
- const lockFile = join(process.cwd(), '.claude-flow', 'spawn.lock');
700
- let killed = 0;
701
- try {
702
- if (existsSync(registryFile)) {
703
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
704
- for (const entry of entries) {
705
- if (!isProcessAlive(entry.pid))
706
- continue;
707
- try {
708
- if (process.platform === 'win32') {
709
- execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
710
- }
711
- else {
712
- process.kill(entry.pid, 'SIGKILL');
713
- }
714
- killed++;
715
- }
716
- catch { /* already gone */ }
717
- }
718
- // Clear registry
719
- writeFileSync(registryFile, '[]');
720
- }
721
- }
722
- catch { /* non-fatal */ }
723
- // Remove spawn lock
724
- try {
725
- if (existsSync(lockFile))
726
- unlinkSync(lockFile);
727
- }
728
- catch { /* ok */ }
729
- return killed;
730
- }
731
- // Find and optionally kill orphaned moflo/claude-flow node processes.
732
- // A process is only "orphaned" if its parent is no longer alive — meaning
733
- // nothing will clean it up. MCP servers spawned by a live Claude Code session
734
- // have a live parent (claude.exe) and must not be flagged.
735
- async function findZombieProcesses(kill = false) {
736
- const legitimatePid = getDaemonLockHolder(process.cwd());
737
- const currentPid = process.pid;
738
- const parentPid = process.ppid;
739
- const found = [];
740
- let killed = 0;
741
- // Collect candidates as { pid, ppid } so we can check parent liveness
742
- const candidates = [];
743
- try {
744
- if (process.platform === 'win32') {
745
- // Windows: include ParentProcessId so we can verify orphan status
746
- const result = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name=\'node.exe\'\\" | Select-Object ProcessId,ParentProcessId,CommandLine | Format-Table -AutoSize -Wrap"', { encoding: 'utf-8', timeout: 10000, windowsHide: true });
747
- const lines = result.split('\n');
748
- for (const line of lines) {
749
- if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
750
- // Format-Table columns: ProcessId ParentProcessId CommandLine...
751
- const match = line.match(/^\s*(\d+)\s+(\d+)/);
752
- if (match) {
753
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
754
- }
755
- }
756
- }
757
- }
758
- else {
759
- // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
760
- const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
761
- const lines = result.trim().split('\n');
762
- for (const line of lines) {
763
- const match = line.trim().match(/^(\d+)\s+(\d+)/);
764
- if (match) {
765
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
766
- }
767
- }
768
- }
769
- }
770
- catch {
771
- // No matches found (grep exits non-zero) or command failed
772
- }
773
- // Filter: skip known-good PIDs and processes whose parent is still alive.
774
- // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
775
- for (const { pid, ppid } of candidates) {
776
- if (pid === currentPid || pid === parentPid || pid === legitimatePid)
777
- continue;
778
- if (isProcessAlive(ppid))
779
- continue;
780
- // Defense-in-depth: detached daemons have dead parents by design.
781
- // Even if the lock file is missing/corrupted, don't kill a running daemon.
782
- if (isDaemonProcess(pid))
783
- continue;
784
- found.push(pid);
785
- }
786
- if (kill && found.length > 0) {
787
- for (const pid of found) {
788
- try {
789
- if (process.platform === 'win32') {
790
- execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
791
- }
792
- else {
793
- process.kill(pid, 'SIGKILL');
794
- }
795
- killed++;
796
- }
797
- catch {
798
- // Process may have already exited
799
- }
800
- }
801
- // Clean up stale daemon lock if we killed the holder
802
- if (legitimatePid && found.includes(legitimatePid)) {
803
- releaseDaemonLock(process.cwd(), legitimatePid, true);
804
- }
805
- }
806
- return { found: found.length, killed, pids: found };
807
- }
808
- // Format health check result
809
- function formatCheck(check) {
810
- const icon = check.status === 'pass' ? output.success('✓') :
811
- check.status === 'warn' ? output.warning('⚠') :
812
- output.error('✗');
813
- return `${icon} ${check.name}: ${check.message}`;
814
- }
815
- // Main doctor command
816
- export const doctorCommand = {
817
- name: 'doctor',
818
- description: 'System diagnostics and health checks',
819
- options: [
820
- {
821
- name: 'fix',
822
- short: 'f',
823
- description: 'Automatically fix issues where possible',
824
- type: 'boolean',
825
- default: false
826
- },
827
- {
828
- name: 'install',
829
- short: 'i',
830
- description: 'Auto-install missing dependencies (Claude Code CLI)',
831
- type: 'boolean',
832
- default: false
833
- },
834
- {
835
- name: 'component',
836
- short: 'c',
837
- description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript)',
838
- type: 'string'
839
- },
840
- {
841
- name: 'verbose',
842
- short: 'v',
843
- description: 'Verbose output',
844
- type: 'boolean',
845
- default: false
846
- },
847
- {
848
- name: 'kill-zombies',
849
- short: 'k',
850
- description: 'Find and kill orphaned moflo/claude-flow node processes',
851
- type: 'boolean',
852
- default: false
853
- }
854
- ],
855
- examples: [
856
- { command: 'claude-flow doctor', description: 'Run full health check' },
857
- { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' },
858
- { command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },
859
- { command: 'claude-flow doctor --kill-zombies', description: 'Find and kill zombie processes' },
860
- { command: 'claude-flow doctor -c version', description: 'Check for stale npx cache' },
861
- { command: 'claude-flow doctor -c claude', description: 'Check Claude Code CLI only' }
862
- ],
863
- action: async (ctx) => {
864
- const showFix = ctx.flags.fix;
865
- const autoInstall = ctx.flags.install;
866
- const component = ctx.flags.component;
867
- const verbose = ctx.flags.verbose;
868
- const killZombies = ctx.flags['kill-zombies'];
869
- output.writeln();
870
- output.writeln(output.bold('MoFlo Doctor'));
871
- output.writeln(output.dim('System diagnostics and health check'));
872
- output.writeln(output.dim('─'.repeat(50)));
873
- output.writeln();
874
- // Handle --kill-zombies early
875
- if (killZombies) {
876
- output.writeln(output.bold('Zombie Process Scan'));
877
- output.writeln();
878
- // Fast path: kill tracked processes from the shared registry first
879
- const registryKilled = killTrackedProcesses();
880
- if (registryKilled > 0) {
881
- output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
882
- }
883
- // Slow path: OS-level scan for any remaining orphans
884
- const scan = await findZombieProcesses(false);
885
- if (scan.found === 0) {
886
- if (registryKilled === 0) {
887
- output.writeln(output.success(' No orphaned moflo processes found'));
888
- }
889
- }
890
- else {
891
- output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
892
- // Kill them
893
- const result = await findZombieProcesses(true);
894
- if (result.killed > 0) {
895
- output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
896
- }
897
- if (result.killed < result.found) {
898
- output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
899
- }
900
- }
901
- output.writeln();
902
- output.writeln(output.dim('─'.repeat(50)));
903
- output.writeln();
904
- }
905
- const checkZombieProcesses = async () => {
906
- try {
907
- const scan = await findZombieProcesses(false);
908
- if (scan.found === 0) {
909
- return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
910
- }
911
- return {
912
- name: 'Zombie Processes',
913
- status: 'warn',
914
- message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
915
- fix: 'moflo doctor --kill-zombies'
916
- };
917
- }
918
- catch {
919
- return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
920
- }
921
- };
922
- const allChecks = [
923
- checkVersionFreshness,
924
- checkNodeVersion,
925
- checkNpmVersion,
926
- checkClaudeCode,
927
- checkGit,
928
- checkGitRepo,
929
- checkConfigFile,
930
- checkDaemonStatus,
931
- checkMemoryDatabase,
932
- checkEmbeddings,
933
- checkTestDirs,
934
- checkMcpServers,
935
- checkDiskSpace,
936
- checkBuildTools,
937
- checkAgenticFlow,
938
- checkZombieProcesses
939
- ];
940
- const componentMap = {
941
- 'version': checkVersionFreshness,
942
- 'freshness': checkVersionFreshness,
943
- 'node': checkNodeVersion,
944
- 'npm': checkNpmVersion,
945
- 'claude': checkClaudeCode,
946
- 'config': checkConfigFile,
947
- 'daemon': checkDaemonStatus,
948
- 'memory': checkMemoryDatabase,
949
- 'embeddings': checkEmbeddings,
950
- 'git': checkGit,
951
- 'mcp': checkMcpServers,
952
- 'disk': checkDiskSpace,
953
- 'typescript': checkBuildTools,
954
- 'tests': checkTestDirs,
955
- 'agentic-flow': checkAgenticFlow
956
- };
957
- let checksToRun = allChecks;
958
- if (component && componentMap[component]) {
959
- checksToRun = [componentMap[component]];
960
- }
961
- const results = [];
962
- const fixes = [];
963
- // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
964
- const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });
965
- spinner.start();
966
- try {
967
- // Execute all checks concurrently
968
- const checkResults = await Promise.allSettled(checksToRun.map(check => check()));
969
- spinner.stop();
970
- // Process results in order
971
- for (const settledResult of checkResults) {
972
- if (settledResult.status === 'fulfilled') {
973
- const result = settledResult.value;
974
- results.push(result);
975
- output.writeln(formatCheck(result));
976
- if (result.fix && (result.status === 'fail' || result.status === 'warn')) {
977
- fixes.push(`${result.name}: ${result.fix}`);
978
- }
979
- }
980
- else {
981
- const errorResult = {
982
- name: 'Check',
983
- status: 'fail',
984
- message: settledResult.reason?.message || 'Unknown error'
985
- };
986
- results.push(errorResult);
987
- output.writeln(formatCheck(errorResult));
988
- }
989
- }
990
- }
991
- catch (error) {
992
- spinner.stop();
993
- output.writeln(output.error('Failed to run health checks'));
994
- }
995
- // Auto-install missing dependencies if requested
996
- if (autoInstall) {
997
- const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
998
- if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
999
- const installed = await installClaudeCode();
1000
- if (installed) {
1001
- // Re-check Claude Code after installation
1002
- const newCheck = await checkClaudeCode();
1003
- const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1004
- if (idx !== -1) {
1005
- results[idx] = newCheck;
1006
- // Update fixes list
1007
- const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1008
- if (fixIdx !== -1 && newCheck.status === 'pass') {
1009
- fixes.splice(fixIdx, 1);
1010
- }
1011
- }
1012
- output.writeln(formatCheck(newCheck));
1013
- }
1014
- }
1015
- }
1016
- // Summary
1017
- const passed = results.filter(r => r.status === 'pass').length;
1018
- const warnings = results.filter(r => r.status === 'warn').length;
1019
- const failed = results.filter(r => r.status === 'fail').length;
1020
- output.writeln();
1021
- output.writeln(output.dim(''.repeat(50)));
1022
- output.writeln();
1023
- const summaryParts = [
1024
- output.success(`${passed} passed`),
1025
- warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1026
- failed > 0 ? output.error(`${failed} failed`) : null
1027
- ].filter(Boolean);
1028
- output.writeln(`Summary: ${summaryParts.join(', ')}`);
1029
- // Auto-fix or show fixes
1030
- if (showFix && fixes.length > 0) {
1031
- output.writeln();
1032
- output.writeln(output.bold('Auto-fixing issues...'));
1033
- output.writeln();
1034
- const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1035
- let fixed = 0;
1036
- const unfixed = [];
1037
- for (const check of fixableResults) {
1038
- const success = await autoFixCheck(check);
1039
- if (success) {
1040
- fixed++;
1041
- }
1042
- else {
1043
- unfixed.push(`${check.name}: ${check.fix}`);
1044
- }
1045
- }
1046
- if (fixed > 0) {
1047
- output.writeln();
1048
- output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1049
- }
1050
- if (unfixed.length > 0) {
1051
- output.writeln();
1052
- output.writeln(output.bold('Manual fixes needed:'));
1053
- for (const fix of unfixed) {
1054
- output.writeln(output.dim(` ${fix}`));
1055
- }
1056
- }
1057
- // Re-run checks to show updated status
1058
- if (fixed > 0) {
1059
- output.writeln();
1060
- output.writeln(output.dim('Re-checking...'));
1061
- output.writeln();
1062
- const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1063
- let rePassed = 0, reWarnings = 0, reFailed = 0;
1064
- for (const sr of reResults) {
1065
- if (sr.status === 'fulfilled') {
1066
- output.writeln(formatCheck(sr.value));
1067
- if (sr.value.status === 'pass')
1068
- rePassed++;
1069
- else if (sr.value.status === 'warn')
1070
- reWarnings++;
1071
- else
1072
- reFailed++;
1073
- }
1074
- }
1075
- output.writeln();
1076
- output.writeln(output.dim('─'.repeat(50)));
1077
- const reSummary = [
1078
- output.success(`${rePassed} passed`),
1079
- reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1080
- reFailed > 0 ? output.error(`${reFailed} failed`) : null
1081
- ].filter(Boolean);
1082
- output.writeln(`After fix: ${reSummary.join(', ')}`);
1083
- }
1084
- }
1085
- else if (fixes.length > 0 && !showFix) {
1086
- output.writeln();
1087
- output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1088
- }
1089
- // Overall result
1090
- if (failed > 0) {
1091
- output.writeln();
1092
- output.writeln(output.error('Some checks failed. Please address the issues above.'));
1093
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1094
- }
1095
- else if (warnings > 0) {
1096
- output.writeln();
1097
- output.writeln(output.warning('All checks passed with some warnings.'));
1098
- return { success: true, data: { passed, warnings, failed, results } };
1099
- }
1100
- else {
1101
- output.writeln();
1102
- output.writeln(output.success('All checks passed! System is healthy.'));
1103
- return { success: true, data: { passed, warnings, failed, results } };
1104
- }
1105
- }
1106
- };
1107
- export default doctorCommand;
1
+ /**
2
+ * V3 CLI Doctor Command
3
+ * System diagnostics, dependency checks, config validation
4
+ *
5
+ * Created with motailz.com
6
+ */
7
+ import { output } from '../output.js';
8
+ import { existsSync, readFileSync, writeFileSync, unlinkSync, statSync, mkdirSync } from 'fs';
9
+ import { join, dirname } from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { execSync, exec } from 'child_process';
12
+ import { promisify } from 'util';
13
+ import { getDaemonLockHolder, releaseDaemonLock, isDaemonProcess } from '../services/daemon-lock.js';
14
+ // Promisified exec with proper shell and env inheritance for cross-platform support
15
+ const execAsync = promisify(exec);
16
+ /**
17
+ * Execute command asynchronously with proper environment inheritance
18
+ * Critical for Windows where PATH may not be inherited properly
19
+ */
20
+ async function runCommand(command, timeoutMs = 5000) {
21
+ const { stdout } = await execAsync(command, {
22
+ encoding: 'utf8',
23
+ timeout: timeoutMs,
24
+ shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh', // Use proper shell per platform
25
+ env: { ...process.env }, // Explicitly inherit full environment
26
+ windowsHide: true, // Hide window on Windows
27
+ });
28
+ return stdout.trim();
29
+ }
30
+ // Check Node.js version
31
+ async function checkNodeVersion() {
32
+ const requiredMajor = 20;
33
+ const version = process.version;
34
+ const major = parseInt(version.slice(1).split('.')[0], 10);
35
+ if (major >= requiredMajor) {
36
+ return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` };
37
+ }
38
+ else if (major >= 18) {
39
+ return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' };
40
+ }
41
+ else {
42
+ return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' };
43
+ }
44
+ }
45
+ // Check npm version (async with proper env inheritance)
46
+ async function checkNpmVersion() {
47
+ try {
48
+ const version = await runCommand('npm --version');
49
+ const major = parseInt(version.split('.')[0], 10);
50
+ if (major >= 9) {
51
+ return { name: 'npm Version', status: 'pass', message: `v${version}` };
52
+ }
53
+ else {
54
+ return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' };
55
+ }
56
+ }
57
+ catch {
58
+ return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' };
59
+ }
60
+ }
61
+ // Check config file
62
+ async function checkConfigFile() {
63
+ // JSON configs (parse-validated)
64
+ const jsonPaths = [
65
+ '.claude-flow/config.json',
66
+ 'claude-flow.config.json',
67
+ '.claude-flow.json'
68
+ ];
69
+ for (const configPath of jsonPaths) {
70
+ if (existsSync(configPath)) {
71
+ try {
72
+ const content = readFileSync(configPath, 'utf8');
73
+ JSON.parse(content);
74
+ return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
75
+ }
76
+ catch (e) {
77
+ return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' };
78
+ }
79
+ }
80
+ }
81
+ // YAML configs (existence-checked only — no heavy yaml parser dependency)
82
+ const yamlPaths = [
83
+ '.claude-flow/config.yaml',
84
+ '.claude-flow/config.yml',
85
+ 'claude-flow.config.yaml'
86
+ ];
87
+ for (const configPath of yamlPaths) {
88
+ if (existsSync(configPath)) {
89
+ return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
90
+ }
91
+ }
92
+ return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' };
93
+ }
94
+ // Check daemon status — delegates to daemon-lock module for proper
95
+ // PID + command-line verification (avoids Windows PID-recycling false positives).
96
+ async function checkDaemonStatus() {
97
+ try {
98
+ // Retry up to 5 times with 1s delay — the daemon starts in the background
99
+ // during session-start and may not have acquired its lock file yet.
100
+ const MAX_RETRIES = 5;
101
+ const RETRY_DELAY_MS = 1000;
102
+ let holderPid = null;
103
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
104
+ holderPid = getDaemonLockHolder(process.cwd());
105
+ if (holderPid)
106
+ break;
107
+ if (attempt < MAX_RETRIES - 1) {
108
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
109
+ }
110
+ }
111
+ if (holderPid) {
112
+ return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${holderPid})` };
113
+ }
114
+ // getDaemonLockHolder auto-cleans stale locks, but check for legacy PID file
115
+ const lockFile = '.claude-flow/daemon.lock';
116
+ if (existsSync(lockFile)) {
117
+ // Lock exists but holder is null — getDaemonLockHolder already cleaned it,
118
+ // but if it persists it means cleanup failed (permissions, etc.)
119
+ return { name: 'Daemon Status', status: 'warn', message: 'Stale lock file', fix: 'rm .claude-flow/daemon.lock && claude-flow daemon start' };
120
+ }
121
+ // Also check legacy PID file
122
+ const pidFile = '.claude-flow/daemon.pid';
123
+ if (existsSync(pidFile)) {
124
+ return { name: 'Daemon Status', status: 'warn', message: 'Legacy PID file found', fix: 'rm .claude-flow/daemon.pid && claude-flow daemon start' };
125
+ }
126
+ return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' };
127
+ }
128
+ catch {
129
+ return { name: 'Daemon Status', status: 'warn', message: 'Unable to check', fix: 'claude-flow daemon status' };
130
+ }
131
+ }
132
+ // Check memory database
133
+ async function checkMemoryDatabase() {
134
+ const dbPaths = [
135
+ '.claude-flow/memory.db',
136
+ '.swarm/memory.db',
137
+ 'data/memory.db'
138
+ ];
139
+ for (const dbPath of dbPaths) {
140
+ if (existsSync(dbPath)) {
141
+ try {
142
+ const stats = statSync(dbPath);
143
+ const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
144
+ return { name: 'Memory Database', status: 'pass', message: `${dbPath} (${sizeMB} MB)` };
145
+ }
146
+ catch {
147
+ return { name: 'Memory Database', status: 'warn', message: `${dbPath} (unable to stat)` };
148
+ }
149
+ }
150
+ }
151
+ return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
152
+ }
153
+ // Check git (async with proper env inheritance)
154
+ async function checkGit() {
155
+ try {
156
+ const version = await runCommand('git --version');
157
+ return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') };
158
+ }
159
+ catch {
160
+ return { name: 'Git', status: 'warn', message: 'Not installed', fix: 'Install git from https://git-scm.com' };
161
+ }
162
+ }
163
+ // Check if in git repo (async with proper env inheritance)
164
+ async function checkGitRepo() {
165
+ try {
166
+ await runCommand('git rev-parse --git-dir');
167
+ return { name: 'Git Repository', status: 'pass', message: 'In a git repository' };
168
+ }
169
+ catch {
170
+ return { name: 'Git Repository', status: 'warn', message: 'Not a git repository', fix: 'git init' };
171
+ }
172
+ }
173
+ // Check MCP servers
174
+ async function checkMcpServers() {
175
+ const mcpConfigPaths = [
176
+ join(process.env.HOME || '', '.claude/claude_desktop_config.json'),
177
+ join(process.env.HOME || '', '.config/claude/mcp.json'),
178
+ '.mcp.json'
179
+ ];
180
+ for (const configPath of mcpConfigPaths) {
181
+ if (existsSync(configPath)) {
182
+ try {
183
+ const content = JSON.parse(readFileSync(configPath, 'utf8'));
184
+ const servers = content.mcpServers || content.servers || {};
185
+ const count = Object.keys(servers).length;
186
+ const hasClaudeFlow = 'moflo' in servers || 'claude-flow' in servers || 'claude-flow_alpha' in servers || 'ruflo' in servers || 'ruflo_alpha' in servers;
187
+ if (hasClaudeFlow) {
188
+ return { name: 'MCP Servers', status: 'pass', message: `${count} servers (flo configured)` };
189
+ }
190
+ else {
191
+ return { name: 'MCP Servers', status: 'warn', message: `${count} servers (flo not found)`, fix: 'claude mcp add ruflo -- npx -y ruflo@latest mcp start' };
192
+ }
193
+ }
194
+ catch {
195
+ // continue to next path
196
+ }
197
+ }
198
+ }
199
+ return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add moflo npx moflo mcp start' };
200
+ }
201
+ // Check disk space (async with proper env inheritance)
202
+ async function checkDiskSpace() {
203
+ try {
204
+ if (process.platform === 'win32') {
205
+ return { name: 'Disk Space', status: 'pass', message: 'Check skipped on Windows' };
206
+ }
207
+ // Use df -Ph for POSIX mode (guarantees single-line output even with long device names)
208
+ const output_str = await runCommand('df -Ph . | tail -1');
209
+ const parts = output_str.split(/\s+/);
210
+ // POSIX format: Filesystem Size Used Avail Capacity Mounted
211
+ const available = parts[3];
212
+ const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10);
213
+ if (isNaN(usePercent)) {
214
+ return { name: 'Disk Space', status: 'warn', message: `${available || 'unknown'} available (unable to parse usage)` };
215
+ }
216
+ if (usePercent > 90) {
217
+ return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' };
218
+ }
219
+ else if (usePercent > 80) {
220
+ return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` };
221
+ }
222
+ return { name: 'Disk Space', status: 'pass', message: `${available} available` };
223
+ }
224
+ catch {
225
+ return { name: 'Disk Space', status: 'warn', message: 'Unable to check' };
226
+ }
227
+ }
228
+ // Check TypeScript/build (async with proper env inheritance)
229
+ async function checkBuildTools() {
230
+ try {
231
+ const tscVersion = await runCommand('npx tsc --version', 10000); // tsc can be slow
232
+ if (!tscVersion || tscVersion.includes('not found')) {
233
+ return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
234
+ }
235
+ return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') };
236
+ }
237
+ catch {
238
+ return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
239
+ }
240
+ }
241
+ // Check for stale npx cache (version freshness)
242
+ async function checkVersionFreshness() {
243
+ try {
244
+ // Get current CLI version from package.json
245
+ // Use import.meta.url to reliably locate our own package.json,
246
+ // regardless of how deep the compiled file sits (e.g. dist/src/commands/).
247
+ let currentVersion = '0.0.0';
248
+ try {
249
+ const thisFile = fileURLToPath(import.meta.url);
250
+ let dir = dirname(thisFile);
251
+ // Walk up from the current file's directory until we find the
252
+ // package.json that belongs to @claude-flow/cli (or claude-flow/cli).
253
+ // Walk until dirname(dir) === dir (filesystem root on any platform).
254
+ for (;;) {
255
+ const candidate = join(dir, 'package.json');
256
+ try {
257
+ if (existsSync(candidate)) {
258
+ const pkg = JSON.parse(readFileSync(candidate, 'utf8'));
259
+ if (pkg.version &&
260
+ typeof pkg.name === 'string' &&
261
+ (pkg.name === '@claude-flow/cli' || pkg.name === 'claude-flow' || pkg.name === 'ruflo' || pkg.name === 'moflo' || pkg.name === '@moflo/cli')) {
262
+ currentVersion = pkg.version;
263
+ break;
264
+ }
265
+ }
266
+ }
267
+ catch {
268
+ // Unreadable/invalid JSON -- skip and keep walking up
269
+ }
270
+ const parent = dirname(dir);
271
+ if (parent === dir)
272
+ break; // reached root
273
+ dir = parent;
274
+ }
275
+ }
276
+ catch {
277
+ // Fall back to a default
278
+ currentVersion = '0.0.0';
279
+ }
280
+ // Check if running via npx (look for _npx in process path or argv)
281
+ const isNpx = process.argv[1]?.includes('_npx') ||
282
+ process.env.npm_execpath?.includes('npx') ||
283
+ process.cwd().includes('_npx');
284
+ // Query npm for latest version (using alpha tag since that's what we publish to)
285
+ let latestVersion = currentVersion;
286
+ try {
287
+ const npmInfo = await runCommand('npm view moflo version', 5000);
288
+ latestVersion = npmInfo.trim();
289
+ }
290
+ catch {
291
+ // Can't reach npm registry - skip check
292
+ return {
293
+ name: 'Version Freshness',
294
+ status: 'warn',
295
+ message: `v${currentVersion} (cannot check registry)`
296
+ };
297
+ }
298
+ // Parse version numbers for comparison (handle prerelease like 3.0.0-alpha.84)
299
+ const parseVersion = (v) => {
300
+ const match = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-[a-zA-Z]+\.(\d+))?/);
301
+ if (!match)
302
+ return { major: 0, minor: 0, patch: 0, prerelease: 0 };
303
+ return {
304
+ major: parseInt(match[1], 10) || 0,
305
+ minor: parseInt(match[2], 10) || 0,
306
+ patch: parseInt(match[3], 10) || 0,
307
+ prerelease: parseInt(match[4], 10) || 0
308
+ };
309
+ };
310
+ const current = parseVersion(currentVersion);
311
+ const latest = parseVersion(latestVersion);
312
+ // Compare versions (including prerelease number)
313
+ const isOutdated = (latest.major > current.major ||
314
+ (latest.major === current.major && latest.minor > current.minor) ||
315
+ (latest.major === current.major && latest.minor === current.minor && latest.patch > current.patch) ||
316
+ (latest.major === current.major && latest.minor === current.minor && latest.patch === current.patch && latest.prerelease > current.prerelease));
317
+ if (isOutdated) {
318
+ const fix = isNpx
319
+ ? 'rm -rf ~/.npm/_npx/* && npx -y moflo'
320
+ : 'npm update moflo';
321
+ return {
322
+ name: 'Version Freshness',
323
+ status: 'warn',
324
+ message: `v${currentVersion} (latest: v${latestVersion})${isNpx ? ' [npx cache stale]' : ''}`,
325
+ fix
326
+ };
327
+ }
328
+ return {
329
+ name: 'Version Freshness',
330
+ status: 'pass',
331
+ message: `v${currentVersion} (up to date)`
332
+ };
333
+ }
334
+ catch (error) {
335
+ return {
336
+ name: 'Version Freshness',
337
+ status: 'warn',
338
+ message: 'Unable to check version freshness'
339
+ };
340
+ }
341
+ }
342
+ // Check Claude Code CLI (async with proper env inheritance)
343
+ async function checkClaudeCode() {
344
+ try {
345
+ const version = await runCommand('claude --version');
346
+ // Parse version from output like "claude 1.0.0" or "Claude Code v1.0.0"
347
+ const versionMatch = version.match(/v?(\d+\.\d+\.\d+)/);
348
+ const versionStr = versionMatch ? `v${versionMatch[1]}` : version;
349
+ return { name: 'Claude Code CLI', status: 'pass', message: versionStr };
350
+ }
351
+ catch {
352
+ return {
353
+ name: 'Claude Code CLI',
354
+ status: 'warn',
355
+ message: 'Not installed',
356
+ fix: 'npm install -g @anthropic-ai/claude-code'
357
+ };
358
+ }
359
+ }
360
+ // Install Claude Code CLI
361
+ async function installClaudeCode() {
362
+ try {
363
+ output.writeln();
364
+ output.writeln(output.bold('Installing Claude Code CLI...'));
365
+ execSync('npm install -g @anthropic-ai/claude-code', {
366
+ encoding: 'utf8',
367
+ stdio: 'inherit',
368
+ windowsHide: true
369
+ });
370
+ output.writeln(output.success('Claude Code CLI installed successfully!'));
371
+ return true;
372
+ }
373
+ catch (error) {
374
+ output.writeln(output.error('Failed to install Claude Code CLI'));
375
+ if (error instanceof Error) {
376
+ output.writeln(output.dim(error.message));
377
+ }
378
+ return false;
379
+ }
380
+ }
381
+ // Check embeddings / vector index health
382
+ async function checkEmbeddings() {
383
+ const dbPaths = [
384
+ join(process.cwd(), '.swarm', 'memory.db'),
385
+ join(process.cwd(), '.claude-flow', 'memory.db'),
386
+ join(process.cwd(), 'data', 'memory.db'),
387
+ ];
388
+ // 1. Fast path: read cached vector-stats.json if available
389
+ const statsPath = join(process.cwd(), '.claude-flow', 'vector-stats.json');
390
+ try {
391
+ if (existsSync(statsPath)) {
392
+ const stats = JSON.parse(readFileSync(statsPath, 'utf8'));
393
+ const count = stats.vectorCount ?? 0;
394
+ const hasHnsw = stats.hasHnsw ?? false;
395
+ const dbSizeKB = stats.dbSizeKB ?? 0;
396
+ if (count === 0) {
397
+ return {
398
+ name: 'Embeddings',
399
+ status: 'warn',
400
+ message: `Memory DB exists (${dbSizeKB} KB) but 0 vectors indexed — documents not embedded`,
401
+ fix: 'npx moflo memory init --force && npx moflo embeddings init'
402
+ };
403
+ }
404
+ const hnswLabel = hasHnsw ? ', HNSW' : '';
405
+ return {
406
+ name: 'Embeddings',
407
+ status: 'pass',
408
+ message: `${count} vectors indexed (${dbSizeKB} KB${hnswLabel})`
409
+ };
410
+ }
411
+ }
412
+ catch {
413
+ // Stats file unreadable — fall through to DB check
414
+ }
415
+ // 2. Check if memory DB file exists at all
416
+ let foundDbPath = null;
417
+ for (const p of dbPaths) {
418
+ if (existsSync(p)) {
419
+ foundDbPath = p;
420
+ break;
421
+ }
422
+ }
423
+ if (!foundDbPath) {
424
+ return {
425
+ name: 'Embeddings',
426
+ status: 'warn',
427
+ message: 'No memory database — embeddings not initialized',
428
+ fix: 'npx moflo memory init --force'
429
+ };
430
+ }
431
+ // 3. DB exists but no stats cache — try querying the DB for entry count
432
+ try {
433
+ const { checkMemoryInitialization } = await import('../memory/memory-initializer.js');
434
+ const info = await checkMemoryInitialization(foundDbPath);
435
+ if (!info.initialized) {
436
+ return {
437
+ name: 'Embeddings',
438
+ status: 'warn',
439
+ message: 'Memory DB exists but not properly initialized',
440
+ fix: 'npx moflo memory init --force'
441
+ };
442
+ }
443
+ const hasVectors = info.features?.vectorEmbeddings ?? false;
444
+ if (!hasVectors) {
445
+ return {
446
+ name: 'Embeddings',
447
+ status: 'warn',
448
+ message: `Memory DB initialized (v${info.version}) but no vector_indexes table`,
449
+ fix: 'npx moflo memory init --force && npx moflo embeddings init'
450
+ };
451
+ }
452
+ return {
453
+ name: 'Embeddings',
454
+ status: 'pass',
455
+ message: `Memory DB initialized (v${info.version}, vectors enabled)`
456
+ };
457
+ }
458
+ catch {
459
+ // sql.js not available — fall back to file-size heuristic
460
+ try {
461
+ const stats = statSync(foundDbPath);
462
+ const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
463
+ return {
464
+ name: 'Embeddings',
465
+ status: 'warn',
466
+ message: `Memory DB exists (${sizeMB} MB) — cannot verify vectors (sql.js not available)`,
467
+ fix: 'npm install sql.js && npx moflo embeddings init'
468
+ };
469
+ }
470
+ catch {
471
+ return { name: 'Embeddings', status: 'warn', message: 'Unable to check' };
472
+ }
473
+ }
474
+ }
475
+ /**
476
+ * Auto-fix: execute fix commands for a failed/warned health check.
477
+ * Returns true if the fix succeeded (re-check should pass).
478
+ */
479
+ async function autoFixCheck(check) {
480
+ if (!check.fix)
481
+ return false;
482
+ // Map checks to programmatic fixes (not just shell commands)
483
+ const fixActions = {
484
+ 'Memory Database': async () => {
485
+ try {
486
+ const swarmDir = join(process.cwd(), '.swarm');
487
+ if (!existsSync(swarmDir))
488
+ mkdirSync(swarmDir, { recursive: true });
489
+ const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
490
+ const result = await initializeMemoryDatabase({ force: true, verbose: false });
491
+ return result.success;
492
+ }
493
+ catch {
494
+ // Fall back to CLI
495
+ return runFixCommand('npx moflo memory init --force');
496
+ }
497
+ },
498
+ 'Embeddings': async () => {
499
+ try {
500
+ // Step 1: ensure memory DB exists
501
+ const swarmDir = join(process.cwd(), '.swarm');
502
+ if (!existsSync(swarmDir))
503
+ mkdirSync(swarmDir, { recursive: true });
504
+ const dbPath = join(swarmDir, 'memory.db');
505
+ if (!existsSync(dbPath)) {
506
+ const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
507
+ await initializeMemoryDatabase({ force: true, verbose: false });
508
+ }
509
+ // Step 2: attempt embeddings init via CLI
510
+ return runFixCommand('npx moflo embeddings init --force');
511
+ }
512
+ catch {
513
+ return runFixCommand('npx moflo memory init --force');
514
+ }
515
+ },
516
+ 'Config File': async () => {
517
+ try {
518
+ const cfDir = join(process.cwd(), '.claude-flow');
519
+ if (!existsSync(cfDir))
520
+ mkdirSync(cfDir, { recursive: true });
521
+ return runFixCommand('npx moflo config init');
522
+ }
523
+ catch {
524
+ return false;
525
+ }
526
+ },
527
+ 'Daemon Status': async () => {
528
+ // Clean stale locks, then try to start daemon
529
+ const lockFile = join(process.cwd(), '.claude-flow', 'daemon.lock');
530
+ const pidFile = join(process.cwd(), '.claude-flow', 'daemon.pid');
531
+ try {
532
+ if (existsSync(lockFile)) {
533
+ const { unlinkSync } = await import('fs');
534
+ unlinkSync(lockFile);
535
+ }
536
+ if (existsSync(pidFile)) {
537
+ const { unlinkSync } = await import('fs');
538
+ unlinkSync(pidFile);
539
+ }
540
+ }
541
+ catch { /* best effort */ }
542
+ return runFixCommand('npx moflo daemon start');
543
+ },
544
+ 'MCP Servers': async () => {
545
+ return runFixCommand('claude mcp add moflo -- npx -y moflo mcp start');
546
+ },
547
+ 'Claude Code CLI': async () => {
548
+ return installClaudeCode();
549
+ },
550
+ 'Zombie Processes': async () => {
551
+ const result = await findZombieProcesses(true);
552
+ return result.killed > 0 || result.found === 0;
553
+ },
554
+ };
555
+ const fixFn = fixActions[check.name];
556
+ if (fixFn) {
557
+ try {
558
+ output.writeln(output.dim(` Fixing: ${check.name}...`));
559
+ const success = await fixFn();
560
+ if (success) {
561
+ output.writeln(output.success(` Fixed: ${check.name}`));
562
+ }
563
+ else {
564
+ output.writeln(output.warning(` Fix attempted but may need manual action: ${check.fix}`));
565
+ }
566
+ return success;
567
+ }
568
+ catch (e) {
569
+ output.writeln(output.warning(` Fix failed: ${e instanceof Error ? e.message : String(e)}`));
570
+ return false;
571
+ }
572
+ }
573
+ // Generic: try running the fix command directly if it looks like a shell command
574
+ if (check.fix.startsWith('npx ') || check.fix.startsWith('npm ') || check.fix.startsWith('claude ')) {
575
+ return runFixCommand(check.fix);
576
+ }
577
+ return false;
578
+ }
579
+ /**
580
+ * Run a shell command as a fix action. Returns true on exit code 0.
581
+ */
582
+ async function runFixCommand(cmd) {
583
+ try {
584
+ await execAsync(cmd, {
585
+ encoding: 'utf8',
586
+ timeout: 30000,
587
+ shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh',
588
+ env: { ...process.env },
589
+ windowsHide: true,
590
+ });
591
+ return true;
592
+ }
593
+ catch {
594
+ return false;
595
+ }
596
+ }
597
+ // Check test directories configured in moflo.yaml
598
+ async function checkTestDirs() {
599
+ const yamlPath = join(process.cwd(), 'moflo.yaml');
600
+ if (!existsSync(yamlPath)) {
601
+ return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
602
+ }
603
+ try {
604
+ const content = readFileSync(yamlPath, 'utf-8');
605
+ // Check if tests section exists
606
+ const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
607
+ if (!testsBlock) {
608
+ return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
609
+ }
610
+ // Extract configured directories
611
+ const items = testsBlock[1].match(/-\s+(.+)/g);
612
+ if (!items || items.length === 0) {
613
+ return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
614
+ }
615
+ const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
616
+ const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
617
+ const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
618
+ // Check auto_index.tests flag
619
+ const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
620
+ const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
621
+ const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
622
+ if (missing.length > 0 && existing.length === 0) {
623
+ return {
624
+ name: 'Test Directories',
625
+ status: 'warn',
626
+ message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
627
+ };
628
+ }
629
+ if (missing.length > 0) {
630
+ return {
631
+ name: 'Test Directories',
632
+ status: 'warn',
633
+ message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
634
+ };
635
+ }
636
+ return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
637
+ }
638
+ catch {
639
+ return { name: 'Test Directories', status: 'warn', message: 'Unable to parse moflo.yaml' };
640
+ }
641
+ }
642
+ // Check agentic-flow v3 integration (filesystem-based to avoid slow WASM/DB init)
643
+ async function checkAgenticFlow() {
644
+ try {
645
+ // Walk common node_modules paths to find agentic-flow/package.json
646
+ const candidates = [
647
+ join(process.cwd(), 'node_modules', 'agentic-flow', 'package.json'),
648
+ join(process.cwd(), '..', 'node_modules', 'agentic-flow', 'package.json'),
649
+ ];
650
+ let pkgJsonPath = null;
651
+ for (const p of candidates) {
652
+ if (existsSync(p)) {
653
+ pkgJsonPath = p;
654
+ break;
655
+ }
656
+ }
657
+ if (!pkgJsonPath) {
658
+ return {
659
+ name: 'agentic-flow',
660
+ status: 'warn',
661
+ message: 'Not installed (optional — embeddings/routing will use fallbacks)',
662
+ fix: 'npm install agentic-flow@latest'
663
+ };
664
+ }
665
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
666
+ const version = pkg.version || 'unknown';
667
+ const exports = pkg.exports || {};
668
+ const features = [
669
+ exports['./reasoningbank'] ? 'ReasoningBank' : null,
670
+ exports['./router'] ? 'Router' : null,
671
+ exports['./transport/quic'] ? 'QUIC' : null,
672
+ ].filter(Boolean);
673
+ return {
674
+ name: 'agentic-flow',
675
+ status: 'pass',
676
+ message: `v${version} (${features.join(', ')})`
677
+ };
678
+ }
679
+ catch {
680
+ return { name: 'agentic-flow', status: 'warn', message: 'Check failed' };
681
+ }
682
+ }
683
+ // Check semantic search quality verify no 0.500 keyword fallback scores
684
+ async function checkSemanticQuality() {
685
+ try {
686
+ const { searchEntries } = await import('../memory/memory-initializer.js');
687
+ const result = await searchEntries({
688
+ query: 'test infrastructure health check',
689
+ namespace: 'patterns',
690
+ limit: 5,
691
+ threshold: 0.1
692
+ });
693
+ if (!result.success || result.results.length === 0) {
694
+ return {
695
+ name: 'Semantic Quality',
696
+ status: 'warn',
697
+ message: 'No search results (empty database or no patterns namespace)',
698
+ };
699
+ }
700
+ const scores = result.results.map((r) => r.score);
701
+ const allSame = scores.every((s) => s === scores[0]);
702
+ const hasFallback = scores.some((s) => s === 0.5);
703
+ if (hasFallback) {
704
+ return {
705
+ name: 'Semantic Quality',
706
+ status: 'fail',
707
+ message: `${scores.length} results, scores include 0.500 fallback (keyword-only, no embeddings)`,
708
+ fix: 'Re-index with: npx moflo embeddings build --force'
709
+ };
710
+ }
711
+ if (allSame && scores.length > 1) {
712
+ return {
713
+ name: 'Semantic Quality',
714
+ status: 'warn',
715
+ message: `${scores.length} results, all scores identical (${scores[0].toFixed(3)}) — degraded search`,
716
+ };
717
+ }
718
+ const topScore = Math.max(...scores);
719
+ return {
720
+ name: 'Semantic Quality',
721
+ status: topScore >= 0.3 ? 'pass' : 'warn',
722
+ message: `${scores.length} results, top ${topScore.toFixed(3)}, varied (semantic search active)`,
723
+ };
724
+ }
725
+ catch (e) {
726
+ return {
727
+ name: 'Semantic Quality',
728
+ status: 'warn',
729
+ message: `Check failed: ${e instanceof Error ? e.message.split('\n')[0] : 'error'}`,
730
+ };
731
+ }
732
+ }
733
+ // Check intelligence layer: SONA, EWC++, LoRA, Flash Attention, ReasoningBank
734
+ // Exercises each component with a lightweight functional test rather than just checking "loaded".
735
+ async function checkIntelligence() {
736
+ try {
737
+ // @ts-ignore neural is not in tsconfig project references but is available at runtime
738
+ // Import neural module — path is relative to compiled output at dist/src/commands/
739
+ const neural = await import('../../../../neural/dist/index.js');
740
+ const results = [];
741
+ const failures = [];
742
+ // 1. SONA — create manager, run trajectory lifecycle
743
+ try {
744
+ const sona = neural.createSONAManager('balanced');
745
+ await sona.initialize();
746
+ const tid = sona.beginTrajectory('doctor-check', 'general');
747
+ const embedding = new Float32Array(64).fill(0.1);
748
+ sona.recordStep(tid, 'test-action', 0.8, embedding);
749
+ const traj = sona.completeTrajectory(tid, 0.9);
750
+ if (traj && traj.steps.length > 0) {
751
+ results.push('SONA');
752
+ }
753
+ else {
754
+ failures.push('SONA (no trajectory output)');
755
+ }
756
+ await sona.cleanup();
757
+ }
758
+ catch (e) {
759
+ failures.push(`SONA (${e instanceof Error ? e.message : 'error'})`);
760
+ }
761
+ // 2. ReasoningBank — store + retrieve
762
+ try {
763
+ const rb = neural.createReasoningBank();
764
+ const embedding = new Float32Array(64).fill(0.2);
765
+ rb.storeTrajectory({
766
+ id: 'doctor-test',
767
+ context: 'health check',
768
+ domain: 'general',
769
+ mode: 'balanced',
770
+ steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
771
+ startTime: Date.now(),
772
+ endTime: Date.now(),
773
+ quality: 1,
774
+ });
775
+ const retrieved = rb.retrieve(embedding, 1);
776
+ if (retrieved.length > 0) {
777
+ results.push('ReasoningBank');
778
+ }
779
+ else {
780
+ failures.push('ReasoningBank (retrieve failed)');
781
+ }
782
+ }
783
+ catch (e) {
784
+ failures.push(`ReasoningBank (${e instanceof Error ? e.message : 'error'})`);
785
+ }
786
+ // 3. PatternLearner extract + match
787
+ try {
788
+ const pl = neural.createPatternLearner();
789
+ const embedding = new Float32Array(64).fill(0.3);
790
+ pl.extractPattern({
791
+ id: 'doctor-pl', context: 'test', domain: 'general', mode: 'balanced',
792
+ steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
793
+ startTime: Date.now(), endTime: Date.now(), quality: 1,
794
+ }, { trajectoryId: 'doctor-pl', keyInsights: ['test'], compressedEmbedding: embedding, timestamp: Date.now() });
795
+ const matches = pl.findMatches(embedding, 1);
796
+ if (matches.length > 0) {
797
+ results.push('PatternLearner');
798
+ }
799
+ else {
800
+ failures.push('PatternLearner (no matches)');
801
+ }
802
+ }
803
+ catch (e) {
804
+ failures.push(`PatternLearner (${e instanceof Error ? e.message : 'error'})`);
805
+ }
806
+ // 4. SONALearningEngine (MicroLoRA + EWC++)
807
+ try {
808
+ const engine = neural.createSONALearningEngine();
809
+ const ctx = { task: 'doctor', complexity: 0.5, domain: 'general', agentCount: 1, recentPerformance: 0.8 };
810
+ const adapted = engine.adapt(ctx);
811
+ const stats = engine.getStats();
812
+ const components = [];
813
+ if (adapted && adapted.learningRate !== undefined)
814
+ components.push('LoRA');
815
+ if (stats.ewcConsolidations !== undefined)
816
+ components.push('EWC++');
817
+ if (components.length > 0) {
818
+ results.push(...components);
819
+ }
820
+ else {
821
+ failures.push('LoRA/EWC++ (adapt returned no data)');
822
+ }
823
+ }
824
+ catch (e) {
825
+ failures.push(`LoRA/EWC++ (${e instanceof Error ? e.message : 'error'})`);
826
+ }
827
+ // 5. RL Algorithms — quick instantiation check
828
+ try {
829
+ const algNames = [];
830
+ const ppo = neural.createPPO();
831
+ if (ppo)
832
+ algNames.push('PPO');
833
+ const dqn = neural.createDQN();
834
+ if (dqn)
835
+ algNames.push('DQN');
836
+ const ql = neural.createQLearning();
837
+ if (ql)
838
+ algNames.push('Q-Learn');
839
+ if (algNames.length > 0) {
840
+ results.push(`RL(${algNames.join('+')})`);
841
+ }
842
+ }
843
+ catch (e) {
844
+ failures.push(`RL (${e instanceof Error ? e.message : 'error'})`);
845
+ }
846
+ if (failures.length > 0) {
847
+ return {
848
+ name: 'Intelligence',
849
+ status: results.length > 0 ? 'warn' : 'fail',
850
+ message: `${results.join(', ')} OK; FAILED: ${failures.join(', ')}`,
851
+ fix: 'Check neural module imports and dependencies',
852
+ };
853
+ }
854
+ return {
855
+ name: 'Intelligence',
856
+ status: 'pass',
857
+ message: results.join(', '),
858
+ };
859
+ }
860
+ catch (e) {
861
+ return {
862
+ name: 'Intelligence',
863
+ status: 'warn',
864
+ message: `Module unavailable: ${e instanceof Error ? e.message.split('\n')[0] : 'import failed'}`,
865
+ fix: 'Ensure @claude-flow/neural is built (npm run build)',
866
+ };
867
+ }
868
+ }
869
+ // Check whether a given PID is still running.
870
+ // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
871
+ // needing PowerShell or /proc — Node handles the platform abstraction.
872
+ function isProcessAlive(pid) {
873
+ try {
874
+ process.kill(pid, 0);
875
+ return true;
876
+ }
877
+ catch {
878
+ return false;
879
+ }
880
+ }
881
+ // Fast path: kill processes tracked in the shared ProcessManager registry.
882
+ // This avoids the expensive OS-level process scan for known background tasks.
883
+ function killTrackedProcesses() {
884
+ const registryFile = join(process.cwd(), '.claude-flow', 'background-pids.json');
885
+ const lockFile = join(process.cwd(), '.claude-flow', 'spawn.lock');
886
+ let killed = 0;
887
+ try {
888
+ if (existsSync(registryFile)) {
889
+ const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
890
+ for (const entry of entries) {
891
+ if (!isProcessAlive(entry.pid))
892
+ continue;
893
+ try {
894
+ if (process.platform === 'win32') {
895
+ execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
896
+ }
897
+ else {
898
+ process.kill(entry.pid, 'SIGKILL');
899
+ }
900
+ killed++;
901
+ }
902
+ catch { /* already gone */ }
903
+ }
904
+ // Clear registry
905
+ writeFileSync(registryFile, '[]');
906
+ }
907
+ }
908
+ catch { /* non-fatal */ }
909
+ // Remove spawn lock
910
+ try {
911
+ if (existsSync(lockFile))
912
+ unlinkSync(lockFile);
913
+ }
914
+ catch { /* ok */ }
915
+ return killed;
916
+ }
917
+ // Find and optionally kill orphaned moflo/claude-flow node processes.
918
+ // A process is only "orphaned" if its parent is no longer alive — meaning
919
+ // nothing will clean it up. MCP servers spawned by a live Claude Code session
920
+ // have a live parent (claude.exe) and must not be flagged.
921
+ async function findZombieProcesses(kill = false) {
922
+ const legitimatePid = getDaemonLockHolder(process.cwd());
923
+ const currentPid = process.pid;
924
+ const parentPid = process.ppid;
925
+ const found = [];
926
+ let killed = 0;
927
+ // Collect candidates as { pid, ppid } so we can check parent liveness
928
+ const candidates = [];
929
+ try {
930
+ if (process.platform === 'win32') {
931
+ // Windows: include ParentProcessId so we can verify orphan status
932
+ const result = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name=\'node.exe\'\\" | Select-Object ProcessId,ParentProcessId,CommandLine | Format-Table -AutoSize -Wrap"', { encoding: 'utf-8', timeout: 10000, windowsHide: true });
933
+ const lines = result.split('\n');
934
+ for (const line of lines) {
935
+ if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
936
+ // Format-Table columns: ProcessId ParentProcessId CommandLine...
937
+ const match = line.match(/^\s*(\d+)\s+(\d+)/);
938
+ if (match) {
939
+ candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
940
+ }
941
+ }
942
+ }
943
+ }
944
+ else {
945
+ // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
946
+ const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
947
+ const lines = result.trim().split('\n');
948
+ for (const line of lines) {
949
+ const match = line.trim().match(/^(\d+)\s+(\d+)/);
950
+ if (match) {
951
+ candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
952
+ }
953
+ }
954
+ }
955
+ }
956
+ catch {
957
+ // No matches found (grep exits non-zero) or command failed
958
+ }
959
+ // Filter: skip known-good PIDs and processes whose parent is still alive.
960
+ // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
961
+ for (const { pid, ppid } of candidates) {
962
+ if (pid === currentPid || pid === parentPid || pid === legitimatePid)
963
+ continue;
964
+ if (isProcessAlive(ppid))
965
+ continue;
966
+ // Defense-in-depth: detached daemons have dead parents by design.
967
+ // Even if the lock file is missing/corrupted, don't kill a running daemon.
968
+ if (isDaemonProcess(pid))
969
+ continue;
970
+ found.push(pid);
971
+ }
972
+ if (kill && found.length > 0) {
973
+ for (const pid of found) {
974
+ try {
975
+ if (process.platform === 'win32') {
976
+ execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
977
+ }
978
+ else {
979
+ process.kill(pid, 'SIGKILL');
980
+ }
981
+ killed++;
982
+ }
983
+ catch {
984
+ // Process may have already exited
985
+ }
986
+ }
987
+ // Clean up stale daemon lock if we killed the holder
988
+ if (legitimatePid && found.includes(legitimatePid)) {
989
+ releaseDaemonLock(process.cwd(), legitimatePid, true);
990
+ }
991
+ }
992
+ return { found: found.length, killed, pids: found };
993
+ }
994
+ // Format health check result
995
+ function formatCheck(check) {
996
+ const icon = check.status === 'pass' ? output.success('✓') :
997
+ check.status === 'warn' ? output.warning('⚠') :
998
+ output.error('');
999
+ return `${icon} ${check.name}: ${check.message}`;
1000
+ }
1001
+ // Main doctor command
1002
+ export const doctorCommand = {
1003
+ name: 'doctor',
1004
+ description: 'System diagnostics and health checks',
1005
+ options: [
1006
+ {
1007
+ name: 'fix',
1008
+ short: 'f',
1009
+ description: 'Automatically fix issues where possible',
1010
+ type: 'boolean',
1011
+ default: false
1012
+ },
1013
+ {
1014
+ name: 'install',
1015
+ short: 'i',
1016
+ description: 'Auto-install missing dependencies (Claude Code CLI)',
1017
+ type: 'boolean',
1018
+ default: false
1019
+ },
1020
+ {
1021
+ name: 'component',
1022
+ short: 'c',
1023
+ description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript, semantic, intelligence)',
1024
+ type: 'string'
1025
+ },
1026
+ {
1027
+ name: 'verbose',
1028
+ short: 'v',
1029
+ description: 'Verbose output',
1030
+ type: 'boolean',
1031
+ default: false
1032
+ },
1033
+ {
1034
+ name: 'kill-zombies',
1035
+ short: 'k',
1036
+ description: 'Find and kill orphaned moflo/claude-flow node processes',
1037
+ type: 'boolean',
1038
+ default: false
1039
+ }
1040
+ ],
1041
+ examples: [
1042
+ { command: 'claude-flow doctor', description: 'Run full health check' },
1043
+ { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' },
1044
+ { command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },
1045
+ { command: 'claude-flow doctor --kill-zombies', description: 'Find and kill zombie processes' },
1046
+ { command: 'claude-flow doctor -c version', description: 'Check for stale npx cache' },
1047
+ { command: 'claude-flow doctor -c claude', description: 'Check Claude Code CLI only' }
1048
+ ],
1049
+ action: async (ctx) => {
1050
+ const showFix = ctx.flags.fix;
1051
+ const autoInstall = ctx.flags.install;
1052
+ const component = ctx.flags.component;
1053
+ const verbose = ctx.flags.verbose;
1054
+ const killZombies = ctx.flags['kill-zombies'];
1055
+ output.writeln();
1056
+ output.writeln(output.bold('MoFlo Doctor'));
1057
+ output.writeln(output.dim('System diagnostics and health check'));
1058
+ output.writeln(output.dim('─'.repeat(50)));
1059
+ output.writeln();
1060
+ // Handle --kill-zombies early
1061
+ if (killZombies) {
1062
+ output.writeln(output.bold('Zombie Process Scan'));
1063
+ output.writeln();
1064
+ // Fast path: kill tracked processes from the shared registry first
1065
+ const registryKilled = killTrackedProcesses();
1066
+ if (registryKilled > 0) {
1067
+ output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
1068
+ }
1069
+ // Slow path: OS-level scan for any remaining orphans
1070
+ const scan = await findZombieProcesses(false);
1071
+ if (scan.found === 0) {
1072
+ if (registryKilled === 0) {
1073
+ output.writeln(output.success(' No orphaned moflo processes found'));
1074
+ }
1075
+ }
1076
+ else {
1077
+ output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
1078
+ // Kill them
1079
+ const result = await findZombieProcesses(true);
1080
+ if (result.killed > 0) {
1081
+ output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
1082
+ }
1083
+ if (result.killed < result.found) {
1084
+ output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
1085
+ }
1086
+ }
1087
+ output.writeln();
1088
+ output.writeln(output.dim('─'.repeat(50)));
1089
+ output.writeln();
1090
+ }
1091
+ const checkZombieProcesses = async () => {
1092
+ try {
1093
+ const scan = await findZombieProcesses(false);
1094
+ if (scan.found === 0) {
1095
+ return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
1096
+ }
1097
+ return {
1098
+ name: 'Zombie Processes',
1099
+ status: 'warn',
1100
+ message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
1101
+ fix: 'moflo doctor --kill-zombies'
1102
+ };
1103
+ }
1104
+ catch {
1105
+ return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
1106
+ }
1107
+ };
1108
+ const allChecks = [
1109
+ checkVersionFreshness,
1110
+ checkNodeVersion,
1111
+ checkNpmVersion,
1112
+ checkClaudeCode,
1113
+ checkGit,
1114
+ checkGitRepo,
1115
+ checkConfigFile,
1116
+ checkDaemonStatus,
1117
+ checkMemoryDatabase,
1118
+ checkEmbeddings,
1119
+ checkTestDirs,
1120
+ checkMcpServers,
1121
+ checkDiskSpace,
1122
+ checkBuildTools,
1123
+ checkAgenticFlow,
1124
+ checkSemanticQuality,
1125
+ checkIntelligence,
1126
+ checkZombieProcesses
1127
+ ];
1128
+ const componentMap = {
1129
+ 'version': checkVersionFreshness,
1130
+ 'freshness': checkVersionFreshness,
1131
+ 'node': checkNodeVersion,
1132
+ 'npm': checkNpmVersion,
1133
+ 'claude': checkClaudeCode,
1134
+ 'config': checkConfigFile,
1135
+ 'daemon': checkDaemonStatus,
1136
+ 'memory': checkMemoryDatabase,
1137
+ 'embeddings': checkEmbeddings,
1138
+ 'git': checkGit,
1139
+ 'mcp': checkMcpServers,
1140
+ 'disk': checkDiskSpace,
1141
+ 'typescript': checkBuildTools,
1142
+ 'tests': checkTestDirs,
1143
+ 'agentic-flow': checkAgenticFlow,
1144
+ 'semantic': checkSemanticQuality,
1145
+ 'quality': checkSemanticQuality,
1146
+ 'intelligence': checkIntelligence
1147
+ };
1148
+ let checksToRun = allChecks;
1149
+ if (component && componentMap[component]) {
1150
+ checksToRun = [componentMap[component]];
1151
+ }
1152
+ const results = [];
1153
+ const fixes = [];
1154
+ // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
1155
+ const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });
1156
+ spinner.start();
1157
+ try {
1158
+ // Execute all checks concurrently
1159
+ const checkResults = await Promise.allSettled(checksToRun.map(check => check()));
1160
+ spinner.stop();
1161
+ // Process results in order
1162
+ for (const settledResult of checkResults) {
1163
+ if (settledResult.status === 'fulfilled') {
1164
+ const result = settledResult.value;
1165
+ results.push(result);
1166
+ output.writeln(formatCheck(result));
1167
+ if (result.fix && (result.status === 'fail' || result.status === 'warn')) {
1168
+ fixes.push(`${result.name}: ${result.fix}`);
1169
+ }
1170
+ }
1171
+ else {
1172
+ const errorResult = {
1173
+ name: 'Check',
1174
+ status: 'fail',
1175
+ message: settledResult.reason?.message || 'Unknown error'
1176
+ };
1177
+ results.push(errorResult);
1178
+ output.writeln(formatCheck(errorResult));
1179
+ }
1180
+ }
1181
+ }
1182
+ catch (error) {
1183
+ spinner.stop();
1184
+ output.writeln(output.error('Failed to run health checks'));
1185
+ }
1186
+ // Auto-install missing dependencies if requested
1187
+ if (autoInstall) {
1188
+ const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
1189
+ if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
1190
+ const installed = await installClaudeCode();
1191
+ if (installed) {
1192
+ // Re-check Claude Code after installation
1193
+ const newCheck = await checkClaudeCode();
1194
+ const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1195
+ if (idx !== -1) {
1196
+ results[idx] = newCheck;
1197
+ // Update fixes list
1198
+ const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1199
+ if (fixIdx !== -1 && newCheck.status === 'pass') {
1200
+ fixes.splice(fixIdx, 1);
1201
+ }
1202
+ }
1203
+ output.writeln(formatCheck(newCheck));
1204
+ }
1205
+ }
1206
+ }
1207
+ // Summary
1208
+ const passed = results.filter(r => r.status === 'pass').length;
1209
+ const warnings = results.filter(r => r.status === 'warn').length;
1210
+ const failed = results.filter(r => r.status === 'fail').length;
1211
+ output.writeln();
1212
+ output.writeln(output.dim('─'.repeat(50)));
1213
+ output.writeln();
1214
+ const summaryParts = [
1215
+ output.success(`${passed} passed`),
1216
+ warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1217
+ failed > 0 ? output.error(`${failed} failed`) : null
1218
+ ].filter(Boolean);
1219
+ output.writeln(`Summary: ${summaryParts.join(', ')}`);
1220
+ // Auto-fix or show fixes
1221
+ if (showFix && fixes.length > 0) {
1222
+ output.writeln();
1223
+ output.writeln(output.bold('Auto-fixing issues...'));
1224
+ output.writeln();
1225
+ const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1226
+ let fixed = 0;
1227
+ const unfixed = [];
1228
+ for (const check of fixableResults) {
1229
+ const success = await autoFixCheck(check);
1230
+ if (success) {
1231
+ fixed++;
1232
+ }
1233
+ else {
1234
+ unfixed.push(`${check.name}: ${check.fix}`);
1235
+ }
1236
+ }
1237
+ if (fixed > 0) {
1238
+ output.writeln();
1239
+ output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1240
+ }
1241
+ if (unfixed.length > 0) {
1242
+ output.writeln();
1243
+ output.writeln(output.bold('Manual fixes needed:'));
1244
+ for (const fix of unfixed) {
1245
+ output.writeln(output.dim(` ${fix}`));
1246
+ }
1247
+ }
1248
+ // Re-run checks to show updated status
1249
+ if (fixed > 0) {
1250
+ output.writeln();
1251
+ output.writeln(output.dim('Re-checking...'));
1252
+ output.writeln();
1253
+ const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1254
+ let rePassed = 0, reWarnings = 0, reFailed = 0;
1255
+ for (const sr of reResults) {
1256
+ if (sr.status === 'fulfilled') {
1257
+ output.writeln(formatCheck(sr.value));
1258
+ if (sr.value.status === 'pass')
1259
+ rePassed++;
1260
+ else if (sr.value.status === 'warn')
1261
+ reWarnings++;
1262
+ else
1263
+ reFailed++;
1264
+ }
1265
+ }
1266
+ output.writeln();
1267
+ output.writeln(output.dim('─'.repeat(50)));
1268
+ const reSummary = [
1269
+ output.success(`${rePassed} passed`),
1270
+ reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1271
+ reFailed > 0 ? output.error(`${reFailed} failed`) : null
1272
+ ].filter(Boolean);
1273
+ output.writeln(`After fix: ${reSummary.join(', ')}`);
1274
+ }
1275
+ }
1276
+ else if (fixes.length > 0 && !showFix) {
1277
+ output.writeln();
1278
+ output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1279
+ }
1280
+ // Overall result
1281
+ if (failed > 0) {
1282
+ output.writeln();
1283
+ output.writeln(output.error('Some checks failed. Please address the issues above.'));
1284
+ return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1285
+ }
1286
+ else if (warnings > 0) {
1287
+ output.writeln();
1288
+ output.writeln(output.warning('All checks passed with some warnings.'));
1289
+ return { success: true, data: { passed, warnings, failed, results } };
1290
+ }
1291
+ else {
1292
+ output.writeln();
1293
+ output.writeln(output.success('All checks passed! System is healthy.'));
1294
+ return { success: true, data: { passed, warnings, failed, results } };
1295
+ }
1296
+ }
1297
+ };
1298
+ export default doctorCommand;
1108
1299
  //# sourceMappingURL=doctor.js.map