moflo 4.8.30 → 4.8.32

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 (390) hide show
  1. package/.claude/guidance/shipped/moflo.md +13 -35
  2. package/bin/generate-code-map.mjs +1 -1
  3. package/bin/index-guidance.mjs +1 -1
  4. package/bin/index-tests.mjs +1 -1
  5. package/bin/setup-project.mjs +1 -1
  6. package/package.json +6 -7
  7. package/src/@claude-flow/cli/dist/src/commands/doctor.js +1107 -1244
  8. package/src/@claude-flow/cli/package.json +1 -1
  9. package/.claude/agents/browser/browser-agent.yaml +0 -182
  10. package/.claude/agents/database-specialist.yaml +0 -21
  11. package/.claude/agents/index.yaml +0 -17
  12. package/.claude/agents/project-coordinator.yaml +0 -15
  13. package/.claude/agents/python-specialist.yaml +0 -21
  14. package/.claude/agents/security-auditor.yaml +0 -20
  15. package/.claude/agents/typescript-specialist.yaml +0 -21
  16. package/.claude/checkpoints/1767754460.json +0 -8
  17. package/.claude/config/v3-dependency-optimization.json +0 -266
  18. package/.claude/config/v3-performance-targets.json +0 -251
  19. package/.claude/guidance/moflo-bootstrap.md +0 -129
  20. package/.claude/mcp.json +0 -13
  21. package/.claude/settings.json +0 -351
  22. package/.claude/settings.local.json +0 -18
  23. package/.claude/skills/agentdb-advanced/SKILL.md +0 -550
  24. package/.claude/skills/agentdb-learning/SKILL.md +0 -545
  25. package/.claude/skills/agentdb-memory-patterns/SKILL.md +0 -339
  26. package/.claude/skills/agentdb-optimization/SKILL.md +0 -509
  27. package/.claude/skills/agentdb-vector-search/SKILL.md +0 -339
  28. package/.claude/skills/browser/SKILL.md +0 -204
  29. package/.claude/skills/fl/SKILL.md +0 -583
  30. package/.claude/skills/flo/SKILL.md +0 -583
  31. package/.claude/skills/github-code-review/SKILL.md +0 -1140
  32. package/.claude/skills/github-multi-repo/SKILL.md +0 -874
  33. package/.claude/skills/github-project-management/SKILL.md +0 -1277
  34. package/.claude/skills/github-release-management/SKILL.md +0 -1081
  35. package/.claude/skills/github-workflow-automation/SKILL.md +0 -1065
  36. package/.claude/skills/hive-mind-advanced/SKILL.md +0 -712
  37. package/.claude/skills/hooks-automation/SKILL.md +0 -1201
  38. package/.claude/skills/pair-programming/SKILL.md +0 -1202
  39. package/.claude/skills/performance-analysis/SKILL.md +0 -563
  40. package/.claude/skills/reasoningbank-agentdb/SKILL.md +0 -446
  41. package/.claude/skills/reasoningbank-intelligence/SKILL.md +0 -201
  42. package/.claude/skills/skill-builder/SKILL.md +0 -910
  43. package/.claude/skills/sparc-methodology/SKILL.md +0 -1115
  44. package/.claude/skills/stream-chain/SKILL.md +0 -563
  45. package/.claude/skills/swarm-advanced/SKILL.md +0 -973
  46. package/.claude/skills/swarm-orchestration/SKILL.md +0 -179
  47. package/.claude/skills/v3-cli-modernization/SKILL.md +0 -872
  48. package/.claude/skills/v3-core-implementation/SKILL.md +0 -797
  49. package/.claude/skills/v3-ddd-architecture/SKILL.md +0 -442
  50. package/.claude/skills/v3-integration-deep/SKILL.md +0 -241
  51. package/.claude/skills/v3-mcp-optimization/SKILL.md +0 -777
  52. package/.claude/skills/v3-memory-unification/SKILL.md +0 -174
  53. package/.claude/skills/v3-performance-optimization/SKILL.md +0 -390
  54. package/.claude/skills/v3-security-overhaul/SKILL.md +0 -82
  55. package/.claude/skills/v3-swarm-coordination/SKILL.md +0 -340
  56. package/.claude/skills/verification-quality/SKILL.md +0 -649
  57. package/.claude/skills/worker-benchmarks/skill.md +0 -135
  58. package/.claude/skills/worker-integration/skill.md +0 -154
  59. package/.claude/workflow-state.json +0 -9
  60. package/src/@claude-flow/cli/dist/src/appliance/gguf-engine.d.ts +0 -91
  61. package/src/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.d.ts +0 -102
  62. package/src/@claude-flow/cli/dist/src/appliance/rvfa-builder.d.ts +0 -44
  63. package/src/@claude-flow/cli/dist/src/appliance/rvfa-distribution.d.ts +0 -97
  64. package/src/@claude-flow/cli/dist/src/appliance/rvfa-format.d.ts +0 -111
  65. package/src/@claude-flow/cli/dist/src/appliance/rvfa-runner.d.ts +0 -69
  66. package/src/@claude-flow/cli/dist/src/appliance/rvfa-signing.d.ts +0 -123
  67. package/src/@claude-flow/cli/dist/src/benchmarks/pretrain/index.d.ts +0 -58
  68. package/src/@claude-flow/cli/dist/src/commands/agent.d.ts +0 -8
  69. package/src/@claude-flow/cli/dist/src/commands/analyze.d.ts +0 -19
  70. package/src/@claude-flow/cli/dist/src/commands/appliance-advanced.d.ts +0 -9
  71. package/src/@claude-flow/cli/dist/src/commands/appliance.d.ts +0 -8
  72. package/src/@claude-flow/cli/dist/src/commands/benchmark.d.ts +0 -10
  73. package/src/@claude-flow/cli/dist/src/commands/claims.d.ts +0 -10
  74. package/src/@claude-flow/cli/dist/src/commands/completions.d.ts +0 -10
  75. package/src/@claude-flow/cli/dist/src/commands/config.d.ts +0 -8
  76. package/src/@claude-flow/cli/dist/src/commands/daemon.d.ts +0 -8
  77. package/src/@claude-flow/cli/dist/src/commands/deployment.d.ts +0 -10
  78. package/src/@claude-flow/cli/dist/src/commands/diagnose.d.ts +0 -16
  79. package/src/@claude-flow/cli/dist/src/commands/doctor.d.ts +0 -10
  80. package/src/@claude-flow/cli/dist/src/commands/embeddings.d.ts +0 -18
  81. package/src/@claude-flow/cli/dist/src/commands/gate.d.ts +0 -23
  82. package/src/@claude-flow/cli/dist/src/commands/github.d.ts +0 -12
  83. package/src/@claude-flow/cli/dist/src/commands/guidance.d.ts +0 -8
  84. package/src/@claude-flow/cli/dist/src/commands/hive-mind.d.ts +0 -11
  85. package/src/@claude-flow/cli/dist/src/commands/hooks.d.ts +0 -8
  86. package/src/@claude-flow/cli/dist/src/commands/index.d.ts +0 -115
  87. package/src/@claude-flow/cli/dist/src/commands/init.d.ts +0 -8
  88. package/src/@claude-flow/cli/dist/src/commands/issues.d.ts +0 -21
  89. package/src/@claude-flow/cli/dist/src/commands/mcp.d.ts +0 -11
  90. package/src/@claude-flow/cli/dist/src/commands/memory.d.ts +0 -8
  91. package/src/@claude-flow/cli/dist/src/commands/migrate.d.ts +0 -8
  92. package/src/@claude-flow/cli/dist/src/commands/neural.d.ts +0 -10
  93. package/src/@claude-flow/cli/dist/src/commands/orc.d.ts +0 -21
  94. package/src/@claude-flow/cli/dist/src/commands/performance.d.ts +0 -10
  95. package/src/@claude-flow/cli/dist/src/commands/plugins.d.ts +0 -11
  96. package/src/@claude-flow/cli/dist/src/commands/process.d.ts +0 -10
  97. package/src/@claude-flow/cli/dist/src/commands/progress.d.ts +0 -11
  98. package/src/@claude-flow/cli/dist/src/commands/providers.d.ts +0 -10
  99. package/src/@claude-flow/cli/dist/src/commands/route.d.ts +0 -16
  100. package/src/@claude-flow/cli/dist/src/commands/ruvector/backup.d.ts +0 -11
  101. package/src/@claude-flow/cli/dist/src/commands/ruvector/benchmark.d.ts +0 -11
  102. package/src/@claude-flow/cli/dist/src/commands/ruvector/import.d.ts +0 -18
  103. package/src/@claude-flow/cli/dist/src/commands/ruvector/index.d.ts +0 -29
  104. package/src/@claude-flow/cli/dist/src/commands/ruvector/init.d.ts +0 -11
  105. package/src/@claude-flow/cli/dist/src/commands/ruvector/migrate.d.ts +0 -11
  106. package/src/@claude-flow/cli/dist/src/commands/ruvector/optimize.d.ts +0 -11
  107. package/src/@claude-flow/cli/dist/src/commands/ruvector/setup.d.ts +0 -18
  108. package/src/@claude-flow/cli/dist/src/commands/ruvector/status.d.ts +0 -11
  109. package/src/@claude-flow/cli/dist/src/commands/security.d.ts +0 -10
  110. package/src/@claude-flow/cli/dist/src/commands/session.d.ts +0 -8
  111. package/src/@claude-flow/cli/dist/src/commands/start.d.ts +0 -8
  112. package/src/@claude-flow/cli/dist/src/commands/status.d.ts +0 -8
  113. package/src/@claude-flow/cli/dist/src/commands/swarm.d.ts +0 -8
  114. package/src/@claude-flow/cli/dist/src/commands/task.d.ts +0 -8
  115. package/src/@claude-flow/cli/dist/src/commands/transfer-store.d.ts +0 -13
  116. package/src/@claude-flow/cli/dist/src/commands/update.d.ts +0 -8
  117. package/src/@claude-flow/cli/dist/src/commands/workflow.d.ts +0 -8
  118. package/src/@claude-flow/cli/dist/src/config/moflo-config.d.ts +0 -93
  119. package/src/@claude-flow/cli/dist/src/config-adapter.d.ts +0 -15
  120. package/src/@claude-flow/cli/dist/src/index.d.ts +0 -81
  121. package/src/@claude-flow/cli/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  122. package/src/@claude-flow/cli/dist/src/init/claudemd-generator.d.ts +0 -30
  123. package/src/@claude-flow/cli/dist/src/init/executor.d.ts +0 -41
  124. package/src/@claude-flow/cli/dist/src/init/helpers-generator.d.ts +0 -51
  125. package/src/@claude-flow/cli/dist/src/init/index.d.ts +0 -13
  126. package/src/@claude-flow/cli/dist/src/init/mcp-generator.d.ts +0 -29
  127. package/src/@claude-flow/cli/dist/src/init/moflo-init.d.ts +0 -31
  128. package/src/@claude-flow/cli/dist/src/init/settings-generator.d.ts +0 -14
  129. package/src/@claude-flow/cli/dist/src/init/statusline-generator.d.ts +0 -28
  130. package/src/@claude-flow/cli/dist/src/init/types.d.ts +0 -285
  131. package/src/@claude-flow/cli/dist/src/mcp-client.d.ts +0 -92
  132. package/src/@claude-flow/cli/dist/src/mcp-server.d.ts +0 -161
  133. package/src/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +0 -9
  134. package/src/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.d.ts +0 -30
  135. package/src/@claude-flow/cli/dist/src/mcp-tools/analyze-tools.d.ts +0 -38
  136. package/src/@claude-flow/cli/dist/src/mcp-tools/auto-install.d.ts +0 -83
  137. package/src/@claude-flow/cli/dist/src/mcp-tools/browser-tools.d.ts +0 -13
  138. package/src/@claude-flow/cli/dist/src/mcp-tools/claims-tools.d.ts +0 -12
  139. package/src/@claude-flow/cli/dist/src/mcp-tools/config-tools.d.ts +0 -8
  140. package/src/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.d.ts +0 -13
  141. package/src/@claude-flow/cli/dist/src/mcp-tools/daa-tools.d.ts +0 -13
  142. package/src/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.d.ts +0 -9
  143. package/src/@claude-flow/cli/dist/src/mcp-tools/github-tools.d.ts +0 -13
  144. package/src/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.d.ts +0 -8
  145. package/src/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.d.ts +0 -44
  146. package/src/@claude-flow/cli/dist/src/mcp-tools/index.d.ts +0 -23
  147. package/src/@claude-flow/cli/dist/src/mcp-tools/memory-tools.d.ts +0 -14
  148. package/src/@claude-flow/cli/dist/src/mcp-tools/neural-tools.d.ts +0 -16
  149. package/src/@claude-flow/cli/dist/src/mcp-tools/performance-tools.d.ts +0 -16
  150. package/src/@claude-flow/cli/dist/src/mcp-tools/progress-tools.d.ts +0 -14
  151. package/src/@claude-flow/cli/dist/src/mcp-tools/security-tools.d.ts +0 -18
  152. package/src/@claude-flow/cli/dist/src/mcp-tools/session-tools.d.ts +0 -8
  153. package/src/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.d.ts +0 -8
  154. package/src/@claude-flow/cli/dist/src/mcp-tools/system-tools.d.ts +0 -13
  155. package/src/@claude-flow/cli/dist/src/mcp-tools/task-tools.d.ts +0 -8
  156. package/src/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.d.ts +0 -13
  157. package/src/@claude-flow/cli/dist/src/mcp-tools/transfer-tools.d.ts +0 -14
  158. package/src/@claude-flow/cli/dist/src/mcp-tools/types.d.ts +0 -31
  159. package/src/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  160. package/src/@claude-flow/cli/dist/src/memory/ewc-consolidation.d.ts +0 -271
  161. package/src/@claude-flow/cli/dist/src/memory/intelligence.d.ts +0 -285
  162. package/src/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +0 -413
  163. package/src/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +0 -405
  164. package/src/@claude-flow/cli/dist/src/memory/sona-optimizer.d.ts +0 -227
  165. package/src/@claude-flow/cli/dist/src/output.d.ts +0 -133
  166. package/src/@claude-flow/cli/dist/src/parser.d.ts +0 -51
  167. package/src/@claude-flow/cli/dist/src/plugins/manager.d.ts +0 -133
  168. package/src/@claude-flow/cli/dist/src/plugins/store/discovery.d.ts +0 -88
  169. package/src/@claude-flow/cli/dist/src/plugins/store/index.d.ts +0 -76
  170. package/src/@claude-flow/cli/dist/src/plugins/store/search.d.ts +0 -46
  171. package/src/@claude-flow/cli/dist/src/plugins/store/types.d.ts +0 -274
  172. package/src/@claude-flow/cli/dist/src/plugins/tests/demo-plugin-store.d.ts +0 -7
  173. package/src/@claude-flow/cli/dist/src/plugins/tests/standalone-test.d.ts +0 -12
  174. package/src/@claude-flow/cli/dist/src/plugins/tests/test-plugin-store.d.ts +0 -7
  175. package/src/@claude-flow/cli/dist/src/production/circuit-breaker.d.ts +0 -101
  176. package/src/@claude-flow/cli/dist/src/production/error-handler.d.ts +0 -92
  177. package/src/@claude-flow/cli/dist/src/production/index.d.ts +0 -23
  178. package/src/@claude-flow/cli/dist/src/production/monitoring.d.ts +0 -161
  179. package/src/@claude-flow/cli/dist/src/production/rate-limiter.d.ts +0 -80
  180. package/src/@claude-flow/cli/dist/src/production/retry.d.ts +0 -48
  181. package/src/@claude-flow/cli/dist/src/prompt.d.ts +0 -44
  182. package/src/@claude-flow/cli/dist/src/runtime/headless.d.ts +0 -60
  183. package/src/@claude-flow/cli/dist/src/ruvector/ast-analyzer.d.ts +0 -67
  184. package/src/@claude-flow/cli/dist/src/ruvector/coverage-router.d.ts +0 -160
  185. package/src/@claude-flow/cli/dist/src/ruvector/coverage-tools.d.ts +0 -33
  186. package/src/@claude-flow/cli/dist/src/ruvector/diff-classifier.d.ts +0 -175
  187. package/src/@claude-flow/cli/dist/src/ruvector/enhanced-model-router.d.ts +0 -146
  188. package/src/@claude-flow/cli/dist/src/ruvector/flash-attention.d.ts +0 -195
  189. package/src/@claude-flow/cli/dist/src/ruvector/graph-analyzer.d.ts +0 -187
  190. package/src/@claude-flow/cli/dist/src/ruvector/index.d.ts +0 -34
  191. package/src/@claude-flow/cli/dist/src/ruvector/lora-adapter.d.ts +0 -218
  192. package/src/@claude-flow/cli/dist/src/ruvector/model-router.d.ts +0 -220
  193. package/src/@claude-flow/cli/dist/src/ruvector/moe-router.d.ts +0 -206
  194. package/src/@claude-flow/cli/dist/src/ruvector/q-learning-router.d.ts +0 -211
  195. package/src/@claude-flow/cli/dist/src/ruvector/semantic-router.d.ts +0 -77
  196. package/src/@claude-flow/cli/dist/src/ruvector/vector-db.d.ts +0 -69
  197. package/src/@claude-flow/cli/dist/src/services/agent-router.d.ts +0 -63
  198. package/src/@claude-flow/cli/dist/src/services/agentic-flow-bridge.d.ts +0 -50
  199. package/src/@claude-flow/cli/dist/src/services/claim-service.d.ts +0 -204
  200. package/src/@claude-flow/cli/dist/src/services/container-worker-pool.d.ts +0 -197
  201. package/src/@claude-flow/cli/dist/src/services/daemon-lock.d.ts +0 -60
  202. package/src/@claude-flow/cli/dist/src/services/headless-worker-executor.d.ts +0 -304
  203. package/src/@claude-flow/cli/dist/src/services/index.d.ts +0 -13
  204. package/src/@claude-flow/cli/dist/src/services/learning-service.d.ts +0 -161
  205. package/src/@claude-flow/cli/dist/src/services/moflo-require.d.ts +0 -34
  206. package/src/@claude-flow/cli/dist/src/services/registry-api.d.ts +0 -58
  207. package/src/@claude-flow/cli/dist/src/services/ruvector-training.d.ts +0 -214
  208. package/src/@claude-flow/cli/dist/src/services/worker-daemon.d.ts +0 -225
  209. package/src/@claude-flow/cli/dist/src/services/worker-queue.d.ts +0 -194
  210. package/src/@claude-flow/cli/dist/src/services/workflow-gate.d.ts +0 -88
  211. package/src/@claude-flow/cli/dist/src/suggest.d.ts +0 -53
  212. package/src/@claude-flow/cli/dist/src/transfer/anonymization/index.d.ts +0 -25
  213. package/src/@claude-flow/cli/dist/src/transfer/deploy-seraphine.d.ts +0 -13
  214. package/src/@claude-flow/cli/dist/src/transfer/export.d.ts +0 -25
  215. package/src/@claude-flow/cli/dist/src/transfer/index.d.ts +0 -12
  216. package/src/@claude-flow/cli/dist/src/transfer/ipfs/client.d.ts +0 -109
  217. package/src/@claude-flow/cli/dist/src/transfer/ipfs/upload.d.ts +0 -95
  218. package/src/@claude-flow/cli/dist/src/transfer/models/seraphine.d.ts +0 -72
  219. package/src/@claude-flow/cli/dist/src/transfer/serialization/cfp.d.ts +0 -49
  220. package/src/@claude-flow/cli/dist/src/transfer/storage/gcs.d.ts +0 -82
  221. package/src/@claude-flow/cli/dist/src/transfer/storage/index.d.ts +0 -6
  222. package/src/@claude-flow/cli/dist/src/transfer/store/discovery.d.ts +0 -84
  223. package/src/@claude-flow/cli/dist/src/transfer/store/download.d.ts +0 -70
  224. package/src/@claude-flow/cli/dist/src/transfer/store/index.d.ts +0 -84
  225. package/src/@claude-flow/cli/dist/src/transfer/store/publish.d.ts +0 -76
  226. package/src/@claude-flow/cli/dist/src/transfer/store/registry.d.ts +0 -58
  227. package/src/@claude-flow/cli/dist/src/transfer/store/search.d.ts +0 -54
  228. package/src/@claude-flow/cli/dist/src/transfer/store/tests/standalone-test.d.ts +0 -12
  229. package/src/@claude-flow/cli/dist/src/transfer/store/types.d.ts +0 -193
  230. package/src/@claude-flow/cli/dist/src/transfer/test-seraphine.d.ts +0 -6
  231. package/src/@claude-flow/cli/dist/src/transfer/tests/test-store.d.ts +0 -7
  232. package/src/@claude-flow/cli/dist/src/transfer/types.d.ts +0 -245
  233. package/src/@claude-flow/cli/dist/src/types.d.ts +0 -198
  234. package/src/@claude-flow/cli/dist/src/update/checker.d.ts +0 -34
  235. package/src/@claude-flow/cli/dist/src/update/executor.d.ts +0 -32
  236. package/src/@claude-flow/cli/dist/src/update/index.d.ts +0 -33
  237. package/src/@claude-flow/cli/dist/src/update/rate-limiter.d.ts +0 -20
  238. package/src/@claude-flow/cli/dist/src/update/validator.d.ts +0 -17
  239. package/src/@claude-flow/guidance/dist/adversarial.d.ts +0 -284
  240. package/src/@claude-flow/guidance/dist/analyzer.d.ts +0 -530
  241. package/src/@claude-flow/guidance/dist/artifacts.d.ts +0 -283
  242. package/src/@claude-flow/guidance/dist/authority.d.ts +0 -290
  243. package/src/@claude-flow/guidance/dist/capabilities.d.ts +0 -209
  244. package/src/@claude-flow/guidance/dist/coherence.d.ts +0 -233
  245. package/src/@claude-flow/guidance/dist/compiler.d.ts +0 -87
  246. package/src/@claude-flow/guidance/dist/conformance-kit.d.ts +0 -225
  247. package/src/@claude-flow/guidance/dist/continue-gate.d.ts +0 -214
  248. package/src/@claude-flow/guidance/dist/crypto-utils.d.ts +0 -17
  249. package/src/@claude-flow/guidance/dist/evolution.d.ts +0 -282
  250. package/src/@claude-flow/guidance/dist/gates.d.ts +0 -79
  251. package/src/@claude-flow/guidance/dist/gateway.d.ts +0 -206
  252. package/src/@claude-flow/guidance/dist/generators.d.ts +0 -153
  253. package/src/@claude-flow/guidance/dist/headless.d.ts +0 -177
  254. package/src/@claude-flow/guidance/dist/hooks.d.ts +0 -109
  255. package/src/@claude-flow/guidance/dist/index.d.ts +0 -205
  256. package/src/@claude-flow/guidance/dist/ledger.d.ts +0 -162
  257. package/src/@claude-flow/guidance/dist/manifest-validator.d.ts +0 -289
  258. package/src/@claude-flow/guidance/dist/memory-gate.d.ts +0 -222
  259. package/src/@claude-flow/guidance/dist/meta-governance.d.ts +0 -265
  260. package/src/@claude-flow/guidance/dist/optimizer.d.ts +0 -104
  261. package/src/@claude-flow/guidance/dist/persistence.d.ts +0 -189
  262. package/src/@claude-flow/guidance/dist/proof.d.ts +0 -185
  263. package/src/@claude-flow/guidance/dist/retriever.d.ts +0 -116
  264. package/src/@claude-flow/guidance/dist/ruvbot-integration.d.ts +0 -370
  265. package/src/@claude-flow/guidance/dist/temporal.d.ts +0 -426
  266. package/src/@claude-flow/guidance/dist/trust.d.ts +0 -283
  267. package/src/@claude-flow/guidance/dist/truth-anchors.d.ts +0 -276
  268. package/src/@claude-flow/guidance/dist/types.d.ts +0 -378
  269. package/src/@claude-flow/guidance/dist/uncertainty.d.ts +0 -372
  270. package/src/@claude-flow/guidance/dist/wasm-kernel.d.ts +0 -48
  271. package/src/@claude-flow/memory/dist/agent-memory-scope.d.ts +0 -131
  272. package/src/@claude-flow/memory/dist/agent-memory-scope.test.d.ts +0 -8
  273. package/src/@claude-flow/memory/dist/agentdb-adapter.d.ts +0 -165
  274. package/src/@claude-flow/memory/dist/agentdb-backend.d.ts +0 -212
  275. package/src/@claude-flow/memory/dist/agentdb-backend.test.d.ts +0 -7
  276. package/src/@claude-flow/memory/dist/application/commands/delete-memory.command.d.ts +0 -65
  277. package/src/@claude-flow/memory/dist/application/commands/store-memory.command.d.ts +0 -48
  278. package/src/@claude-flow/memory/dist/application/index.d.ts +0 -12
  279. package/src/@claude-flow/memory/dist/application/queries/search-memory.query.d.ts +0 -72
  280. package/src/@claude-flow/memory/dist/application/services/memory-application-service.d.ts +0 -121
  281. package/src/@claude-flow/memory/dist/auto-memory-bridge.d.ts +0 -226
  282. package/src/@claude-flow/memory/dist/auto-memory-bridge.test.d.ts +0 -8
  283. package/src/@claude-flow/memory/dist/benchmark.test.d.ts +0 -2
  284. package/src/@claude-flow/memory/dist/cache-manager.d.ts +0 -134
  285. package/src/@claude-flow/memory/dist/controller-registry.d.ts +0 -216
  286. package/src/@claude-flow/memory/dist/controller-registry.test.d.ts +0 -14
  287. package/src/@claude-flow/memory/dist/database-provider.d.ts +0 -87
  288. package/src/@claude-flow/memory/dist/database-provider.test.d.ts +0 -7
  289. package/src/@claude-flow/memory/dist/domain/entities/memory-entry.d.ts +0 -143
  290. package/src/@claude-flow/memory/dist/domain/index.d.ts +0 -11
  291. package/src/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.d.ts +0 -102
  292. package/src/@claude-flow/memory/dist/domain/services/memory-domain-service.d.ts +0 -105
  293. package/src/@claude-flow/memory/dist/hnsw-index.d.ts +0 -111
  294. package/src/@claude-flow/memory/dist/hnsw-lite.d.ts +0 -23
  295. package/src/@claude-flow/memory/dist/hybrid-backend.d.ts +0 -245
  296. package/src/@claude-flow/memory/dist/hybrid-backend.test.d.ts +0 -8
  297. package/src/@claude-flow/memory/dist/index.d.ts +0 -204
  298. package/src/@claude-flow/memory/dist/infrastructure/index.d.ts +0 -17
  299. package/src/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.d.ts +0 -66
  300. package/src/@claude-flow/memory/dist/learning-bridge.d.ts +0 -137
  301. package/src/@claude-flow/memory/dist/learning-bridge.test.d.ts +0 -8
  302. package/src/@claude-flow/memory/dist/memory-graph.d.ts +0 -100
  303. package/src/@claude-flow/memory/dist/memory-graph.test.d.ts +0 -8
  304. package/src/@claude-flow/memory/dist/migration.d.ts +0 -68
  305. package/src/@claude-flow/memory/dist/persistent-sona.d.ts +0 -144
  306. package/src/@claude-flow/memory/dist/query-builder.d.ts +0 -211
  307. package/src/@claude-flow/memory/dist/rvf-backend.d.ts +0 -51
  308. package/src/@claude-flow/memory/dist/rvf-learning-store.d.ts +0 -139
  309. package/src/@claude-flow/memory/dist/rvf-migration.d.ts +0 -45
  310. package/src/@claude-flow/memory/dist/sqlite-backend.d.ts +0 -121
  311. package/src/@claude-flow/memory/dist/sqljs-backend.d.ts +0 -127
  312. package/src/@claude-flow/memory/dist/types.d.ts +0 -484
  313. package/src/@claude-flow/shared/dist/core/config/defaults.d.ts +0 -41
  314. package/src/@claude-flow/shared/dist/core/config/index.d.ts +0 -8
  315. package/src/@claude-flow/shared/dist/core/config/loader.d.ts +0 -45
  316. package/src/@claude-flow/shared/dist/core/config/schema.d.ts +0 -1134
  317. package/src/@claude-flow/shared/dist/core/config/validator.d.ts +0 -92
  318. package/src/@claude-flow/shared/dist/core/event-bus.d.ts +0 -31
  319. package/src/@claude-flow/shared/dist/core/index.d.ts +0 -15
  320. package/src/@claude-flow/shared/dist/core/interfaces/agent.interface.d.ts +0 -200
  321. package/src/@claude-flow/shared/dist/core/interfaces/coordinator.interface.d.ts +0 -310
  322. package/src/@claude-flow/shared/dist/core/interfaces/event.interface.d.ts +0 -224
  323. package/src/@claude-flow/shared/dist/core/interfaces/index.d.ts +0 -10
  324. package/src/@claude-flow/shared/dist/core/interfaces/memory.interface.d.ts +0 -298
  325. package/src/@claude-flow/shared/dist/core/interfaces/task.interface.d.ts +0 -185
  326. package/src/@claude-flow/shared/dist/core/orchestrator/event-coordinator.d.ts +0 -35
  327. package/src/@claude-flow/shared/dist/core/orchestrator/health-monitor.d.ts +0 -60
  328. package/src/@claude-flow/shared/dist/core/orchestrator/index.d.ts +0 -46
  329. package/src/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.d.ts +0 -56
  330. package/src/@claude-flow/shared/dist/core/orchestrator/session-manager.d.ts +0 -83
  331. package/src/@claude-flow/shared/dist/core/orchestrator/task-manager.d.ts +0 -49
  332. package/src/@claude-flow/shared/dist/events/domain-events.d.ts +0 -282
  333. package/src/@claude-flow/shared/dist/events/event-store.d.ts +0 -126
  334. package/src/@claude-flow/shared/dist/events/event-store.test.d.ts +0 -8
  335. package/src/@claude-flow/shared/dist/events/example-usage.d.ts +0 -10
  336. package/src/@claude-flow/shared/dist/events/index.d.ts +0 -21
  337. package/src/@claude-flow/shared/dist/events/projections.d.ts +0 -177
  338. package/src/@claude-flow/shared/dist/events/rvf-event-log.d.ts +0 -82
  339. package/src/@claude-flow/shared/dist/events/state-reconstructor.d.ts +0 -101
  340. package/src/@claude-flow/shared/dist/events.d.ts +0 -80
  341. package/src/@claude-flow/shared/dist/hooks/example-usage.d.ts +0 -42
  342. package/src/@claude-flow/shared/dist/hooks/executor.d.ts +0 -100
  343. package/src/@claude-flow/shared/dist/hooks/hooks.test.d.ts +0 -9
  344. package/src/@claude-flow/shared/dist/hooks/index.d.ts +0 -52
  345. package/src/@claude-flow/shared/dist/hooks/registry.d.ts +0 -133
  346. package/src/@claude-flow/shared/dist/hooks/safety/bash-safety.d.ts +0 -105
  347. package/src/@claude-flow/shared/dist/hooks/safety/file-organization.d.ts +0 -144
  348. package/src/@claude-flow/shared/dist/hooks/safety/git-commit.d.ts +0 -158
  349. package/src/@claude-flow/shared/dist/hooks/safety/index.d.ts +0 -17
  350. package/src/@claude-flow/shared/dist/hooks/session-hooks.d.ts +0 -234
  351. package/src/@claude-flow/shared/dist/hooks/task-hooks.d.ts +0 -163
  352. package/src/@claude-flow/shared/dist/hooks/types.d.ts +0 -267
  353. package/src/@claude-flow/shared/dist/hooks/verify-exports.test.d.ts +0 -9
  354. package/src/@claude-flow/shared/dist/index.d.ts +0 -20
  355. package/src/@claude-flow/shared/dist/mcp/connection-pool.d.ts +0 -98
  356. package/src/@claude-flow/shared/dist/mcp/index.d.ts +0 -69
  357. package/src/@claude-flow/shared/dist/mcp/server.d.ts +0 -166
  358. package/src/@claude-flow/shared/dist/mcp/session-manager.d.ts +0 -136
  359. package/src/@claude-flow/shared/dist/mcp/tool-registry.d.ts +0 -178
  360. package/src/@claude-flow/shared/dist/mcp/transport/http.d.ts +0 -104
  361. package/src/@claude-flow/shared/dist/mcp/transport/index.d.ts +0 -102
  362. package/src/@claude-flow/shared/dist/mcp/transport/stdio.d.ts +0 -104
  363. package/src/@claude-flow/shared/dist/mcp/transport/websocket.d.ts +0 -133
  364. package/src/@claude-flow/shared/dist/mcp/types.d.ts +0 -438
  365. package/src/@claude-flow/shared/dist/plugin-interface.d.ts +0 -544
  366. package/src/@claude-flow/shared/dist/plugin-loader.d.ts +0 -139
  367. package/src/@claude-flow/shared/dist/plugin-registry.d.ts +0 -183
  368. package/src/@claude-flow/shared/dist/plugins/index.d.ts +0 -10
  369. package/src/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.d.ts +0 -106
  370. package/src/@claude-flow/shared/dist/plugins/official/index.d.ts +0 -10
  371. package/src/@claude-flow/shared/dist/plugins/official/maestro-plugin.d.ts +0 -121
  372. package/src/@claude-flow/shared/dist/plugins/types.d.ts +0 -93
  373. package/src/@claude-flow/shared/dist/resilience/bulkhead.d.ts +0 -105
  374. package/src/@claude-flow/shared/dist/resilience/circuit-breaker.d.ts +0 -132
  375. package/src/@claude-flow/shared/dist/resilience/index.d.ts +0 -19
  376. package/src/@claude-flow/shared/dist/resilience/rate-limiter.d.ts +0 -168
  377. package/src/@claude-flow/shared/dist/resilience/retry.d.ts +0 -91
  378. package/src/@claude-flow/shared/dist/security/index.d.ts +0 -10
  379. package/src/@claude-flow/shared/dist/security/input-validation.d.ts +0 -73
  380. package/src/@claude-flow/shared/dist/security/secure-random.d.ts +0 -92
  381. package/src/@claude-flow/shared/dist/services/index.d.ts +0 -7
  382. package/src/@claude-flow/shared/dist/services/v3-progress.service.d.ts +0 -124
  383. package/src/@claude-flow/shared/dist/types/agent.types.d.ts +0 -137
  384. package/src/@claude-flow/shared/dist/types/index.d.ts +0 -11
  385. package/src/@claude-flow/shared/dist/types/mcp.types.d.ts +0 -266
  386. package/src/@claude-flow/shared/dist/types/memory.types.d.ts +0 -236
  387. package/src/@claude-flow/shared/dist/types/swarm.types.d.ts +0 -186
  388. package/src/@claude-flow/shared/dist/types/task.types.d.ts +0 -178
  389. package/src/@claude-flow/shared/dist/types.d.ts +0 -197
  390. package/src/@claude-flow/shared/dist/utils/secure-logger.d.ts +0 -69
@@ -1,1245 +1,1108 @@
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 intelligence layer: SONA, EWC++, LoRA, Flash Attention, ReasoningBank
684
- // Exercises each component with a lightweight functional test rather than just checking "loaded".
685
- async function checkIntelligence() {
686
- try {
687
- // @ts-ignore — neural is not in tsconfig project references but is available at runtime
688
- const neural = await import('../../neural/src/index.js');
689
- const results = [];
690
- const failures = [];
691
- // 1. SONA — create manager, run trajectory lifecycle
692
- try {
693
- const sona = neural.createSONAManager('balanced');
694
- await sona.initialize();
695
- const tid = sona.beginTrajectory('doctor-check', 'general');
696
- const embedding = new Float32Array(64).fill(0.1);
697
- sona.recordStep(tid, 'test-action', 0.8, embedding);
698
- const traj = sona.completeTrajectory(tid, 0.9);
699
- if (traj && traj.steps.length > 0) {
700
- results.push('SONA');
701
- }
702
- else {
703
- failures.push('SONA (no trajectory output)');
704
- }
705
- await sona.cleanup();
706
- }
707
- catch (e) {
708
- failures.push(`SONA (${e instanceof Error ? e.message : 'error'})`);
709
- }
710
- // 2. ReasoningBank — store + retrieve
711
- try {
712
- const rb = neural.createReasoningBank();
713
- const embedding = new Float32Array(64).fill(0.2);
714
- rb.storeTrajectory({
715
- id: 'doctor-test',
716
- context: 'health check',
717
- domain: 'general',
718
- mode: 'balanced',
719
- steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
720
- startTime: Date.now(),
721
- endTime: Date.now(),
722
- quality: 1,
723
- });
724
- const retrieved = rb.retrieve(embedding, 1);
725
- if (retrieved.length > 0) {
726
- results.push('ReasoningBank');
727
- }
728
- else {
729
- failures.push('ReasoningBank (retrieve failed)');
730
- }
731
- }
732
- catch (e) {
733
- failures.push(`ReasoningBank (${e instanceof Error ? e.message : 'error'})`);
734
- }
735
- // 3. PatternLearner extract + match
736
- try {
737
- const pl = neural.createPatternLearner();
738
- const embedding = new Float32Array(64).fill(0.3);
739
- pl.extractPattern({
740
- id: 'doctor-pl', context: 'test', domain: 'general', mode: 'balanced',
741
- steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
742
- startTime: Date.now(), endTime: Date.now(), quality: 1,
743
- }, { trajectoryId: 'doctor-pl', keyInsights: ['test'], compressedEmbedding: embedding, timestamp: Date.now() });
744
- const matches = pl.findMatches(embedding, 1);
745
- if (matches.length > 0) {
746
- results.push('PatternLearner');
747
- }
748
- else {
749
- failures.push('PatternLearner (no matches)');
750
- }
751
- }
752
- catch (e) {
753
- failures.push(`PatternLearner (${e instanceof Error ? e.message : 'error'})`);
754
- }
755
- // 4. SONALearningEngine (MicroLoRA + EWC++)
756
- try {
757
- const engine = neural.createSONALearningEngine();
758
- const ctx = { task: 'doctor', complexity: 0.5, domain: 'general', agentCount: 1, recentPerformance: 0.8 };
759
- const adapted = engine.adapt(ctx);
760
- const stats = engine.getStats();
761
- const components = [];
762
- if (adapted && adapted.learningRate !== undefined)
763
- components.push('LoRA');
764
- if (stats.ewcConsolidations !== undefined)
765
- components.push('EWC++');
766
- if (components.length > 0) {
767
- results.push(...components);
768
- }
769
- else {
770
- failures.push('LoRA/EWC++ (adapt returned no data)');
771
- }
772
- }
773
- catch (e) {
774
- failures.push(`LoRA/EWC++ (${e instanceof Error ? e.message : 'error'})`);
775
- }
776
- // 5. RL Algorithms quick instantiation check
777
- try {
778
- const algNames = [];
779
- const ppo = neural.createPPO();
780
- if (ppo)
781
- algNames.push('PPO');
782
- const dqn = neural.createDQN();
783
- if (dqn)
784
- algNames.push('DQN');
785
- const ql = neural.createQLearning();
786
- if (ql)
787
- algNames.push('Q-Learn');
788
- if (algNames.length > 0) {
789
- results.push(`RL(${algNames.join('+')})`);
790
- }
791
- }
792
- catch (e) {
793
- failures.push(`RL (${e instanceof Error ? e.message : 'error'})`);
794
- }
795
- if (failures.length > 0) {
796
- return {
797
- name: 'Intelligence',
798
- status: results.length > 0 ? 'warn' : 'fail',
799
- message: `${results.join(', ')} OK; FAILED: ${failures.join(', ')}`,
800
- fix: 'Check neural module imports and dependencies',
801
- };
802
- }
803
- return {
804
- name: 'Intelligence',
805
- status: 'pass',
806
- message: results.join(', '),
807
- };
808
- }
809
- catch (e) {
810
- return {
811
- name: 'Intelligence',
812
- status: 'warn',
813
- message: `Module unavailable: ${e instanceof Error ? e.message.split('\n')[0] : 'import failed'}`,
814
- fix: 'Ensure @claude-flow/neural is built (npm run build)',
815
- };
816
- }
817
- }
818
- // Check whether a given PID is still running.
819
- // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
820
- // needing PowerShell or /proc — Node handles the platform abstraction.
821
- function isProcessAlive(pid) {
822
- try {
823
- process.kill(pid, 0);
824
- return true;
825
- }
826
- catch {
827
- return false;
828
- }
829
- }
830
- // Fast path: kill processes tracked in the shared ProcessManager registry.
831
- // This avoids the expensive OS-level process scan for known background tasks.
832
- function killTrackedProcesses() {
833
- const registryFile = join(process.cwd(), '.claude-flow', 'background-pids.json');
834
- const lockFile = join(process.cwd(), '.claude-flow', 'spawn.lock');
835
- let killed = 0;
836
- try {
837
- if (existsSync(registryFile)) {
838
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
839
- for (const entry of entries) {
840
- if (!isProcessAlive(entry.pid))
841
- continue;
842
- try {
843
- if (process.platform === 'win32') {
844
- execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
845
- }
846
- else {
847
- process.kill(entry.pid, 'SIGKILL');
848
- }
849
- killed++;
850
- }
851
- catch { /* already gone */ }
852
- }
853
- // Clear registry
854
- writeFileSync(registryFile, '[]');
855
- }
856
- }
857
- catch { /* non-fatal */ }
858
- // Remove spawn lock
859
- try {
860
- if (existsSync(lockFile))
861
- unlinkSync(lockFile);
862
- }
863
- catch { /* ok */ }
864
- return killed;
865
- }
866
- // Find and optionally kill orphaned moflo/claude-flow node processes.
867
- // A process is only "orphaned" if its parent is no longer alive — meaning
868
- // nothing will clean it up. MCP servers spawned by a live Claude Code session
869
- // have a live parent (claude.exe) and must not be flagged.
870
- async function findZombieProcesses(kill = false) {
871
- const legitimatePid = getDaemonLockHolder(process.cwd());
872
- const currentPid = process.pid;
873
- const parentPid = process.ppid;
874
- const found = [];
875
- let killed = 0;
876
- // Collect candidates as { pid, ppid } so we can check parent liveness
877
- const candidates = [];
878
- try {
879
- if (process.platform === 'win32') {
880
- // Windows: include ParentProcessId so we can verify orphan status
881
- 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 });
882
- const lines = result.split('\n');
883
- for (const line of lines) {
884
- if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
885
- // Format-Table columns: ProcessId ParentProcessId CommandLine...
886
- const match = line.match(/^\s*(\d+)\s+(\d+)/);
887
- if (match) {
888
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
889
- }
890
- }
891
- }
892
- }
893
- else {
894
- // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
895
- const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
896
- const lines = result.trim().split('\n');
897
- for (const line of lines) {
898
- const match = line.trim().match(/^(\d+)\s+(\d+)/);
899
- if (match) {
900
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
901
- }
902
- }
903
- }
904
- }
905
- catch {
906
- // No matches found (grep exits non-zero) or command failed
907
- }
908
- // Filter: skip known-good PIDs and processes whose parent is still alive.
909
- // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
910
- for (const { pid, ppid } of candidates) {
911
- if (pid === currentPid || pid === parentPid || pid === legitimatePid)
912
- continue;
913
- if (isProcessAlive(ppid))
914
- continue;
915
- // Defense-in-depth: detached daemons have dead parents by design.
916
- // Even if the lock file is missing/corrupted, don't kill a running daemon.
917
- if (isDaemonProcess(pid))
918
- continue;
919
- found.push(pid);
920
- }
921
- if (kill && found.length > 0) {
922
- for (const pid of found) {
923
- try {
924
- if (process.platform === 'win32') {
925
- execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
926
- }
927
- else {
928
- process.kill(pid, 'SIGKILL');
929
- }
930
- killed++;
931
- }
932
- catch {
933
- // Process may have already exited
934
- }
935
- }
936
- // Clean up stale daemon lock if we killed the holder
937
- if (legitimatePid && found.includes(legitimatePid)) {
938
- releaseDaemonLock(process.cwd(), legitimatePid, true);
939
- }
940
- }
941
- return { found: found.length, killed, pids: found };
942
- }
943
- // Format health check result
944
- function formatCheck(check) {
945
- const icon = check.status === 'pass' ? output.success('✓') :
946
- check.status === 'warn' ? output.warning('⚠') :
947
- output.error('');
948
- return `${icon} ${check.name}: ${check.message}`;
949
- }
950
- // Main doctor command
951
- export const doctorCommand = {
952
- name: 'doctor',
953
- description: 'System diagnostics and health checks',
954
- options: [
955
- {
956
- name: 'fix',
957
- short: 'f',
958
- description: 'Automatically fix issues where possible',
959
- type: 'boolean',
960
- default: false
961
- },
962
- {
963
- name: 'install',
964
- short: 'i',
965
- description: 'Auto-install missing dependencies (Claude Code CLI)',
966
- type: 'boolean',
967
- default: false
968
- },
969
- {
970
- name: 'component',
971
- short: 'c',
972
- description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript)',
973
- type: 'string'
974
- },
975
- {
976
- name: 'verbose',
977
- short: 'v',
978
- description: 'Verbose output',
979
- type: 'boolean',
980
- default: false
981
- },
982
- {
983
- name: 'kill-zombies',
984
- short: 'k',
985
- description: 'Find and kill orphaned moflo/claude-flow node processes',
986
- type: 'boolean',
987
- default: false
988
- }
989
- ],
990
- examples: [
991
- { command: 'claude-flow doctor', description: 'Run full health check' },
992
- { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' },
993
- { command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },
994
- { command: 'claude-flow doctor --kill-zombies', description: 'Find and kill zombie processes' },
995
- { command: 'claude-flow doctor -c version', description: 'Check for stale npx cache' },
996
- { command: 'claude-flow doctor -c claude', description: 'Check Claude Code CLI only' }
997
- ],
998
- action: async (ctx) => {
999
- const showFix = ctx.flags.fix;
1000
- const autoInstall = ctx.flags.install;
1001
- const component = ctx.flags.component;
1002
- const verbose = ctx.flags.verbose;
1003
- const killZombies = ctx.flags['kill-zombies'];
1004
- output.writeln();
1005
- output.writeln(output.bold('MoFlo Doctor'));
1006
- output.writeln(output.dim('System diagnostics and health check'));
1007
- output.writeln(output.dim(''.repeat(50)));
1008
- output.writeln();
1009
- // Handle --kill-zombies early
1010
- if (killZombies) {
1011
- output.writeln(output.bold('Zombie Process Scan'));
1012
- output.writeln();
1013
- // Fast path: kill tracked processes from the shared registry first
1014
- const registryKilled = killTrackedProcesses();
1015
- if (registryKilled > 0) {
1016
- output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
1017
- }
1018
- // Slow path: OS-level scan for any remaining orphans
1019
- const scan = await findZombieProcesses(false);
1020
- if (scan.found === 0) {
1021
- if (registryKilled === 0) {
1022
- output.writeln(output.success(' No orphaned moflo processes found'));
1023
- }
1024
- }
1025
- else {
1026
- output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
1027
- // Kill them
1028
- const result = await findZombieProcesses(true);
1029
- if (result.killed > 0) {
1030
- output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
1031
- }
1032
- if (result.killed < result.found) {
1033
- output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
1034
- }
1035
- }
1036
- output.writeln();
1037
- output.writeln(output.dim('─'.repeat(50)));
1038
- output.writeln();
1039
- }
1040
- const checkZombieProcesses = async () => {
1041
- try {
1042
- const scan = await findZombieProcesses(false);
1043
- if (scan.found === 0) {
1044
- return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
1045
- }
1046
- return {
1047
- name: 'Zombie Processes',
1048
- status: 'warn',
1049
- message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
1050
- fix: 'moflo doctor --kill-zombies'
1051
- };
1052
- }
1053
- catch {
1054
- return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
1055
- }
1056
- };
1057
- const allChecks = [
1058
- checkVersionFreshness,
1059
- checkNodeVersion,
1060
- checkNpmVersion,
1061
- checkClaudeCode,
1062
- checkGit,
1063
- checkGitRepo,
1064
- checkConfigFile,
1065
- checkDaemonStatus,
1066
- checkMemoryDatabase,
1067
- checkEmbeddings,
1068
- checkTestDirs,
1069
- checkMcpServers,
1070
- checkDiskSpace,
1071
- checkBuildTools,
1072
- checkAgenticFlow,
1073
- checkIntelligence,
1074
- checkZombieProcesses
1075
- ];
1076
- const componentMap = {
1077
- 'version': checkVersionFreshness,
1078
- 'freshness': checkVersionFreshness,
1079
- 'node': checkNodeVersion,
1080
- 'npm': checkNpmVersion,
1081
- 'claude': checkClaudeCode,
1082
- 'config': checkConfigFile,
1083
- 'daemon': checkDaemonStatus,
1084
- 'memory': checkMemoryDatabase,
1085
- 'embeddings': checkEmbeddings,
1086
- 'git': checkGit,
1087
- 'mcp': checkMcpServers,
1088
- 'disk': checkDiskSpace,
1089
- 'typescript': checkBuildTools,
1090
- 'tests': checkTestDirs,
1091
- 'agentic-flow': checkAgenticFlow,
1092
- 'intelligence': checkIntelligence
1093
- };
1094
- let checksToRun = allChecks;
1095
- if (component && componentMap[component]) {
1096
- checksToRun = [componentMap[component]];
1097
- }
1098
- const results = [];
1099
- const fixes = [];
1100
- // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
1101
- const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });
1102
- spinner.start();
1103
- try {
1104
- // Execute all checks concurrently
1105
- const checkResults = await Promise.allSettled(checksToRun.map(check => check()));
1106
- spinner.stop();
1107
- // Process results in order
1108
- for (const settledResult of checkResults) {
1109
- if (settledResult.status === 'fulfilled') {
1110
- const result = settledResult.value;
1111
- results.push(result);
1112
- output.writeln(formatCheck(result));
1113
- if (result.fix && (result.status === 'fail' || result.status === 'warn')) {
1114
- fixes.push(`${result.name}: ${result.fix}`);
1115
- }
1116
- }
1117
- else {
1118
- const errorResult = {
1119
- name: 'Check',
1120
- status: 'fail',
1121
- message: settledResult.reason?.message || 'Unknown error'
1122
- };
1123
- results.push(errorResult);
1124
- output.writeln(formatCheck(errorResult));
1125
- }
1126
- }
1127
- }
1128
- catch (error) {
1129
- spinner.stop();
1130
- output.writeln(output.error('Failed to run health checks'));
1131
- }
1132
- // Auto-install missing dependencies if requested
1133
- if (autoInstall) {
1134
- const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
1135
- if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
1136
- const installed = await installClaudeCode();
1137
- if (installed) {
1138
- // Re-check Claude Code after installation
1139
- const newCheck = await checkClaudeCode();
1140
- const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1141
- if (idx !== -1) {
1142
- results[idx] = newCheck;
1143
- // Update fixes list
1144
- const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1145
- if (fixIdx !== -1 && newCheck.status === 'pass') {
1146
- fixes.splice(fixIdx, 1);
1147
- }
1148
- }
1149
- output.writeln(formatCheck(newCheck));
1150
- }
1151
- }
1152
- }
1153
- // Summary
1154
- const passed = results.filter(r => r.status === 'pass').length;
1155
- const warnings = results.filter(r => r.status === 'warn').length;
1156
- const failed = results.filter(r => r.status === 'fail').length;
1157
- output.writeln();
1158
- output.writeln(output.dim('─'.repeat(50)));
1159
- output.writeln();
1160
- const summaryParts = [
1161
- output.success(`${passed} passed`),
1162
- warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1163
- failed > 0 ? output.error(`${failed} failed`) : null
1164
- ].filter(Boolean);
1165
- output.writeln(`Summary: ${summaryParts.join(', ')}`);
1166
- // Auto-fix or show fixes
1167
- if (showFix && fixes.length > 0) {
1168
- output.writeln();
1169
- output.writeln(output.bold('Auto-fixing issues...'));
1170
- output.writeln();
1171
- const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1172
- let fixed = 0;
1173
- const unfixed = [];
1174
- for (const check of fixableResults) {
1175
- const success = await autoFixCheck(check);
1176
- if (success) {
1177
- fixed++;
1178
- }
1179
- else {
1180
- unfixed.push(`${check.name}: ${check.fix}`);
1181
- }
1182
- }
1183
- if (fixed > 0) {
1184
- output.writeln();
1185
- output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1186
- }
1187
- if (unfixed.length > 0) {
1188
- output.writeln();
1189
- output.writeln(output.bold('Manual fixes needed:'));
1190
- for (const fix of unfixed) {
1191
- output.writeln(output.dim(` ${fix}`));
1192
- }
1193
- }
1194
- // Re-run checks to show updated status
1195
- if (fixed > 0) {
1196
- output.writeln();
1197
- output.writeln(output.dim('Re-checking...'));
1198
- output.writeln();
1199
- const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1200
- let rePassed = 0, reWarnings = 0, reFailed = 0;
1201
- for (const sr of reResults) {
1202
- if (sr.status === 'fulfilled') {
1203
- output.writeln(formatCheck(sr.value));
1204
- if (sr.value.status === 'pass')
1205
- rePassed++;
1206
- else if (sr.value.status === 'warn')
1207
- reWarnings++;
1208
- else
1209
- reFailed++;
1210
- }
1211
- }
1212
- output.writeln();
1213
- output.writeln(output.dim('─'.repeat(50)));
1214
- const reSummary = [
1215
- output.success(`${rePassed} passed`),
1216
- reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1217
- reFailed > 0 ? output.error(`${reFailed} failed`) : null
1218
- ].filter(Boolean);
1219
- output.writeln(`After fix: ${reSummary.join(', ')}`);
1220
- }
1221
- }
1222
- else if (fixes.length > 0 && !showFix) {
1223
- output.writeln();
1224
- output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1225
- }
1226
- // Overall result
1227
- if (failed > 0) {
1228
- output.writeln();
1229
- output.writeln(output.error('Some checks failed. Please address the issues above.'));
1230
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1231
- }
1232
- else if (warnings > 0) {
1233
- output.writeln();
1234
- output.writeln(output.warning('All checks passed with some warnings.'));
1235
- return { success: true, data: { passed, warnings, failed, results } };
1236
- }
1237
- else {
1238
- output.writeln();
1239
- output.writeln(output.success('All checks passed! System is healthy.'));
1240
- return { success: true, data: { passed, warnings, failed, results } };
1241
- }
1242
- }
1243
- };
1244
- 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 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;
1245
1108
  //# sourceMappingURL=doctor.js.map