@claude-flow/cli 3.32.2 → 3.32.3

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 (655) hide show
  1. package/.claude/helpers/helpers.manifest.json +3 -3
  2. package/.claude/helpers/statusline.cjs +38 -38
  3. package/catalog-manifest.json +2 -2
  4. package/package.json +2 -2
  5. package/plugins/ruflo-metaharness/scripts/smoke.sh +11 -11
  6. package/dist/src/agenticow/speculative-exploration.d.ts +0 -148
  7. package/dist/src/agenticow/speculative-exploration.js +0 -218
  8. package/dist/src/appliance/gguf-engine.d.ts +0 -91
  9. package/dist/src/appliance/gguf-engine.js +0 -425
  10. package/dist/src/appliance/ruvllm-bridge.d.ts +0 -102
  11. package/dist/src/appliance/ruvllm-bridge.js +0 -292
  12. package/dist/src/appliance/rvfa-builder.d.ts +0 -44
  13. package/dist/src/appliance/rvfa-builder.js +0 -329
  14. package/dist/src/appliance/rvfa-distribution.d.ts +0 -97
  15. package/dist/src/appliance/rvfa-distribution.js +0 -370
  16. package/dist/src/appliance/rvfa-format.d.ts +0 -111
  17. package/dist/src/appliance/rvfa-format.js +0 -393
  18. package/dist/src/appliance/rvfa-runner.d.ts +0 -69
  19. package/dist/src/appliance/rvfa-runner.js +0 -237
  20. package/dist/src/appliance/rvfa-signing.d.ts +0 -123
  21. package/dist/src/appliance/rvfa-signing.js +0 -347
  22. package/dist/src/autopilot-state.d.ts +0 -77
  23. package/dist/src/autopilot-state.js +0 -271
  24. package/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +0 -18
  25. package/dist/src/benchmarks/gaia-agent-planning.smoke.js +0 -253
  26. package/dist/src/benchmarks/gaia-agent.d.ts +0 -198
  27. package/dist/src/benchmarks/gaia-agent.js +0 -651
  28. package/dist/src/benchmarks/gaia-causal-memory.d.ts +0 -133
  29. package/dist/src/benchmarks/gaia-causal-memory.js +0 -281
  30. package/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +0 -22
  31. package/dist/src/benchmarks/gaia-causal-memory.smoke.js +0 -300
  32. package/dist/src/benchmarks/gaia-convergence.d.ts +0 -138
  33. package/dist/src/benchmarks/gaia-convergence.js +0 -260
  34. package/dist/src/benchmarks/gaia-convergence.smoke.d.ts +0 -19
  35. package/dist/src/benchmarks/gaia-convergence.smoke.js +0 -246
  36. package/dist/src/benchmarks/gaia-critic.d.ts +0 -123
  37. package/dist/src/benchmarks/gaia-critic.js +0 -312
  38. package/dist/src/benchmarks/gaia-critic.smoke.d.ts +0 -21
  39. package/dist/src/benchmarks/gaia-critic.smoke.js +0 -327
  40. package/dist/src/benchmarks/gaia-decomposer.d.ts +0 -125
  41. package/dist/src/benchmarks/gaia-decomposer.js +0 -350
  42. package/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +0 -21
  43. package/dist/src/benchmarks/gaia-decomposer.smoke.js +0 -228
  44. package/dist/src/benchmarks/gaia-e2e-smoke.d.ts +0 -27
  45. package/dist/src/benchmarks/gaia-e2e-smoke.js +0 -136
  46. package/dist/src/benchmarks/gaia-extract.smoke.d.ts +0 -45
  47. package/dist/src/benchmarks/gaia-extract.smoke.js +0 -242
  48. package/dist/src/benchmarks/gaia-hardness/features.d.ts +0 -46
  49. package/dist/src/benchmarks/gaia-hardness/features.js +0 -170
  50. package/dist/src/benchmarks/gaia-hardness/predictor.d.ts +0 -105
  51. package/dist/src/benchmarks/gaia-hardness/predictor.js +0 -260
  52. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +0 -20
  53. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +0 -235
  54. package/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +0 -51
  55. package/dist/src/benchmarks/gaia-hardness/train-data-loader.js +0 -179
  56. package/dist/src/benchmarks/gaia-judge.d.ts +0 -88
  57. package/dist/src/benchmarks/gaia-judge.js +0 -437
  58. package/dist/src/benchmarks/gaia-loader.d.ts +0 -87
  59. package/dist/src/benchmarks/gaia-loader.js +0 -326
  60. package/dist/src/benchmarks/gaia-tools/file_read.d.ts +0 -35
  61. package/dist/src/benchmarks/gaia-tools/file_read.js +0 -403
  62. package/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +0 -126
  63. package/dist/src/benchmarks/gaia-tools/grounded_query.js +0 -225
  64. package/dist/src/benchmarks/gaia-tools/index.d.ts +0 -32
  65. package/dist/src/benchmarks/gaia-tools/index.js +0 -36
  66. package/dist/src/benchmarks/gaia-tools/types.d.ts +0 -62
  67. package/dist/src/benchmarks/gaia-tools/types.js +0 -12
  68. package/dist/src/benchmarks/gaia-tools/web_search.d.ts +0 -30
  69. package/dist/src/benchmarks/gaia-tools/web_search.js +0 -210
  70. package/dist/src/benchmarks/gaia-voting.d.ts +0 -88
  71. package/dist/src/benchmarks/gaia-voting.js +0 -297
  72. package/dist/src/benchmarks/gaia-voting.smoke.d.ts +0 -20
  73. package/dist/src/benchmarks/gaia-voting.smoke.js +0 -332
  74. package/dist/src/benchmarks/pretrain/index.d.ts +0 -58
  75. package/dist/src/benchmarks/pretrain/index.js +0 -404
  76. package/dist/src/business-pods/bbs-budget-tracker.d.ts +0 -139
  77. package/dist/src/business-pods/bbs-budget-tracker.js +0 -358
  78. package/dist/src/business-pods/domain-affinity-policy.d.ts +0 -47
  79. package/dist/src/business-pods/domain-affinity-policy.js +0 -65
  80. package/dist/src/business-pods/pod-schema.d.ts +0 -96
  81. package/dist/src/business-pods/pod-schema.js +0 -225
  82. package/dist/src/commands/advisor.d.ts +0 -15
  83. package/dist/src/commands/advisor.js +0 -94
  84. package/dist/src/commands/agent-wasm.d.ts +0 -14
  85. package/dist/src/commands/agent-wasm.js +0 -333
  86. package/dist/src/commands/agent.d.ts +0 -8
  87. package/dist/src/commands/agent.js +0 -927
  88. package/dist/src/commands/analyze.d.ts +0 -19
  89. package/dist/src/commands/analyze.js +0 -2047
  90. package/dist/src/commands/announcements.d.ts +0 -17
  91. package/dist/src/commands/announcements.js +0 -0
  92. package/dist/src/commands/appliance-advanced.d.ts +0 -9
  93. package/dist/src/commands/appliance-advanced.js +0 -215
  94. package/dist/src/commands/appliance.d.ts +0 -8
  95. package/dist/src/commands/appliance.js +0 -404
  96. package/dist/src/commands/autopilot.d.ts +0 -15
  97. package/dist/src/commands/autopilot.js +0 -407
  98. package/dist/src/commands/benchmark.d.ts +0 -10
  99. package/dist/src/commands/benchmark.js +0 -460
  100. package/dist/src/commands/claims.d.ts +0 -10
  101. package/dist/src/commands/claims.js +0 -620
  102. package/dist/src/commands/cleanup.d.ts +0 -13
  103. package/dist/src/commands/cleanup.js +0 -250
  104. package/dist/src/commands/completions.d.ts +0 -10
  105. package/dist/src/commands/completions.js +0 -539
  106. package/dist/src/commands/config.d.ts +0 -8
  107. package/dist/src/commands/config.js +0 -428
  108. package/dist/src/commands/daemon.d.ts +0 -59
  109. package/dist/src/commands/daemon.js +0 -1733
  110. package/dist/src/commands/deployment.d.ts +0 -10
  111. package/dist/src/commands/deployment.js +0 -672
  112. package/dist/src/commands/doctor.d.ts +0 -10
  113. package/dist/src/commands/doctor.js +0 -1695
  114. package/dist/src/commands/eject.d.ts +0 -33
  115. package/dist/src/commands/eject.js +0 -195
  116. package/dist/src/commands/embeddings.d.ts +0 -18
  117. package/dist/src/commands/embeddings.js +0 -1623
  118. package/dist/src/commands/funnel.d.ts +0 -18
  119. package/dist/src/commands/funnel.js +0 -302
  120. package/dist/src/commands/gaia-bench.d.ts +0 -40
  121. package/dist/src/commands/gaia-bench.js +0 -597
  122. package/dist/src/commands/guidance.d.ts +0 -8
  123. package/dist/src/commands/guidance.js +0 -556
  124. package/dist/src/commands/hive-mind.d.ts +0 -11
  125. package/dist/src/commands/hive-mind.js +0 -1319
  126. package/dist/src/commands/hooks.d.ts +0 -8
  127. package/dist/src/commands/hooks.js +0 -4606
  128. package/dist/src/commands/index.d.ts +0 -118
  129. package/dist/src/commands/index.js +0 -364
  130. package/dist/src/commands/init.d.ts +0 -13
  131. package/dist/src/commands/init.js +0 -1297
  132. package/dist/src/commands/issues.d.ts +0 -21
  133. package/dist/src/commands/issues.js +0 -567
  134. package/dist/src/commands/mcp.d.ts +0 -11
  135. package/dist/src/commands/mcp.js +0 -732
  136. package/dist/src/commands/memory-backup.d.ts +0 -11
  137. package/dist/src/commands/memory-backup.js +0 -46
  138. package/dist/src/commands/memory-distill.d.ts +0 -27
  139. package/dist/src/commands/memory-distill.js +0 -374
  140. package/dist/src/commands/memory.d.ts +0 -8
  141. package/dist/src/commands/memory.js +0 -1596
  142. package/dist/src/commands/metaharness.d.ts +0 -39
  143. package/dist/src/commands/metaharness.js +0 -215
  144. package/dist/src/commands/migrate.d.ts +0 -8
  145. package/dist/src/commands/migrate.js +0 -742
  146. package/dist/src/commands/neural.d.ts +0 -10
  147. package/dist/src/commands/neural.js +0 -4331
  148. package/dist/src/commands/performance.d.ts +0 -10
  149. package/dist/src/commands/performance.js +0 -583
  150. package/dist/src/commands/plugins.d.ts +0 -11
  151. package/dist/src/commands/plugins.js +0 -826
  152. package/dist/src/commands/process.d.ts +0 -10
  153. package/dist/src/commands/process.js +0 -694
  154. package/dist/src/commands/progress.d.ts +0 -11
  155. package/dist/src/commands/progress.js +0 -259
  156. package/dist/src/commands/providers.d.ts +0 -10
  157. package/dist/src/commands/providers.js +0 -502
  158. package/dist/src/commands/proxy.d.ts +0 -21
  159. package/dist/src/commands/proxy.js +0 -310
  160. package/dist/src/commands/route.d.ts +0 -16
  161. package/dist/src/commands/route.js +0 -822
  162. package/dist/src/commands/ruvector/backup.d.ts +0 -11
  163. package/dist/src/commands/ruvector/backup.js +0 -747
  164. package/dist/src/commands/ruvector/benchmark.d.ts +0 -11
  165. package/dist/src/commands/ruvector/benchmark.js +0 -490
  166. package/dist/src/commands/ruvector/import.d.ts +0 -18
  167. package/dist/src/commands/ruvector/import.js +0 -373
  168. package/dist/src/commands/ruvector/index.d.ts +0 -29
  169. package/dist/src/commands/ruvector/index.js +0 -129
  170. package/dist/src/commands/ruvector/init.d.ts +0 -11
  171. package/dist/src/commands/ruvector/init.js +0 -467
  172. package/dist/src/commands/ruvector/migrate.d.ts +0 -11
  173. package/dist/src/commands/ruvector/migrate.js +0 -498
  174. package/dist/src/commands/ruvector/optimize.d.ts +0 -11
  175. package/dist/src/commands/ruvector/optimize.js +0 -505
  176. package/dist/src/commands/ruvector/pg-utils.d.ts +0 -14
  177. package/dist/src/commands/ruvector/pg-utils.js +0 -41
  178. package/dist/src/commands/ruvector/setup.d.ts +0 -18
  179. package/dist/src/commands/ruvector/setup.js +0 -765
  180. package/dist/src/commands/ruvector/status.d.ts +0 -11
  181. package/dist/src/commands/ruvector/status.js +0 -479
  182. package/dist/src/commands/security.d.ts +0 -10
  183. package/dist/src/commands/security.js +0 -1012
  184. package/dist/src/commands/session.d.ts +0 -8
  185. package/dist/src/commands/session.js +0 -757
  186. package/dist/src/commands/settings.d.ts +0 -19
  187. package/dist/src/commands/settings.js +0 -180
  188. package/dist/src/commands/spinner.d.ts +0 -16
  189. package/dist/src/commands/spinner.js +0 -329
  190. package/dist/src/commands/start.d.ts +0 -8
  191. package/dist/src/commands/start.js +0 -418
  192. package/dist/src/commands/status.d.ts +0 -8
  193. package/dist/src/commands/status.js +0 -608
  194. package/dist/src/commands/swarm.d.ts +0 -8
  195. package/dist/src/commands/swarm.js +0 -891
  196. package/dist/src/commands/task.d.ts +0 -8
  197. package/dist/src/commands/task.js +0 -675
  198. package/dist/src/commands/transfer-store.d.ts +0 -13
  199. package/dist/src/commands/transfer-store.js +0 -428
  200. package/dist/src/commands/update.d.ts +0 -8
  201. package/dist/src/commands/update.js +0 -276
  202. package/dist/src/commands/verify.d.ts +0 -19
  203. package/dist/src/commands/verify.js +0 -261
  204. package/dist/src/commands/version.d.ts +0 -42
  205. package/dist/src/commands/version.js +0 -106
  206. package/dist/src/commands/workflow.d.ts +0 -8
  207. package/dist/src/commands/workflow.js +0 -617
  208. package/dist/src/config/harness-feedback-applier.d.ts +0 -50
  209. package/dist/src/config/harness-feedback-applier.js +0 -122
  210. package/dist/src/config/proven-config-refresh.d.ts +0 -39
  211. package/dist/src/config/proven-config-refresh.js +0 -154
  212. package/dist/src/config/proven-config-rvfa.d.ts +0 -23
  213. package/dist/src/config/proven-config-rvfa.js +0 -73
  214. package/dist/src/config/proven-config.d.ts +0 -86
  215. package/dist/src/config/proven-config.js +0 -176
  216. package/dist/src/config-adapter.d.ts +0 -15
  217. package/dist/src/config-adapter.js +0 -186
  218. package/dist/src/encryption/vault.d.ts +0 -94
  219. package/dist/src/encryption/vault.js +0 -172
  220. package/dist/src/fs-secure.d.ts +0 -86
  221. package/dist/src/fs-secure.js +0 -133
  222. package/dist/src/funnel/advisor-tip.d.ts +0 -58
  223. package/dist/src/funnel/advisor-tip.js +0 -92
  224. package/dist/src/funnel/attribution.d.ts +0 -37
  225. package/dist/src/funnel/attribution.js +0 -101
  226. package/dist/src/funnel/consent.d.ts +0 -22
  227. package/dist/src/funnel/consent.js +0 -58
  228. package/dist/src/funnel/credit-errors.d.ts +0 -31
  229. package/dist/src/funnel/credit-errors.js +0 -88
  230. package/dist/src/funnel/credit-notifier.d.ts +0 -44
  231. package/dist/src/funnel/credit-notifier.js +0 -74
  232. package/dist/src/funnel/disclosure.d.ts +0 -47
  233. package/dist/src/funnel/disclosure.js +0 -109
  234. package/dist/src/funnel/enrollment.d.ts +0 -36
  235. package/dist/src/funnel/enrollment.js +0 -64
  236. package/dist/src/funnel/environment.d.ts +0 -17
  237. package/dist/src/funnel/environment.js +0 -39
  238. package/dist/src/funnel/event-transport.d.ts +0 -51
  239. package/dist/src/funnel/event-transport.js +0 -199
  240. package/dist/src/funnel/events.d.ts +0 -42
  241. package/dist/src/funnel/events.js +0 -150
  242. package/dist/src/funnel/index.d.ts +0 -21
  243. package/dist/src/funnel/index.js +0 -21
  244. package/dist/src/funnel/insights.d.ts +0 -50
  245. package/dist/src/funnel/insights.js +0 -120
  246. package/dist/src/funnel/local-signals.d.ts +0 -20
  247. package/dist/src/funnel/local-signals.js +0 -77
  248. package/dist/src/funnel/message-transport.d.ts +0 -51
  249. package/dist/src/funnel/message-transport.js +0 -149
  250. package/dist/src/funnel/messages.d.ts +0 -55
  251. package/dist/src/funnel/messages.js +0 -160
  252. package/dist/src/funnel/payout.d.ts +0 -40
  253. package/dist/src/funnel/payout.js +0 -60
  254. package/dist/src/funnel/power-saver-notifier.d.ts +0 -44
  255. package/dist/src/funnel/power-saver-notifier.js +0 -92
  256. package/dist/src/funnel/precedence.d.ts +0 -16
  257. package/dist/src/funnel/precedence.js +0 -85
  258. package/dist/src/funnel/promo.d.ts +0 -41
  259. package/dist/src/funnel/promo.js +0 -144
  260. package/dist/src/funnel/rate-limit-notifier.d.ts +0 -55
  261. package/dist/src/funnel/rate-limit-notifier.js +0 -102
  262. package/dist/src/funnel/rotation.d.ts +0 -19
  263. package/dist/src/funnel/rotation.js +0 -70
  264. package/dist/src/funnel/state.d.ts +0 -13
  265. package/dist/src/funnel/state.js +0 -52
  266. package/dist/src/funnel/toggle-cooldown.d.ts +0 -17
  267. package/dist/src/funnel/toggle-cooldown.js +0 -32
  268. package/dist/src/funnel/types.d.ts +0 -98
  269. package/dist/src/funnel/types.js +0 -26
  270. package/dist/src/index.d.ts +0 -81
  271. package/dist/src/index.js +0 -609
  272. package/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  273. package/dist/src/infrastructure/in-memory-repositories.js +0 -264
  274. package/dist/src/init/claudemd-generator.d.ts +0 -16
  275. package/dist/src/init/claudemd-generator.js +0 -368
  276. package/dist/src/init/executor.d.ts +0 -41
  277. package/dist/src/init/executor.js +0 -2142
  278. package/dist/src/init/helper-refresh.d.ts +0 -79
  279. package/dist/src/init/helper-refresh.js +0 -347
  280. package/dist/src/init/helper-signing.d.ts +0 -37
  281. package/dist/src/init/helper-signing.js +0 -67
  282. package/dist/src/init/helpers-generator.d.ts +0 -87
  283. package/dist/src/init/helpers-generator.js +0 -1456
  284. package/dist/src/init/index.d.ts +0 -13
  285. package/dist/src/init/index.js +0 -15
  286. package/dist/src/init/mcp-generator.d.ts +0 -26
  287. package/dist/src/init/mcp-generator.js +0 -126
  288. package/dist/src/init/memory-package-resolver.d.ts +0 -53
  289. package/dist/src/init/memory-package-resolver.js +0 -118
  290. package/dist/src/init/settings-generator.d.ts +0 -14
  291. package/dist/src/init/settings-generator.js +0 -462
  292. package/dist/src/init/statusline-generator.d.ts +0 -28
  293. package/dist/src/init/statusline-generator.js +0 -177
  294. package/dist/src/init/types.d.ts +0 -331
  295. package/dist/src/init/types.js +0 -276
  296. package/dist/src/log-filters.d.ts +0 -46
  297. package/dist/src/log-filters.js +0 -107
  298. package/dist/src/mcp-client.d.ts +0 -92
  299. package/dist/src/mcp-client.js +0 -397
  300. package/dist/src/mcp-server.d.ts +0 -163
  301. package/dist/src/mcp-server.js +0 -751
  302. package/dist/src/mcp-tools/agent-execute-core.d.ts +0 -115
  303. package/dist/src/mcp-tools/agent-execute-core.js +0 -587
  304. package/dist/src/mcp-tools/agent-tools.d.ts +0 -9
  305. package/dist/src/mcp-tools/agent-tools.js +0 -837
  306. package/dist/src/mcp-tools/agentbbs-tools.d.ts +0 -28
  307. package/dist/src/mcp-tools/agentbbs-tools.js +0 -394
  308. package/dist/src/mcp-tools/agentdb-tools.d.ts +0 -35
  309. package/dist/src/mcp-tools/agentdb-tools.js +0 -1473
  310. package/dist/src/mcp-tools/agenticow-loader.d.ts +0 -59
  311. package/dist/src/mcp-tools/agenticow-loader.js +0 -105
  312. package/dist/src/mcp-tools/agenticow-speculate-tools.d.ts +0 -24
  313. package/dist/src/mcp-tools/agenticow-speculate-tools.js +0 -209
  314. package/dist/src/mcp-tools/agenticow-tools.d.ts +0 -36
  315. package/dist/src/mcp-tools/agenticow-tools.js +0 -360
  316. package/dist/src/mcp-tools/analyze-tools.d.ts +0 -38
  317. package/dist/src/mcp-tools/analyze-tools.js +0 -346
  318. package/dist/src/mcp-tools/auto-install.d.ts +0 -83
  319. package/dist/src/mcp-tools/auto-install.js +0 -131
  320. package/dist/src/mcp-tools/autopilot-tools.d.ts +0 -12
  321. package/dist/src/mcp-tools/autopilot-tools.js +0 -231
  322. package/dist/src/mcp-tools/browser-intent-tools.d.ts +0 -162
  323. package/dist/src/mcp-tools/browser-intent-tools.js +0 -548
  324. package/dist/src/mcp-tools/browser-session-tools.d.ts +0 -27
  325. package/dist/src/mcp-tools/browser-session-tools.js +0 -398
  326. package/dist/src/mcp-tools/browser-tools.d.ts +0 -21
  327. package/dist/src/mcp-tools/browser-tools.js +0 -760
  328. package/dist/src/mcp-tools/business-pod-tools.d.ts +0 -20
  329. package/dist/src/mcp-tools/business-pod-tools.js +0 -169
  330. package/dist/src/mcp-tools/claims-tools.d.ts +0 -12
  331. package/dist/src/mcp-tools/claims-tools.js +0 -863
  332. package/dist/src/mcp-tools/config-tools.d.ts +0 -8
  333. package/dist/src/mcp-tools/config-tools.js +0 -411
  334. package/dist/src/mcp-tools/coordination-tools.d.ts +0 -13
  335. package/dist/src/mcp-tools/coordination-tools.js +0 -729
  336. package/dist/src/mcp-tools/daa-tools.d.ts +0 -13
  337. package/dist/src/mcp-tools/daa-tools.js +0 -534
  338. package/dist/src/mcp-tools/embeddings-tools.d.ts +0 -9
  339. package/dist/src/mcp-tools/embeddings-tools.js +0 -904
  340. package/dist/src/mcp-tools/github-tools.d.ts +0 -9
  341. package/dist/src/mcp-tools/github-tools.js +0 -659
  342. package/dist/src/mcp-tools/guidance-tools.d.ts +0 -15
  343. package/dist/src/mcp-tools/guidance-tools.js +0 -639
  344. package/dist/src/mcp-tools/hive-mind-tools.d.ts +0 -8
  345. package/dist/src/mcp-tools/hive-mind-tools.js +0 -953
  346. package/dist/src/mcp-tools/hooks-tools.d.ts +0 -65
  347. package/dist/src/mcp-tools/hooks-tools.js +0 -4836
  348. package/dist/src/mcp-tools/http-fetch-tools.d.ts +0 -55
  349. package/dist/src/mcp-tools/http-fetch-tools.js +0 -329
  350. package/dist/src/mcp-tools/index.d.ts +0 -34
  351. package/dist/src/mcp-tools/index.js +0 -40
  352. package/dist/src/mcp-tools/managed-agent-tools.d.ts +0 -22
  353. package/dist/src/mcp-tools/managed-agent-tools.js +0 -357
  354. package/dist/src/mcp-tools/memory-tools.d.ts +0 -14
  355. package/dist/src/mcp-tools/memory-tools.js +0 -1330
  356. package/dist/src/mcp-tools/metaharness-tools.d.ts +0 -51
  357. package/dist/src/mcp-tools/metaharness-tools.js +0 -684
  358. package/dist/src/mcp-tools/neural-tools.d.ts +0 -54
  359. package/dist/src/mcp-tools/neural-tools.js +0 -1168
  360. package/dist/src/mcp-tools/performance-tools.d.ts +0 -16
  361. package/dist/src/mcp-tools/performance-tools.js +0 -675
  362. package/dist/src/mcp-tools/progress-tools.d.ts +0 -14
  363. package/dist/src/mcp-tools/progress-tools.js +0 -348
  364. package/dist/src/mcp-tools/request-tracker.d.ts +0 -17
  365. package/dist/src/mcp-tools/request-tracker.js +0 -27
  366. package/dist/src/mcp-tools/ruvllm-tools.d.ts +0 -9
  367. package/dist/src/mcp-tools/ruvllm-tools.js +0 -355
  368. package/dist/src/mcp-tools/security-tools.d.ts +0 -18
  369. package/dist/src/mcp-tools/security-tools.js +0 -556
  370. package/dist/src/mcp-tools/session-tools.d.ts +0 -8
  371. package/dist/src/mcp-tools/session-tools.js +0 -517
  372. package/dist/src/mcp-tools/swarm-tools.d.ts +0 -37
  373. package/dist/src/mcp-tools/swarm-tools.js +0 -390
  374. package/dist/src/mcp-tools/system-tools.d.ts +0 -13
  375. package/dist/src/mcp-tools/system-tools.js +0 -688
  376. package/dist/src/mcp-tools/task-tools.d.ts +0 -8
  377. package/dist/src/mcp-tools/task-tools.js +0 -487
  378. package/dist/src/mcp-tools/terminal-tools.d.ts +0 -8
  379. package/dist/src/mcp-tools/terminal-tools.js +0 -306
  380. package/dist/src/mcp-tools/testgen-tools.d.ts +0 -26
  381. package/dist/src/mcp-tools/testgen-tools.js +0 -168
  382. package/dist/src/mcp-tools/tool-loop-guardrail.d.ts +0 -31
  383. package/dist/src/mcp-tools/tool-loop-guardrail.js +0 -71
  384. package/dist/src/mcp-tools/transfer-tools.d.ts +0 -14
  385. package/dist/src/mcp-tools/transfer-tools.js +0 -447
  386. package/dist/src/mcp-tools/types.d.ts +0 -8
  387. package/dist/src/mcp-tools/types.js +0 -8
  388. package/dist/src/mcp-tools/validate-input.d.ts +0 -9
  389. package/dist/src/mcp-tools/validate-input.js +0 -9
  390. package/dist/src/mcp-tools/wasm-agent-tools.d.ts +0 -13
  391. package/dist/src/mcp-tools/wasm-agent-tools.js +0 -840
  392. package/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  393. package/dist/src/mcp-tools/workflow-tools.js +0 -884
  394. package/dist/src/memory/bge-embedder.d.ts +0 -25
  395. package/dist/src/memory/bge-embedder.js +0 -121
  396. package/dist/src/memory/cross-encoder-rerank.d.ts +0 -33
  397. package/dist/src/memory/cross-encoder-rerank.js +0 -123
  398. package/dist/src/memory/embedding-policy.d.ts +0 -21
  399. package/dist/src/memory/embedding-policy.js +0 -30
  400. package/dist/src/memory/embedding-quantization.d.ts +0 -62
  401. package/dist/src/memory/embedding-quantization.js +0 -156
  402. package/dist/src/memory/ewc-consolidation.d.ts +0 -305
  403. package/dist/src/memory/ewc-consolidation.js +0 -611
  404. package/dist/src/memory/graph-edge-writer.d.ts +0 -95
  405. package/dist/src/memory/graph-edge-writer.js +0 -217
  406. package/dist/src/memory/hybrid-retrieval.d.ts +0 -77
  407. package/dist/src/memory/hybrid-retrieval.js +0 -192
  408. package/dist/src/memory/intelligence.d.ts +0 -405
  409. package/dist/src/memory/intelligence.js +0 -1316
  410. package/dist/src/memory/lucene-bm25.d.ts +0 -19
  411. package/dist/src/memory/lucene-bm25.js +0 -308
  412. package/dist/src/memory/memory-bridge.d.ts +0 -537
  413. package/dist/src/memory/memory-bridge.js +0 -2460
  414. package/dist/src/memory/memory-initializer.d.ts +0 -556
  415. package/dist/src/memory/memory-initializer.js +0 -3021
  416. package/dist/src/memory/neural-package-bridge.d.ts +0 -48
  417. package/dist/src/memory/neural-package-bridge.js +0 -87
  418. package/dist/src/memory/rabitq-index.d.ts +0 -60
  419. package/dist/src/memory/rabitq-index.js +0 -242
  420. package/dist/src/memory/sona-optimizer.d.ts +0 -267
  421. package/dist/src/memory/sona-optimizer.js +0 -779
  422. package/dist/src/memory/structured-distill.d.ts +0 -48
  423. package/dist/src/memory/structured-distill.js +0 -125
  424. package/dist/src/output.d.ts +0 -9
  425. package/dist/src/output.js +0 -9
  426. package/dist/src/parser.d.ts +0 -89
  427. package/dist/src/parser.js +0 -516
  428. package/dist/src/plugins/manager.d.ts +0 -133
  429. package/dist/src/plugins/manager.js +0 -415
  430. package/dist/src/plugins/store/discovery.d.ts +0 -99
  431. package/dist/src/plugins/store/discovery.js +0 -1224
  432. package/dist/src/plugins/store/index.d.ts +0 -76
  433. package/dist/src/plugins/store/index.js +0 -141
  434. package/dist/src/plugins/store/search.d.ts +0 -46
  435. package/dist/src/plugins/store/search.js +0 -230
  436. package/dist/src/plugins/store/types.d.ts +0 -279
  437. package/dist/src/plugins/store/types.js +0 -7
  438. package/dist/src/plugins/tests/demo-plugin-store.d.ts +0 -7
  439. package/dist/src/plugins/tests/demo-plugin-store.js +0 -126
  440. package/dist/src/plugins/tests/standalone-test.d.ts +0 -12
  441. package/dist/src/plugins/tests/standalone-test.js +0 -188
  442. package/dist/src/plugins/tests/test-plugin-store.d.ts +0 -7
  443. package/dist/src/plugins/tests/test-plugin-store.js +0 -206
  444. package/dist/src/production/circuit-breaker.d.ts +0 -101
  445. package/dist/src/production/circuit-breaker.js +0 -241
  446. package/dist/src/production/error-handler.d.ts +0 -92
  447. package/dist/src/production/error-handler.js +0 -299
  448. package/dist/src/production/index.d.ts +0 -23
  449. package/dist/src/production/index.js +0 -18
  450. package/dist/src/production/monitoring.d.ts +0 -161
  451. package/dist/src/production/monitoring.js +0 -356
  452. package/dist/src/production/rate-limiter.d.ts +0 -80
  453. package/dist/src/production/rate-limiter.js +0 -201
  454. package/dist/src/production/retry.d.ts +0 -48
  455. package/dist/src/production/retry.js +0 -179
  456. package/dist/src/prompt.d.ts +0 -44
  457. package/dist/src/prompt.js +0 -501
  458. package/dist/src/runtime/headless.d.ts +0 -60
  459. package/dist/src/runtime/headless.js +0 -284
  460. package/dist/src/runtime/parent-death-watchdog.d.ts +0 -42
  461. package/dist/src/runtime/parent-death-watchdog.js +0 -70
  462. package/dist/src/ruvector/agent-wasm.d.ts +0 -228
  463. package/dist/src/ruvector/agent-wasm.js +0 -463
  464. package/dist/src/ruvector/ast-analyzer.d.ts +0 -67
  465. package/dist/src/ruvector/ast-analyzer.js +0 -277
  466. package/dist/src/ruvector/codemods/engine.d.ts +0 -45
  467. package/dist/src/ruvector/codemods/engine.js +0 -291
  468. package/dist/src/ruvector/codemods/scope-analysis.d.ts +0 -29
  469. package/dist/src/ruvector/codemods/scope-analysis.js +0 -162
  470. package/dist/src/ruvector/coverage-router.d.ts +0 -160
  471. package/dist/src/ruvector/coverage-router.js +0 -531
  472. package/dist/src/ruvector/coverage-tools.d.ts +0 -33
  473. package/dist/src/ruvector/coverage-tools.js +0 -157
  474. package/dist/src/ruvector/diff-classifier.d.ts +0 -175
  475. package/dist/src/ruvector/diff-classifier.js +0 -699
  476. package/dist/src/ruvector/diskann-backend.d.ts +0 -78
  477. package/dist/src/ruvector/diskann-backend.js +0 -310
  478. package/dist/src/ruvector/enhanced-model-router.d.ts +0 -172
  479. package/dist/src/ruvector/enhanced-model-router.js +0 -577
  480. package/dist/src/ruvector/graph-analyzer.d.ts +0 -187
  481. package/dist/src/ruvector/graph-analyzer.js +0 -929
  482. package/dist/src/ruvector/graph-backend.d.ts +0 -79
  483. package/dist/src/ruvector/graph-backend.js +0 -220
  484. package/dist/src/ruvector/index.d.ts +0 -38
  485. package/dist/src/ruvector/index.js +0 -86
  486. package/dist/src/ruvector/lora-adapter.d.ts +0 -292
  487. package/dist/src/ruvector/lora-adapter.js +0 -710
  488. package/dist/src/ruvector/model-prices.d.ts +0 -50
  489. package/dist/src/ruvector/model-prices.js +0 -72
  490. package/dist/src/ruvector/model-router.d.ts +0 -408
  491. package/dist/src/ruvector/model-router.js +0 -1162
  492. package/dist/src/ruvector/neural-router.d.ts +0 -182
  493. package/dist/src/ruvector/neural-router.js +0 -825
  494. package/dist/src/ruvector/output-verifier.d.ts +0 -83
  495. package/dist/src/ruvector/output-verifier.js +0 -277
  496. package/dist/src/ruvector/q-learning-router.d.ts +0 -227
  497. package/dist/src/ruvector/q-learning-router.js +0 -721
  498. package/dist/src/ruvector/router-calibrator.d.ts +0 -65
  499. package/dist/src/ruvector/router-calibrator.js +0 -120
  500. package/dist/src/ruvector/router-parallel-recorder.d.ts +0 -127
  501. package/dist/src/ruvector/router-parallel-recorder.js +0 -183
  502. package/dist/src/ruvector/router-trajectory.d.ts +0 -194
  503. package/dist/src/ruvector/router-trajectory.js +0 -281
  504. package/dist/src/ruvector/run-transcript-recorder.d.ts +0 -154
  505. package/dist/src/ruvector/run-transcript-recorder.js +0 -209
  506. package/dist/src/ruvector/ruvllm-wasm.d.ts +0 -179
  507. package/dist/src/ruvector/ruvllm-wasm.js +0 -379
  508. package/dist/src/ruvector/semantic-router.d.ts +0 -77
  509. package/dist/src/ruvector/semantic-router.js +0 -178
  510. package/dist/src/ruvector/task-embedder.d.ts +0 -56
  511. package/dist/src/ruvector/task-embedder.js +0 -237
  512. package/dist/src/ruvector/trajectory-tree.d.ts +0 -113
  513. package/dist/src/ruvector/trajectory-tree.js +0 -237
  514. package/dist/src/ruvector/vector-db.d.ts +0 -73
  515. package/dist/src/ruvector/vector-db.js +0 -301
  516. package/dist/src/ruvector/wasm-embedder.d.ts +0 -13
  517. package/dist/src/ruvector/wasm-embedder.js +0 -143
  518. package/dist/src/security/builtin-aidefence.d.ts +0 -34
  519. package/dist/src/security/builtin-aidefence.js +0 -86
  520. package/dist/src/services/agentic-flow-bridge.d.ts +0 -50
  521. package/dist/src/services/agentic-flow-bridge.js +0 -95
  522. package/dist/src/services/ai-job-dedup.d.ts +0 -61
  523. package/dist/src/services/ai-job-dedup.js +0 -136
  524. package/dist/src/services/checkpoint-gate.d.ts +0 -140
  525. package/dist/src/services/checkpoint-gate.js +0 -223
  526. package/dist/src/services/claim-service.d.ts +0 -204
  527. package/dist/src/services/claim-service.js +0 -818
  528. package/dist/src/services/config-file-manager.d.ts +0 -37
  529. package/dist/src/services/config-file-manager.js +0 -224
  530. package/dist/src/services/container-worker-pool.d.ts +0 -204
  531. package/dist/src/services/container-worker-pool.js +0 -589
  532. package/dist/src/services/daemon-autostart.d.ts +0 -17
  533. package/dist/src/services/daemon-autostart.js +0 -102
  534. package/dist/src/services/distill-oracle.d.ts +0 -190
  535. package/dist/src/services/distill-oracle.js +0 -349
  536. package/dist/src/services/distill-tuning.d.ts +0 -111
  537. package/dist/src/services/distill-tuning.js +0 -510
  538. package/dist/src/services/evolve-proof.d.ts +0 -253
  539. package/dist/src/services/evolve-proof.js +0 -343
  540. package/dist/src/services/fable-harness.d.ts +0 -208
  541. package/dist/src/services/fable-harness.js +0 -388
  542. package/dist/src/services/git-workspace-identity.d.ts +0 -42
  543. package/dist/src/services/git-workspace-identity.js +0 -99
  544. package/dist/src/services/global-ai-budget.d.ts +0 -135
  545. package/dist/src/services/global-ai-budget.js +0 -415
  546. package/dist/src/services/harness-benchmark.d.ts +0 -68
  547. package/dist/src/services/harness-benchmark.js +0 -94
  548. package/dist/src/services/harness-canary.d.ts +0 -60
  549. package/dist/src/services/harness-canary.js +0 -69
  550. package/dist/src/services/harness-corpus-harvester.d.ts +0 -51
  551. package/dist/src/services/harness-corpus-harvester.js +0 -74
  552. package/dist/src/services/harness-flywheel-generations.d.ts +0 -115
  553. package/dist/src/services/harness-flywheel-generations.js +0 -360
  554. package/dist/src/services/harness-flywheel-runtime.d.ts +0 -25
  555. package/dist/src/services/harness-flywheel-runtime.js +0 -92
  556. package/dist/src/services/harness-flywheel.d.ts +0 -48
  557. package/dist/src/services/harness-flywheel.js +0 -207
  558. package/dist/src/services/harness-frozen-eval.d.ts +0 -22
  559. package/dist/src/services/harness-frozen-eval.js +0 -66
  560. package/dist/src/services/harness-hosts.d.ts +0 -40
  561. package/dist/src/services/harness-hosts.js +0 -88
  562. package/dist/src/services/harness-improvement-ledger.d.ts +0 -63
  563. package/dist/src/services/harness-improvement-ledger.js +0 -101
  564. package/dist/src/services/harness-loop.d.ts +0 -53
  565. package/dist/src/services/harness-loop.js +0 -85
  566. package/dist/src/services/harness-qualification.d.ts +0 -66
  567. package/dist/src/services/harness-qualification.js +0 -143
  568. package/dist/src/services/harness-replay.d.ts +0 -37
  569. package/dist/src/services/harness-replay.js +0 -92
  570. package/dist/src/services/harness-verify.d.ts +0 -33
  571. package/dist/src/services/harness-verify.js +0 -26
  572. package/dist/src/services/harness-worker.d.ts +0 -23
  573. package/dist/src/services/harness-worker.js +0 -66
  574. package/dist/src/services/headless-worker-executor.d.ts +0 -358
  575. package/dist/src/services/headless-worker-executor.js +0 -1269
  576. package/dist/src/services/index.d.ts +0 -13
  577. package/dist/src/services/index.js +0 -11
  578. package/dist/src/services/memory-backup.d.ts +0 -53
  579. package/dist/src/services/memory-backup.js +0 -198
  580. package/dist/src/services/memory-distillation.d.ts +0 -41
  581. package/dist/src/services/memory-distillation.js +0 -277
  582. package/dist/src/services/native-training.d.ts +0 -68
  583. package/dist/src/services/native-training.js +0 -141
  584. package/dist/src/services/registry-api.d.ts +0 -58
  585. package/dist/src/services/registry-api.js +0 -146
  586. package/dist/src/services/repo-supervisor.d.ts +0 -70
  587. package/dist/src/services/repo-supervisor.js +0 -228
  588. package/dist/src/services/ruvector-training.d.ts +0 -222
  589. package/dist/src/services/ruvector-training.js +0 -693
  590. package/dist/src/services/swarm-memory-branches.d.ts +0 -135
  591. package/dist/src/services/swarm-memory-branches.js +0 -213
  592. package/dist/src/services/weight-eft.d.ts +0 -305
  593. package/dist/src/services/weight-eft.js +0 -296
  594. package/dist/src/services/worker-daemon.d.ts +0 -439
  595. package/dist/src/services/worker-daemon.js +0 -1865
  596. package/dist/src/services/worker-queue.d.ts +0 -194
  597. package/dist/src/services/worker-queue.js +0 -513
  598. package/dist/src/services/workspace-lease.d.ts +0 -55
  599. package/dist/src/services/workspace-lease.js +0 -191
  600. package/dist/src/suggest.d.ts +0 -53
  601. package/dist/src/suggest.js +0 -200
  602. package/dist/src/transfer/anonymization/index.d.ts +0 -25
  603. package/dist/src/transfer/anonymization/index.js +0 -175
  604. package/dist/src/transfer/deploy-seraphine.d.ts +0 -13
  605. package/dist/src/transfer/deploy-seraphine.js +0 -205
  606. package/dist/src/transfer/export.d.ts +0 -25
  607. package/dist/src/transfer/export.js +0 -113
  608. package/dist/src/transfer/index.d.ts +0 -12
  609. package/dist/src/transfer/index.js +0 -31
  610. package/dist/src/transfer/ipfs/client.d.ts +0 -109
  611. package/dist/src/transfer/ipfs/client.js +0 -307
  612. package/dist/src/transfer/ipfs/upload.d.ts +0 -95
  613. package/dist/src/transfer/ipfs/upload.js +0 -413
  614. package/dist/src/transfer/models/seraphine.d.ts +0 -72
  615. package/dist/src/transfer/models/seraphine.js +0 -373
  616. package/dist/src/transfer/serialization/cfp.d.ts +0 -49
  617. package/dist/src/transfer/serialization/cfp.js +0 -183
  618. package/dist/src/transfer/storage/gcs.d.ts +0 -82
  619. package/dist/src/transfer/storage/gcs.js +0 -272
  620. package/dist/src/transfer/storage/index.d.ts +0 -6
  621. package/dist/src/transfer/storage/index.js +0 -6
  622. package/dist/src/transfer/store/discovery.d.ts +0 -84
  623. package/dist/src/transfer/store/discovery.js +0 -382
  624. package/dist/src/transfer/store/download.d.ts +0 -70
  625. package/dist/src/transfer/store/download.js +0 -334
  626. package/dist/src/transfer/store/index.d.ts +0 -84
  627. package/dist/src/transfer/store/index.js +0 -153
  628. package/dist/src/transfer/store/publish.d.ts +0 -76
  629. package/dist/src/transfer/store/publish.js +0 -294
  630. package/dist/src/transfer/store/registry.d.ts +0 -58
  631. package/dist/src/transfer/store/registry.js +0 -285
  632. package/dist/src/transfer/store/search.d.ts +0 -54
  633. package/dist/src/transfer/store/search.js +0 -232
  634. package/dist/src/transfer/store/tests/standalone-test.d.ts +0 -12
  635. package/dist/src/transfer/store/tests/standalone-test.js +0 -190
  636. package/dist/src/transfer/store/types.d.ts +0 -193
  637. package/dist/src/transfer/store/types.js +0 -6
  638. package/dist/src/transfer/test-seraphine.d.ts +0 -6
  639. package/dist/src/transfer/test-seraphine.js +0 -105
  640. package/dist/src/transfer/tests/test-store.d.ts +0 -7
  641. package/dist/src/transfer/tests/test-store.js +0 -214
  642. package/dist/src/transfer/types.d.ts +0 -245
  643. package/dist/src/transfer/types.js +0 -6
  644. package/dist/src/types.d.ts +0 -13
  645. package/dist/src/types.js +0 -13
  646. package/dist/src/update/checker.d.ts +0 -34
  647. package/dist/src/update/checker.js +0 -191
  648. package/dist/src/update/executor.d.ts +0 -33
  649. package/dist/src/update/executor.js +0 -217
  650. package/dist/src/update/index.d.ts +0 -33
  651. package/dist/src/update/index.js +0 -64
  652. package/dist/src/update/rate-limiter.d.ts +0 -20
  653. package/dist/src/update/rate-limiter.js +0 -96
  654. package/dist/src/update/validator.d.ts +0 -17
  655. package/dist/src/update/validator.js +0 -123
@@ -1,2047 +0,0 @@
1
- /**
2
- * V3 CLI Analyze Command
3
- * Code analysis, diff classification, AST analysis, and change risk assessment
4
- *
5
- * Features:
6
- * - AST analysis using ruvector (tree-sitter) with graceful fallback
7
- * - Symbol extraction (functions, classes, variables, types)
8
- * - Cyclomatic complexity scoring
9
- * - Diff classification and risk assessment
10
- * - Graph boundaries using MinCut algorithm
11
- * - Module communities using Louvain algorithm
12
- * - Circular dependency detection
13
- *
14
- * Created with ruv.io
15
- */
16
- import { output } from '../output.js';
17
- import { callMCPTool, MCPClientError } from '../mcp-client.js';
18
- import * as path from 'path';
19
- import * as fs from 'fs/promises';
20
- import { writeFile } from 'fs/promises';
21
- import { resolve } from 'path';
22
- import { execSync } from 'child_process';
23
- // Dynamic import for AST analyzer
24
- async function getASTAnalyzer() {
25
- try {
26
- return await import('../ruvector/ast-analyzer.js');
27
- }
28
- catch {
29
- return null;
30
- }
31
- }
32
- // Dynamic import for graph analyzer
33
- async function getGraphAnalyzer() {
34
- try {
35
- return await import('../ruvector/graph-analyzer.js');
36
- }
37
- catch {
38
- return null;
39
- }
40
- }
41
- // Diff subcommand
42
- const diffCommand = {
43
- name: 'diff',
44
- description: 'Analyze git diff for change risk assessment and classification',
45
- options: [
46
- {
47
- name: 'risk',
48
- short: 'r',
49
- description: 'Show risk assessment',
50
- type: 'boolean',
51
- default: false,
52
- },
53
- {
54
- name: 'classify',
55
- short: 'c',
56
- description: 'Classify change type',
57
- type: 'boolean',
58
- default: false,
59
- },
60
- {
61
- name: 'reviewers',
62
- description: 'Show recommended reviewers',
63
- type: 'boolean',
64
- default: false,
65
- },
66
- {
67
- name: 'format',
68
- short: 'f',
69
- description: 'Output format: text, json, table',
70
- type: 'string',
71
- default: 'text',
72
- choices: ['text', 'json', 'table'],
73
- },
74
- {
75
- name: 'verbose',
76
- short: 'v',
77
- description: 'Show detailed file-level analysis',
78
- type: 'boolean',
79
- default: false,
80
- },
81
- ],
82
- examples: [
83
- { command: 'claude-flow analyze diff --risk', description: 'Analyze current diff with risk assessment' },
84
- { command: 'claude-flow analyze diff HEAD~1 --classify', description: 'Classify changes from last commit' },
85
- { command: 'claude-flow analyze diff main..feature --format json', description: 'Compare branches with JSON output' },
86
- { command: 'claude-flow analyze diff --reviewers', description: 'Get recommended reviewers for changes' },
87
- ],
88
- action: async (ctx) => {
89
- const ref = ctx.args[0] || 'HEAD';
90
- const showRisk = ctx.flags.risk;
91
- const showClassify = ctx.flags.classify;
92
- const showReviewers = ctx.flags.reviewers;
93
- const formatType = ctx.flags.format || 'text';
94
- const verbose = ctx.flags.verbose;
95
- // If no specific flag, show all
96
- const showAll = !showRisk && !showClassify && !showReviewers;
97
- output.printInfo(`Analyzing diff: ${output.highlight(ref)}`);
98
- try {
99
- // Call MCP tool for diff analysis
100
- const result = await callMCPTool('analyze_diff', {
101
- ref,
102
- includeFileRisks: verbose,
103
- includeReviewers: showReviewers || showAll,
104
- });
105
- // JSON output
106
- if (formatType === 'json') {
107
- output.printJson(result);
108
- return { success: true, data: result };
109
- }
110
- output.writeln();
111
- // Summary box
112
- const files = result.files || [];
113
- const risk = result.risk || { overall: 'unknown', score: 0, breakdown: { fileCount: 0, totalChanges: 0, highRiskFiles: [], securityConcerns: [], breakingChanges: [], testCoverage: 'unknown' } };
114
- const classification = result.classification || { category: 'unknown', confidence: 0, reasoning: '' };
115
- output.printBox([
116
- `Ref: ${result.ref || 'HEAD'}`,
117
- `Files: ${files.length}`,
118
- `Risk: ${getRiskDisplay(risk.overall)} (${risk.score}/100)`,
119
- `Type: ${classification.category}${classification.subcategory ? ` (${classification.subcategory})` : ''}`,
120
- ``,
121
- result.summary || 'No summary available',
122
- ].join('\n'), 'Diff Analysis');
123
- // Risk assessment
124
- if (showRisk || showAll) {
125
- output.writeln();
126
- output.writeln(output.bold('Risk Assessment'));
127
- output.writeln(output.dim('-'.repeat(50)));
128
- output.printTable({
129
- columns: [
130
- { key: 'metric', header: 'Metric', width: 25 },
131
- { key: 'value', header: 'Value', width: 30 },
132
- ],
133
- data: [
134
- { metric: 'Overall Risk', value: getRiskDisplay(risk.overall) },
135
- { metric: 'Risk Score', value: `${risk.score}/100` },
136
- { metric: 'Files Changed', value: risk.breakdown.fileCount },
137
- { metric: 'Total Lines Changed', value: risk.breakdown.totalChanges },
138
- { metric: 'Test Coverage', value: risk.breakdown.testCoverage },
139
- ],
140
- });
141
- // Security concerns
142
- if (risk.breakdown.securityConcerns.length > 0) {
143
- output.writeln();
144
- output.writeln(output.bold(output.warning('Security Concerns')));
145
- output.printList(risk.breakdown.securityConcerns.map(c => output.warning(c)));
146
- }
147
- // Breaking changes
148
- if (risk.breakdown.breakingChanges.length > 0) {
149
- output.writeln();
150
- output.writeln(output.bold(output.error('Potential Breaking Changes')));
151
- output.printList(risk.breakdown.breakingChanges.map(c => output.error(c)));
152
- }
153
- // High risk files
154
- if (risk.breakdown.highRiskFiles.length > 0) {
155
- output.writeln();
156
- output.writeln(output.bold('High Risk Files'));
157
- output.printList(risk.breakdown.highRiskFiles.map(f => output.warning(f)));
158
- }
159
- }
160
- // Classification
161
- if (showClassify || showAll) {
162
- output.writeln();
163
- output.writeln(output.bold('Classification'));
164
- output.writeln(output.dim('-'.repeat(50)));
165
- output.printTable({
166
- columns: [
167
- { key: 'field', header: 'Field', width: 15 },
168
- { key: 'value', header: 'Value', width: 40 },
169
- ],
170
- data: [
171
- { field: 'Category', value: classification.category },
172
- { field: 'Subcategory', value: classification.subcategory || '-' },
173
- { field: 'Confidence', value: `${(classification.confidence * 100).toFixed(0)}%` },
174
- ],
175
- });
176
- output.writeln();
177
- output.writeln(output.dim(`Reasoning: ${classification.reasoning}`));
178
- }
179
- // Reviewers
180
- if (showReviewers || showAll) {
181
- output.writeln();
182
- output.writeln(output.bold('Recommended Reviewers'));
183
- output.writeln(output.dim('-'.repeat(50)));
184
- const reviewers = result.recommendedReviewers || [];
185
- if (reviewers.length > 0) {
186
- output.printNumberedList(reviewers.map(r => output.highlight(r)));
187
- }
188
- else {
189
- output.writeln(output.dim('No specific reviewers recommended'));
190
- }
191
- }
192
- // Verbose file-level details
193
- if (verbose && result.fileRisks) {
194
- output.writeln();
195
- output.writeln(output.bold('File-Level Analysis'));
196
- output.writeln(output.dim('-'.repeat(50)));
197
- output.printTable({
198
- columns: [
199
- { key: 'path', header: 'File', width: 40 },
200
- { key: 'risk', header: 'Risk', width: 12, format: (v) => getRiskDisplay(String(v)) },
201
- { key: 'score', header: 'Score', width: 8, align: 'right' },
202
- { key: 'reasons', header: 'Reasons', width: 30, format: (v) => {
203
- const reasons = v;
204
- return reasons.slice(0, 2).join('; ');
205
- } },
206
- ],
207
- data: result.fileRisks,
208
- });
209
- }
210
- // Files changed table
211
- if (formatType === 'table' || showAll) {
212
- output.writeln();
213
- output.writeln(output.bold('Files Changed'));
214
- output.writeln(output.dim('-'.repeat(50)));
215
- output.printTable({
216
- columns: [
217
- { key: 'status', header: 'Status', width: 10, format: (v) => getStatusDisplay(String(v)) },
218
- { key: 'path', header: 'File', width: 45 },
219
- { key: 'additions', header: '+', width: 8, align: 'right', format: (v) => output.success(`+${v}`) },
220
- { key: 'deletions', header: '-', width: 8, align: 'right', format: (v) => output.error(`-${v}`) },
221
- ],
222
- data: files.slice(0, 20),
223
- });
224
- if (files.length > 20) {
225
- output.writeln(output.dim(` ... and ${files.length - 20} more files`));
226
- }
227
- }
228
- return { success: true, data: result };
229
- }
230
- catch (error) {
231
- if (error instanceof MCPClientError) {
232
- output.printError(`Diff analysis failed: ${error.message}`);
233
- }
234
- else {
235
- output.printError(`Unexpected error: ${String(error)}`);
236
- }
237
- return { success: false, exitCode: 1 };
238
- }
239
- },
240
- };
241
- const codeCommand = {
242
- name: 'code',
243
- description: 'Static code analysis and quality assessment',
244
- options: [
245
- { name: 'path', short: 'p', type: 'string', description: 'Path to analyze', default: '.' },
246
- { name: 'type', short: 't', type: 'string', description: 'Analysis type: quality, complexity, security', default: 'quality' },
247
- { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
248
- ],
249
- examples: [
250
- { command: 'claude-flow analyze code -p ./src', description: 'Analyze source directory' },
251
- { command: 'claude-flow analyze code --type complexity', description: 'Run complexity analysis' },
252
- ],
253
- action: async (ctx) => {
254
- const targetPath = resolve(ctx.flags.path || '.');
255
- const analysisType = ctx.flags.type || 'quality';
256
- const formatJson = ctx.flags.format === 'json';
257
- output.writeln();
258
- output.writeln(output.bold('Code Analysis'));
259
- output.writeln(output.dim('-'.repeat(50)));
260
- const spinner = output.createSpinner({ text: `Analyzing ${targetPath}...`, spinner: 'dots' });
261
- spinner.start();
262
- try {
263
- const files = await scanSourceFiles(targetPath);
264
- if (files.length === 0) {
265
- spinner.stop();
266
- output.printWarning('No source files found');
267
- return { success: true };
268
- }
269
- const fileStats = [];
270
- for (const filePath of files) {
271
- const content = await fs.readFile(filePath, 'utf-8');
272
- const lines = content.split('\n');
273
- const nonEmpty = lines.filter(l => l.trim().length > 0 && !/^\s*(\/\/|\/\*|\*\s|#)/.test(l)).length;
274
- const todos = (content.match(/\b(TODO|FIXME|HACK|XXX)\b/gi) || []).length;
275
- const fns = (content.match(/(?:export\s+)?(?:async\s+)?function\s+\w+|(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\([^)]*\)\s*=>/g) || []).length;
276
- const imps = (content.match(/^import\s+/gm) || []).length + (content.match(/require\s*\(/g) || []).length;
277
- let maxNesting = 0;
278
- let nesting = 0;
279
- for (const line of lines) {
280
- nesting += (line.match(/\{/g) || []).length;
281
- nesting -= (line.match(/\}/g) || []).length;
282
- if (nesting > maxNesting)
283
- maxNesting = nesting;
284
- }
285
- const securityIssues = [];
286
- if (/\beval\s*\(/.test(content))
287
- securityIssues.push('eval()');
288
- if (/\bexec\s*\(/.test(content))
289
- securityIssues.push('exec()');
290
- if (/\.innerHTML\s*=/.test(content))
291
- securityIssues.push('innerHTML');
292
- if (/dangerouslySetInnerHTML/.test(content))
293
- securityIssues.push('dangerouslySetInnerHTML');
294
- if (/['"](?:password|secret|api[_-]?key|token)\s*[:=]\s*['"][^'"]{3,}['"]/i.test(content))
295
- securityIssues.push('hardcoded secret');
296
- if (/new\s+Function\s*\(/.test(content))
297
- securityIssues.push('new Function()');
298
- fileStats.push({
299
- file: filePath,
300
- loc: nonEmpty,
301
- todos,
302
- functions: fns,
303
- imports: imps,
304
- maxNesting,
305
- securityIssues,
306
- });
307
- }
308
- spinner.stop();
309
- const totalLoc = fileStats.reduce((s, f) => s + f.loc, 0);
310
- const totalTodos = fileStats.reduce((s, f) => s + f.todos, 0);
311
- const totalFunctions = fileStats.reduce((s, f) => s + f.functions, 0);
312
- const totalImports = fileStats.reduce((s, f) => s + f.imports, 0);
313
- const avgFileSize = Math.round(totalLoc / files.length);
314
- const longestFile = fileStats.reduce((a, b) => a.loc > b.loc ? a : b);
315
- const avgFnPerFile = (totalFunctions / files.length).toFixed(1);
316
- const deepestNesting = fileStats.reduce((a, b) => a.maxNesting > b.maxNesting ? a : b);
317
- const allSecurityIssues = fileStats.filter(f => f.securityIssues.length > 0);
318
- if (formatJson) {
319
- const jsonData = { type: analysisType, path: targetPath, files: files.length, totalLoc, totalTodos, totalFunctions, totalImports, avgFileSize, fileStats: fileStats.map(f => ({ relativePath: path.relative(targetPath, f.file), loc: f.loc, todos: f.todos, functions: f.functions, imports: f.imports, maxNesting: f.maxNesting, securityIssues: f.securityIssues })) };
320
- output.printJson(jsonData);
321
- return { success: true, data: jsonData };
322
- }
323
- if (analysisType === 'quality') {
324
- output.printBox([`Files: ${files.length}`, `Lines of Code: ${totalLoc.toLocaleString()}`, `Avg File Size: ${avgFileSize} LOC`, `TODO/FIXME: ${totalTodos}`, `Functions: ${totalFunctions}`, `Imports: ${totalImports}`].join('\n'), 'Quality Summary');
325
- output.writeln();
326
- output.writeln(output.bold('Largest Files'));
327
- output.writeln(output.dim('-'.repeat(60)));
328
- const top10 = [...fileStats].sort((a, b) => b.loc - a.loc).slice(0, 10);
329
- output.printTable({
330
- columns: [
331
- { key: 'file', header: 'File', width: 45 },
332
- { key: 'loc', header: 'LOC', width: 8, align: 'right' },
333
- { key: 'fns', header: 'Fns', width: 6, align: 'right' },
334
- { key: 'todos', header: 'TODOs', width: 7, align: 'right' },
335
- ],
336
- data: top10.map(f => ({ file: path.relative(targetPath, f.file), loc: f.loc, fns: f.functions, todos: f.todos })),
337
- });
338
- if (totalTodos > 0) {
339
- output.writeln();
340
- output.printWarning(`${totalTodos} TODO/FIXME comments found across ${fileStats.filter(f => f.todos > 0).length} files`);
341
- }
342
- }
343
- else if (analysisType === 'complexity') {
344
- output.printBox([`Files: ${files.length}`, `Total Functions: ${totalFunctions}`, `Avg Functions/File: ${avgFnPerFile}`, `Deepest Nesting: ${deepestNesting.maxNesting} levels (${path.relative(targetPath, deepestNesting.file)})`, `Longest File: ${longestFile.loc} LOC (${path.relative(targetPath, longestFile.file)})`].join('\n'), 'Complexity Summary');
345
- output.writeln();
346
- output.writeln(output.bold('High Complexity Files (nesting > 5)'));
347
- output.writeln(output.dim('-'.repeat(60)));
348
- const complex = fileStats.filter(f => f.maxNesting > 5).sort((a, b) => b.maxNesting - a.maxNesting);
349
- if (complex.length === 0) {
350
- output.printSuccess('No files with excessive nesting detected');
351
- }
352
- else {
353
- output.printTable({
354
- columns: [
355
- { key: 'file', header: 'File', width: 45 },
356
- { key: 'nesting', header: 'Max Nest', width: 10, align: 'right' },
357
- { key: 'fns', header: 'Fns', width: 6, align: 'right' },
358
- { key: 'loc', header: 'LOC', width: 8, align: 'right' },
359
- ],
360
- data: complex.slice(0, 15).map(f => ({ file: path.relative(targetPath, f.file), nesting: f.maxNesting, fns: f.functions, loc: f.loc })),
361
- });
362
- }
363
- }
364
- else if (analysisType === 'security') {
365
- output.printBox([`Files Scanned: ${files.length}`, `Files with Issues: ${allSecurityIssues.length}`, `Total Issues: ${allSecurityIssues.reduce((s, f) => s + f.securityIssues.length, 0)}`].join('\n'), 'Security Summary');
366
- if (allSecurityIssues.length === 0) {
367
- output.writeln();
368
- output.printSuccess('No common security patterns detected');
369
- }
370
- else {
371
- output.writeln();
372
- output.writeln(output.bold('Security Concerns'));
373
- output.writeln(output.dim('-'.repeat(60)));
374
- output.printTable({
375
- columns: [
376
- { key: 'file', header: 'File', width: 40 },
377
- { key: 'issues', header: 'Issues', width: 35 },
378
- ],
379
- data: allSecurityIssues.map(f => ({ file: path.relative(targetPath, f.file), issues: f.securityIssues.join(', ') })),
380
- });
381
- }
382
- }
383
- else {
384
- output.printWarning(`Unknown analysis type: ${analysisType}. Use quality, complexity, or security.`);
385
- }
386
- return { success: true };
387
- }
388
- catch (error) {
389
- spinner.stop();
390
- const message = error instanceof Error ? error.message : String(error);
391
- output.printError(`Code analysis failed: ${message}`);
392
- return { success: false, exitCode: 1 };
393
- }
394
- },
395
- };
396
- // ============================================================================
397
- // AST Analysis Subcommands (using ruvector tree-sitter with fallback)
398
- // ============================================================================
399
- /**
400
- * Helper: Truncate file path for display
401
- */
402
- function truncatePathAst(filePath, maxLen = 45) {
403
- if (filePath.length <= maxLen)
404
- return filePath;
405
- return '...' + filePath.slice(-(maxLen - 3));
406
- }
407
- /**
408
- * Helper: Format complexity value with color coding
409
- */
410
- function formatComplexityValueAst(value) {
411
- if (value <= 5)
412
- return output.success(String(value));
413
- if (value <= 10)
414
- return output.warning(String(value));
415
- return output.error(String(value));
416
- }
417
- /**
418
- * Helper: Get type marker for symbols
419
- */
420
- function getTypeMarkerAst(type) {
421
- switch (type) {
422
- case 'function': return output.success('fn');
423
- case 'class': return output.info('class');
424
- case 'variable': return output.dim('var');
425
- case 'type': return output.highlight('type');
426
- case 'interface': return output.highlight('iface');
427
- default: return output.dim(type.slice(0, 5));
428
- }
429
- }
430
- /**
431
- * Helper: Get complexity rating text
432
- */
433
- function getComplexityRatingAst(value) {
434
- if (value <= 5)
435
- return output.success('Simple');
436
- if (value <= 10)
437
- return output.warning('Moderate');
438
- if (value <= 20)
439
- return output.error('Complex');
440
- return output.error(output.bold('Very Complex'));
441
- }
442
- /**
443
- * AST analysis subcommand
444
- */
445
- const astCommand = {
446
- name: 'ast',
447
- description: 'Analyze code using AST parsing (tree-sitter via ruvector)',
448
- options: [
449
- {
450
- name: 'complexity',
451
- short: 'c',
452
- description: 'Include complexity metrics',
453
- type: 'boolean',
454
- default: false,
455
- },
456
- {
457
- name: 'symbols',
458
- short: 's',
459
- description: 'Include symbol extraction',
460
- type: 'boolean',
461
- default: false,
462
- },
463
- {
464
- name: 'format',
465
- short: 'f',
466
- description: 'Output format (text, json, table)',
467
- type: 'string',
468
- default: 'text',
469
- choices: ['text', 'json', 'table'],
470
- },
471
- {
472
- name: 'output',
473
- short: 'o',
474
- description: 'Output file path',
475
- type: 'string',
476
- },
477
- {
478
- name: 'verbose',
479
- short: 'v',
480
- description: 'Show detailed analysis',
481
- type: 'boolean',
482
- default: false,
483
- },
484
- ],
485
- examples: [
486
- { command: 'claude-flow analyze ast src/', description: 'Analyze all files in src/' },
487
- { command: 'claude-flow analyze ast src/index.ts --complexity', description: 'Analyze with complexity' },
488
- { command: 'claude-flow analyze ast . --format json', description: 'JSON output' },
489
- { command: 'claude-flow analyze ast src/ --symbols', description: 'Extract symbols' },
490
- ],
491
- action: async (ctx) => {
492
- const targetPath = ctx.args[0] || ctx.cwd;
493
- const showComplexity = ctx.flags.complexity;
494
- const showSymbols = ctx.flags.symbols;
495
- const formatType = ctx.flags.format || 'text';
496
- const outputFile = ctx.flags.output;
497
- const verbose = ctx.flags.verbose;
498
- // If no specific flags, show summary
499
- const showAll = !showComplexity && !showSymbols;
500
- output.printInfo(`Analyzing: ${output.highlight(targetPath)}`);
501
- output.writeln();
502
- const spinner = output.createSpinner({ text: 'Parsing AST...', spinner: 'dots' });
503
- spinner.start();
504
- try {
505
- const astModule = await getASTAnalyzer();
506
- if (!astModule) {
507
- spinner.stop();
508
- output.printWarning('AST analyzer not available, using regex fallback');
509
- }
510
- // Resolve path and check if file or directory
511
- const resolvedPath = resolve(targetPath);
512
- const stat = await fs.stat(resolvedPath);
513
- const isDirectory = stat.isDirectory();
514
- let results = [];
515
- if (isDirectory) {
516
- // Scan directory for source files
517
- const files = await scanSourceFiles(resolvedPath);
518
- spinner.stop();
519
- output.printInfo(`Found ${files.length} source files`);
520
- spinner.start();
521
- for (const file of files.slice(0, 100)) {
522
- try {
523
- const content = await fs.readFile(file, 'utf-8');
524
- if (astModule) {
525
- const analyzer = astModule.createASTAnalyzer();
526
- const analysis = analyzer.analyze(content, file);
527
- results.push(analysis);
528
- }
529
- else {
530
- // Fallback analysis
531
- results.push(fallbackAnalyze(content, file));
532
- }
533
- }
534
- catch {
535
- // Skip files that can't be analyzed
536
- }
537
- }
538
- }
539
- else {
540
- // Single file
541
- const content = await fs.readFile(resolvedPath, 'utf-8');
542
- if (astModule) {
543
- const analyzer = astModule.createASTAnalyzer();
544
- const analysis = analyzer.analyze(content, resolvedPath);
545
- results.push(analysis);
546
- }
547
- else {
548
- results.push(fallbackAnalyze(content, resolvedPath));
549
- }
550
- }
551
- spinner.stop();
552
- if (results.length === 0) {
553
- output.printWarning('No files analyzed');
554
- return { success: true };
555
- }
556
- // Calculate totals
557
- const totals = {
558
- files: results.length,
559
- functions: results.reduce((sum, r) => sum + r.functions.length, 0),
560
- classes: results.reduce((sum, r) => sum + r.classes.length, 0),
561
- imports: results.reduce((sum, r) => sum + r.imports.length, 0),
562
- avgComplexity: results.reduce((sum, r) => sum + r.complexity.cyclomatic, 0) / results.length,
563
- totalLoc: results.reduce((sum, r) => sum + r.complexity.loc, 0),
564
- };
565
- // JSON output
566
- if (formatType === 'json') {
567
- const jsonOutput = { files: results, totals };
568
- if (outputFile) {
569
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
570
- output.printSuccess(`Results written to ${outputFile}`);
571
- }
572
- else {
573
- output.printJson(jsonOutput);
574
- }
575
- return { success: true, data: jsonOutput };
576
- }
577
- // Summary box
578
- output.printBox([
579
- `Files analyzed: ${totals.files}`,
580
- `Functions: ${totals.functions}`,
581
- `Classes: ${totals.classes}`,
582
- `Total LOC: ${totals.totalLoc}`,
583
- `Avg Complexity: ${formatComplexityValueAst(Math.round(totals.avgComplexity))}`,
584
- ].join('\n'), 'AST Analysis Summary');
585
- // Complexity view
586
- if (showComplexity || showAll) {
587
- output.writeln();
588
- output.writeln(output.bold('Complexity by File'));
589
- output.writeln(output.dim('-'.repeat(60)));
590
- const complexityData = results
591
- .map(r => ({
592
- file: truncatePathAst(r.filePath),
593
- cyclomatic: r.complexity.cyclomatic,
594
- cognitive: r.complexity.cognitive,
595
- loc: r.complexity.loc,
596
- rating: getComplexityRatingAst(r.complexity.cyclomatic),
597
- }))
598
- .sort((a, b) => b.cyclomatic - a.cyclomatic)
599
- .slice(0, 15);
600
- output.printTable({
601
- columns: [
602
- { key: 'file', header: 'File', width: 40 },
603
- { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v) },
604
- { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
605
- { key: 'loc', header: 'LOC', width: 8, align: 'right' },
606
- { key: 'rating', header: 'Rating', width: 15 },
607
- ],
608
- data: complexityData,
609
- });
610
- if (results.length > 15) {
611
- output.writeln(output.dim(` ... and ${results.length - 15} more files`));
612
- }
613
- }
614
- // Symbols view
615
- if (showSymbols || showAll) {
616
- output.writeln();
617
- output.writeln(output.bold('Extracted Symbols'));
618
- output.writeln(output.dim('-'.repeat(60)));
619
- const allSymbols = [];
620
- for (const r of results) {
621
- for (const fn of r.functions) {
622
- allSymbols.push({ name: fn.name, type: 'function', file: truncatePathAst(r.filePath, 30), line: fn.startLine });
623
- }
624
- for (const cls of r.classes) {
625
- allSymbols.push({ name: cls.name, type: 'class', file: truncatePathAst(r.filePath, 30), line: cls.startLine });
626
- }
627
- }
628
- const displaySymbols = allSymbols.slice(0, 20);
629
- output.printTable({
630
- columns: [
631
- { key: 'type', header: 'Type', width: 8, format: (v) => getTypeMarkerAst(v) },
632
- { key: 'name', header: 'Symbol', width: 30 },
633
- { key: 'file', header: 'File', width: 35 },
634
- { key: 'line', header: 'Line', width: 8, align: 'right' },
635
- ],
636
- data: displaySymbols,
637
- });
638
- if (allSymbols.length > 20) {
639
- output.writeln(output.dim(` ... and ${allSymbols.length - 20} more symbols`));
640
- }
641
- }
642
- // Verbose output
643
- if (verbose) {
644
- output.writeln();
645
- output.writeln(output.bold('Import Analysis'));
646
- output.writeln(output.dim('-'.repeat(60)));
647
- const importCounts = new Map();
648
- for (const r of results) {
649
- for (const imp of r.imports) {
650
- importCounts.set(imp, (importCounts.get(imp) || 0) + 1);
651
- }
652
- }
653
- const topImports = Array.from(importCounts.entries())
654
- .sort((a, b) => b[1] - a[1])
655
- .slice(0, 10);
656
- for (const [imp, count] of topImports) {
657
- output.writeln(` ${output.highlight(count.toString().padStart(3))} ${imp}`);
658
- }
659
- }
660
- if (outputFile) {
661
- await writeFile(outputFile, JSON.stringify({ files: results, totals }, null, 2));
662
- output.printSuccess(`Results written to ${outputFile}`);
663
- }
664
- return { success: true, data: { files: results, totals } };
665
- }
666
- catch (error) {
667
- spinner.stop();
668
- const message = error instanceof Error ? error.message : String(error);
669
- output.printError(`AST analysis failed: ${message}`);
670
- return { success: false, exitCode: 1 };
671
- }
672
- },
673
- };
674
- /**
675
- * Complexity analysis subcommand
676
- */
677
- const complexityAstCommand = {
678
- name: 'complexity',
679
- aliases: ['cx'],
680
- description: 'Analyze code complexity metrics',
681
- options: [
682
- {
683
- name: 'threshold',
684
- short: 't',
685
- description: 'Complexity threshold to flag (default: 10)',
686
- type: 'number',
687
- default: 10,
688
- },
689
- {
690
- name: 'format',
691
- short: 'f',
692
- description: 'Output format (text, json)',
693
- type: 'string',
694
- default: 'text',
695
- choices: ['text', 'json'],
696
- },
697
- {
698
- name: 'output',
699
- short: 'o',
700
- description: 'Output file path',
701
- type: 'string',
702
- },
703
- ],
704
- examples: [
705
- { command: 'claude-flow analyze complexity src/', description: 'Analyze complexity' },
706
- { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Flag high complexity' },
707
- ],
708
- action: async (ctx) => {
709
- const targetPath = ctx.args[0] || ctx.cwd;
710
- const threshold = ctx.flags.threshold || 10;
711
- const formatType = ctx.flags.format || 'text';
712
- const outputFile = ctx.flags.output;
713
- output.printInfo(`Analyzing complexity: ${output.highlight(targetPath)}`);
714
- output.writeln();
715
- const spinner = output.createSpinner({ text: 'Calculating complexity...', spinner: 'dots' });
716
- spinner.start();
717
- try {
718
- const astModule = await getASTAnalyzer();
719
- const resolvedPath = resolve(targetPath);
720
- const stat = await fs.stat(resolvedPath);
721
- const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
722
- const results = [];
723
- for (const file of files.slice(0, 100)) {
724
- try {
725
- const content = await fs.readFile(file, 'utf-8');
726
- let analysis;
727
- if (astModule) {
728
- const analyzer = astModule.createASTAnalyzer();
729
- analysis = analyzer.analyze(content, file);
730
- }
731
- else {
732
- analysis = fallbackAnalyze(content, file);
733
- }
734
- const flagged = analysis.complexity.cyclomatic > threshold;
735
- const rating = analysis.complexity.cyclomatic <= 5 ? 'Simple' :
736
- analysis.complexity.cyclomatic <= 10 ? 'Moderate' :
737
- analysis.complexity.cyclomatic <= 20 ? 'Complex' : 'Very Complex';
738
- results.push({
739
- file: file,
740
- cyclomatic: analysis.complexity.cyclomatic,
741
- cognitive: analysis.complexity.cognitive,
742
- loc: analysis.complexity.loc,
743
- commentDensity: analysis.complexity.commentDensity,
744
- rating,
745
- flagged,
746
- });
747
- }
748
- catch {
749
- // Skip files that can't be analyzed
750
- }
751
- }
752
- spinner.stop();
753
- // Sort by complexity descending
754
- results.sort((a, b) => b.cyclomatic - a.cyclomatic);
755
- const flaggedCount = results.filter(r => r.flagged).length;
756
- const avgComplexity = results.length > 0
757
- ? results.reduce((sum, r) => sum + r.cyclomatic, 0) / results.length
758
- : 0;
759
- if (formatType === 'json') {
760
- const jsonOutput = { files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } };
761
- if (outputFile) {
762
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
763
- output.printSuccess(`Results written to ${outputFile}`);
764
- }
765
- else {
766
- output.printJson(jsonOutput);
767
- }
768
- return { success: true, data: jsonOutput };
769
- }
770
- // Summary
771
- output.printBox([
772
- `Files analyzed: ${results.length}`,
773
- `Threshold: ${threshold}`,
774
- `Flagged files: ${flaggedCount > 0 ? output.error(String(flaggedCount)) : output.success('0')}`,
775
- `Average complexity: ${formatComplexityValueAst(Math.round(avgComplexity))}`,
776
- ].join('\n'), 'Complexity Analysis');
777
- // Show flagged files first
778
- if (flaggedCount > 0) {
779
- output.writeln();
780
- output.writeln(output.bold(output.warning(`High Complexity Files (>${threshold})`)));
781
- output.writeln(output.dim('-'.repeat(60)));
782
- const flaggedFiles = results.filter(r => r.flagged).slice(0, 10);
783
- output.printTable({
784
- columns: [
785
- { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v) },
786
- { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => output.error(String(v)) },
787
- { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
788
- { key: 'loc', header: 'LOC', width: 8, align: 'right' },
789
- { key: 'rating', header: 'Rating', width: 15 },
790
- ],
791
- data: flaggedFiles,
792
- });
793
- }
794
- // Show all files in table format
795
- output.writeln();
796
- output.writeln(output.bold('All Files'));
797
- output.writeln(output.dim('-'.repeat(60)));
798
- const displayFiles = results.slice(0, 15);
799
- output.printTable({
800
- columns: [
801
- { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v) },
802
- { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v) },
803
- { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
804
- { key: 'loc', header: 'LOC', width: 8, align: 'right' },
805
- ],
806
- data: displayFiles,
807
- });
808
- if (results.length > 15) {
809
- output.writeln(output.dim(` ... and ${results.length - 15} more files`));
810
- }
811
- if (outputFile) {
812
- await writeFile(outputFile, JSON.stringify({ files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } }, null, 2));
813
- output.printSuccess(`Results written to ${outputFile}`);
814
- }
815
- return { success: true, data: { files: results, flaggedCount } };
816
- }
817
- catch (error) {
818
- spinner.stop();
819
- const message = error instanceof Error ? error.message : String(error);
820
- output.printError(`Complexity analysis failed: ${message}`);
821
- return { success: false, exitCode: 1 };
822
- }
823
- },
824
- };
825
- /**
826
- * Symbol extraction subcommand
827
- */
828
- const symbolsCommand = {
829
- name: 'symbols',
830
- aliases: ['sym'],
831
- description: 'Extract and list code symbols (functions, classes, types)',
832
- options: [
833
- {
834
- name: 'type',
835
- short: 't',
836
- description: 'Filter by symbol type (function, class, all)',
837
- type: 'string',
838
- default: 'all',
839
- choices: ['function', 'class', 'all'],
840
- },
841
- {
842
- name: 'format',
843
- short: 'f',
844
- description: 'Output format (text, json)',
845
- type: 'string',
846
- default: 'text',
847
- choices: ['text', 'json'],
848
- },
849
- {
850
- name: 'output',
851
- short: 'o',
852
- description: 'Output file path',
853
- type: 'string',
854
- },
855
- ],
856
- examples: [
857
- { command: 'claude-flow analyze symbols src/', description: 'Extract all symbols' },
858
- { command: 'claude-flow analyze symbols src/ --type function', description: 'Only functions' },
859
- { command: 'claude-flow analyze symbols src/ --format json', description: 'JSON output' },
860
- ],
861
- action: async (ctx) => {
862
- const targetPath = ctx.args[0] || ctx.cwd;
863
- const symbolType = ctx.flags.type || 'all';
864
- const formatType = ctx.flags.format || 'text';
865
- const outputFile = ctx.flags.output;
866
- output.printInfo(`Extracting symbols: ${output.highlight(targetPath)}`);
867
- output.writeln();
868
- const spinner = output.createSpinner({ text: 'Parsing code...', spinner: 'dots' });
869
- spinner.start();
870
- try {
871
- const astModule = await getASTAnalyzer();
872
- const resolvedPath = resolve(targetPath);
873
- const stat = await fs.stat(resolvedPath);
874
- const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
875
- const symbols = [];
876
- for (const file of files.slice(0, 100)) {
877
- try {
878
- const content = await fs.readFile(file, 'utf-8');
879
- let analysis;
880
- if (astModule) {
881
- const analyzer = astModule.createASTAnalyzer();
882
- analysis = analyzer.analyze(content, file);
883
- }
884
- else {
885
- analysis = fallbackAnalyze(content, file);
886
- }
887
- if (symbolType === 'all' || symbolType === 'function') {
888
- for (const fn of analysis.functions) {
889
- symbols.push({
890
- name: fn.name,
891
- type: 'function',
892
- file,
893
- startLine: fn.startLine,
894
- endLine: fn.endLine,
895
- });
896
- }
897
- }
898
- if (symbolType === 'all' || symbolType === 'class') {
899
- for (const cls of analysis.classes) {
900
- symbols.push({
901
- name: cls.name,
902
- type: 'class',
903
- file,
904
- startLine: cls.startLine,
905
- endLine: cls.endLine,
906
- });
907
- }
908
- }
909
- }
910
- catch {
911
- // Skip files that can't be parsed
912
- }
913
- }
914
- spinner.stop();
915
- // Sort by file then name
916
- symbols.sort((a, b) => a.file.localeCompare(b.file) || a.name.localeCompare(b.name));
917
- if (formatType === 'json') {
918
- if (outputFile) {
919
- await writeFile(outputFile, JSON.stringify(symbols, null, 2));
920
- output.printSuccess(`Results written to ${outputFile}`);
921
- }
922
- else {
923
- output.printJson(symbols);
924
- }
925
- return { success: true, data: symbols };
926
- }
927
- // Summary
928
- const functionCount = symbols.filter(s => s.type === 'function').length;
929
- const classCount = symbols.filter(s => s.type === 'class').length;
930
- output.printBox([
931
- `Total symbols: ${symbols.length}`,
932
- `Functions: ${functionCount}`,
933
- `Classes: ${classCount}`,
934
- `Files: ${files.length}`,
935
- ].join('\n'), 'Symbol Extraction');
936
- output.writeln();
937
- output.writeln(output.bold('Symbols'));
938
- output.writeln(output.dim('-'.repeat(60)));
939
- const displaySymbols = symbols.slice(0, 30);
940
- output.printTable({
941
- columns: [
942
- { key: 'type', header: 'Type', width: 10, format: (v) => getTypeMarkerAst(v) },
943
- { key: 'name', header: 'Name', width: 30 },
944
- { key: 'file', header: 'File', width: 35, format: (v) => truncatePathAst(v, 33) },
945
- { key: 'startLine', header: 'Line', width: 8, align: 'right' },
946
- ],
947
- data: displaySymbols,
948
- });
949
- if (symbols.length > 30) {
950
- output.writeln(output.dim(` ... and ${symbols.length - 30} more symbols`));
951
- }
952
- if (outputFile) {
953
- await writeFile(outputFile, JSON.stringify(symbols, null, 2));
954
- output.printSuccess(`Results written to ${outputFile}`);
955
- }
956
- return { success: true, data: symbols };
957
- }
958
- catch (error) {
959
- spinner.stop();
960
- const message = error instanceof Error ? error.message : String(error);
961
- output.printError(`Symbol extraction failed: ${message}`);
962
- return { success: false, exitCode: 1 };
963
- }
964
- },
965
- };
966
- /**
967
- * Imports analysis subcommand
968
- */
969
- const importsCommand = {
970
- name: 'imports',
971
- aliases: ['imp'],
972
- description: 'Analyze import dependencies across files',
973
- options: [
974
- {
975
- name: 'format',
976
- short: 'f',
977
- description: 'Output format (text, json)',
978
- type: 'string',
979
- default: 'text',
980
- choices: ['text', 'json'],
981
- },
982
- {
983
- name: 'output',
984
- short: 'o',
985
- description: 'Output file path',
986
- type: 'string',
987
- },
988
- {
989
- name: 'external',
990
- short: 'e',
991
- description: 'Show only external (npm) imports',
992
- type: 'boolean',
993
- default: false,
994
- },
995
- ],
996
- examples: [
997
- { command: 'claude-flow analyze imports src/', description: 'Analyze all imports' },
998
- { command: 'claude-flow analyze imports src/ --external', description: 'Only npm packages' },
999
- ],
1000
- action: async (ctx) => {
1001
- const targetPath = ctx.args[0] || ctx.cwd;
1002
- const formatType = ctx.flags.format || 'text';
1003
- const outputFile = ctx.flags.output;
1004
- const externalOnly = ctx.flags.external;
1005
- output.printInfo(`Analyzing imports: ${output.highlight(targetPath)}`);
1006
- output.writeln();
1007
- const spinner = output.createSpinner({ text: 'Scanning imports...', spinner: 'dots' });
1008
- spinner.start();
1009
- try {
1010
- const astModule = await getASTAnalyzer();
1011
- const resolvedPath = resolve(targetPath);
1012
- const stat = await fs.stat(resolvedPath);
1013
- const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
1014
- const importCounts = new Map();
1015
- const fileImports = new Map();
1016
- for (const file of files.slice(0, 100)) {
1017
- try {
1018
- const content = await fs.readFile(file, 'utf-8');
1019
- let analysis;
1020
- if (astModule) {
1021
- const analyzer = astModule.createASTAnalyzer();
1022
- analysis = analyzer.analyze(content, file);
1023
- }
1024
- else {
1025
- analysis = fallbackAnalyze(content, file);
1026
- }
1027
- const imports = analysis.imports.filter(imp => {
1028
- if (externalOnly) {
1029
- return !imp.startsWith('.') && !imp.startsWith('/');
1030
- }
1031
- return true;
1032
- });
1033
- fileImports.set(file, imports);
1034
- for (const imp of imports) {
1035
- const existing = importCounts.get(imp) || { count: 0, files: [] };
1036
- existing.count++;
1037
- existing.files.push(file);
1038
- importCounts.set(imp, existing);
1039
- }
1040
- }
1041
- catch {
1042
- // Skip files that can't be parsed
1043
- }
1044
- }
1045
- spinner.stop();
1046
- // Sort by count
1047
- const sortedImports = Array.from(importCounts.entries())
1048
- .sort((a, b) => b[1].count - a[1].count);
1049
- if (formatType === 'json') {
1050
- const jsonOutput = {
1051
- imports: Object.fromEntries(sortedImports),
1052
- fileImports: Object.fromEntries(fileImports),
1053
- };
1054
- if (outputFile) {
1055
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1056
- output.printSuccess(`Results written to ${outputFile}`);
1057
- }
1058
- else {
1059
- output.printJson(jsonOutput);
1060
- }
1061
- return { success: true, data: jsonOutput };
1062
- }
1063
- // Summary
1064
- const externalImports = sortedImports.filter(([imp]) => !imp.startsWith('.') && !imp.startsWith('/'));
1065
- const localImports = sortedImports.filter(([imp]) => imp.startsWith('.') || imp.startsWith('/'));
1066
- output.printBox([
1067
- `Total unique imports: ${sortedImports.length}`,
1068
- `External (npm): ${externalImports.length}`,
1069
- `Local (relative): ${localImports.length}`,
1070
- `Files scanned: ${files.length}`,
1071
- ].join('\n'), 'Import Analysis');
1072
- // Most used imports
1073
- output.writeln();
1074
- output.writeln(output.bold('Most Used Imports'));
1075
- output.writeln(output.dim('-'.repeat(60)));
1076
- const topImports = sortedImports.slice(0, 20);
1077
- output.printTable({
1078
- columns: [
1079
- { key: 'count', header: 'Uses', width: 8, align: 'right' },
1080
- { key: 'import', header: 'Import', width: 50 },
1081
- { key: 'type', header: 'Type', width: 10 },
1082
- ],
1083
- data: topImports.map(([imp, data]) => ({
1084
- count: data.count,
1085
- import: imp,
1086
- type: imp.startsWith('.') || imp.startsWith('/') ? output.dim('local') : output.highlight('npm'),
1087
- })),
1088
- });
1089
- if (sortedImports.length > 20) {
1090
- output.writeln(output.dim(` ... and ${sortedImports.length - 20} more imports`));
1091
- }
1092
- if (outputFile) {
1093
- await writeFile(outputFile, JSON.stringify({
1094
- imports: Object.fromEntries(sortedImports),
1095
- fileImports: Object.fromEntries(fileImports),
1096
- }, null, 2));
1097
- output.printSuccess(`Results written to ${outputFile}`);
1098
- }
1099
- return { success: true, data: { imports: sortedImports } };
1100
- }
1101
- catch (error) {
1102
- spinner.stop();
1103
- const message = error instanceof Error ? error.message : String(error);
1104
- output.printError(`Import analysis failed: ${message}`);
1105
- return { success: false, exitCode: 1 };
1106
- }
1107
- },
1108
- };
1109
- /**
1110
- * Helper: Scan directory for source files
1111
- */
1112
- async function scanSourceFiles(dir, maxDepth = 10) {
1113
- const files = [];
1114
- const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
1115
- const excludeDirs = ['node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__'];
1116
- async function scan(currentDir, depth) {
1117
- if (depth > maxDepth)
1118
- return;
1119
- try {
1120
- const entries = await fs.readdir(currentDir, { withFileTypes: true });
1121
- for (const entry of entries) {
1122
- const fullPath = path.join(currentDir, entry.name);
1123
- if (entry.isDirectory()) {
1124
- if (!excludeDirs.includes(entry.name)) {
1125
- await scan(fullPath, depth + 1);
1126
- }
1127
- }
1128
- else if (entry.isFile()) {
1129
- const ext = path.extname(entry.name);
1130
- if (extensions.includes(ext)) {
1131
- files.push(fullPath);
1132
- }
1133
- }
1134
- }
1135
- }
1136
- catch {
1137
- // Skip directories we can't read
1138
- }
1139
- }
1140
- await scan(dir, 0);
1141
- return files;
1142
- }
1143
- /**
1144
- * Fallback analysis when ruvector is not available
1145
- */
1146
- function fallbackAnalyze(code, filePath) {
1147
- const lines = code.split('\n');
1148
- const functions = [];
1149
- const classes = [];
1150
- const imports = [];
1151
- const exports = [];
1152
- // Extract functions
1153
- const funcPattern = /(?:export\s+)?(?:async\s+)?function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>|^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*(?::\s*\w+)?\s*\{/gm;
1154
- let match;
1155
- while ((match = funcPattern.exec(code)) !== null) {
1156
- const name = match[1] || match[2] || match[3];
1157
- if (name && !['if', 'while', 'for', 'switch'].includes(name)) {
1158
- const lineNum = code.substring(0, match.index).split('\n').length;
1159
- functions.push({ name, startLine: lineNum, endLine: lineNum + 10 });
1160
- }
1161
- }
1162
- // Extract classes
1163
- const classPattern = /(?:export\s+)?class\s+(\w+)/gm;
1164
- while ((match = classPattern.exec(code)) !== null) {
1165
- const lineNum = code.substring(0, match.index).split('\n').length;
1166
- classes.push({ name: match[1], startLine: lineNum, endLine: lineNum + 20 });
1167
- }
1168
- // Extract imports
1169
- const importPattern = /import\s+(?:.*\s+from\s+)?['"]([^'"]+)['"]/gm;
1170
- while ((match = importPattern.exec(code)) !== null) {
1171
- imports.push(match[1]);
1172
- }
1173
- const requirePattern = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/gm;
1174
- while ((match = requirePattern.exec(code)) !== null) {
1175
- imports.push(match[1]);
1176
- }
1177
- // Extract exports
1178
- const exportPattern = /export\s+(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/gm;
1179
- while ((match = exportPattern.exec(code)) !== null) {
1180
- exports.push(match[1]);
1181
- }
1182
- // Calculate complexity
1183
- const nonEmptyLines = lines.filter(l => l.trim().length > 0).length;
1184
- const commentLines = lines.filter(l => /^\s*(\/\/|\/\*|\*|#)/.test(l)).length;
1185
- const decisionPoints = (code.match(/\b(if|else|for|while|switch|case|catch|&&|\|\||\?)\b/g) || []).length;
1186
- let cognitive = 0;
1187
- let nestingLevel = 0;
1188
- for (const line of lines) {
1189
- const opens = (line.match(/\{/g) || []).length;
1190
- const closes = (line.match(/\}/g) || []).length;
1191
- if (/\b(if|for|while|switch)\b/.test(line)) {
1192
- cognitive += 1 + nestingLevel;
1193
- }
1194
- nestingLevel = Math.max(0, nestingLevel + opens - closes);
1195
- }
1196
- // Detect language
1197
- const ext = path.extname(filePath).toLowerCase();
1198
- const language = ext === '.ts' || ext === '.tsx' ? 'typescript' :
1199
- ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs' ? 'javascript' :
1200
- ext === '.py' ? 'python' : 'unknown';
1201
- return {
1202
- filePath,
1203
- language,
1204
- functions,
1205
- classes,
1206
- imports,
1207
- exports,
1208
- complexity: {
1209
- cyclomatic: decisionPoints + 1,
1210
- cognitive,
1211
- loc: nonEmptyLines,
1212
- commentDensity: lines.length > 0 ? commentLines / lines.length : 0,
1213
- },
1214
- };
1215
- }
1216
- // Dependencies subcommand
1217
- const depsCommand = {
1218
- name: 'deps',
1219
- description: 'Analyze project dependencies',
1220
- options: [
1221
- { name: 'outdated', short: 'o', type: 'boolean', description: 'Show only outdated dependencies' },
1222
- { name: 'security', short: 's', type: 'boolean', description: 'Check for security vulnerabilities' },
1223
- { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
1224
- ],
1225
- examples: [
1226
- { command: 'claude-flow analyze deps --outdated', description: 'Show outdated dependencies' },
1227
- { command: 'claude-flow analyze deps --security', description: 'Check for vulnerabilities' },
1228
- ],
1229
- action: async (ctx) => {
1230
- const showOutdated = ctx.flags.outdated;
1231
- const checkSecurity = ctx.flags.security;
1232
- const formatJson = ctx.flags.format === 'json';
1233
- output.writeln();
1234
- output.writeln(output.bold('Dependency Analysis'));
1235
- output.writeln(output.dim('-'.repeat(50)));
1236
- try {
1237
- const pkgPath = resolve('package.json');
1238
- let pkgContent;
1239
- try {
1240
- pkgContent = await fs.readFile(pkgPath, 'utf-8');
1241
- }
1242
- catch {
1243
- output.printError('No package.json found in current directory');
1244
- return { success: false, exitCode: 1 };
1245
- }
1246
- const pkg = JSON.parse(pkgContent);
1247
- const deps = Object.entries(pkg.dependencies || {});
1248
- const devDeps = Object.entries(pkg.devDependencies || {});
1249
- const optDeps = Object.entries(pkg.optionalDependencies || {});
1250
- const peerDeps = Object.entries(pkg.peerDependencies || {});
1251
- const total = deps.length + devDeps.length + optDeps.length + peerDeps.length;
1252
- if (formatJson && !showOutdated && !checkSecurity) {
1253
- const jsonData = { name: pkg.name, version: pkg.version, dependencies: deps.length, devDependencies: devDeps.length, optionalDependencies: optDeps.length, peerDependencies: peerDeps.length, total };
1254
- output.printJson(jsonData);
1255
- return { success: true, data: jsonData };
1256
- }
1257
- output.printBox([`Package: ${pkg.name || 'unknown'} @ ${pkg.version || '0.0.0'}`, `Dependencies: ${deps.length}`, `Dev Dependencies: ${devDeps.length}`, `Optional: ${optDeps.length}`, `Peer: ${peerDeps.length}`, `Total: ${total}`].join('\n'), 'Dependency Summary');
1258
- if (showOutdated) {
1259
- output.writeln();
1260
- output.writeln(output.bold('Outdated Check'));
1261
- output.writeln(output.dim('-'.repeat(60)));
1262
- const outdated = [];
1263
- const checkDeps = async (entries, category) => {
1264
- for (const [name, declared] of entries) {
1265
- try {
1266
- const installedPkg = resolve('node_modules', name, 'package.json');
1267
- const raw = await fs.readFile(installedPkg, 'utf-8');
1268
- const installedContent = JSON.parse(raw);
1269
- const installed = installedContent.version || 'unknown';
1270
- const cleanDeclared = declared.replace(/^[\^~>=<]+/, '');
1271
- if (installed !== cleanDeclared) {
1272
- outdated.push({ name, declared: declared, installed, category });
1273
- }
1274
- }
1275
- catch {
1276
- outdated.push({ name, declared: declared, installed: 'not installed', category });
1277
- }
1278
- }
1279
- };
1280
- await checkDeps(deps, 'prod');
1281
- await checkDeps(devDeps, 'dev');
1282
- if (outdated.length === 0) {
1283
- output.printSuccess('All dependencies match declared versions');
1284
- }
1285
- else {
1286
- output.printTable({
1287
- columns: [
1288
- { key: 'name', header: 'Package', width: 30 },
1289
- { key: 'declared', header: 'Declared', width: 14 },
1290
- { key: 'installed', header: 'Installed', width: 14 },
1291
- { key: 'category', header: 'Type', width: 6 },
1292
- ],
1293
- data: outdated.slice(0, 30),
1294
- });
1295
- if (outdated.length > 30) {
1296
- output.writeln(output.dim(` ... and ${outdated.length - 30} more`));
1297
- }
1298
- }
1299
- }
1300
- if (checkSecurity) {
1301
- output.writeln();
1302
- output.writeln(output.bold('Security Audit'));
1303
- output.writeln(output.dim('-'.repeat(60)));
1304
- try {
1305
- const auditRaw = execSync('npm audit --json 2>/dev/null', { encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
1306
- const audit = JSON.parse(auditRaw);
1307
- const vulns = audit.metadata?.vulnerabilities || audit.vulnerabilities || {};
1308
- const info = vulns.info || 0;
1309
- const low = vulns.low || 0;
1310
- const moderate = vulns.moderate || 0;
1311
- const high = vulns.high || 0;
1312
- const critical = vulns.critical || 0;
1313
- const totalVulns = info + low + moderate + high + critical;
1314
- if (totalVulns === 0) {
1315
- output.printSuccess('No known vulnerabilities found');
1316
- }
1317
- else {
1318
- output.printTable({
1319
- columns: [
1320
- { key: 'severity', header: 'Severity', width: 12 },
1321
- { key: 'count', header: 'Count', width: 8, align: 'right' },
1322
- ],
1323
- data: [
1324
- ...(critical > 0 ? [{ severity: 'Critical', count: critical }] : []),
1325
- ...(high > 0 ? [{ severity: 'High', count: high }] : []),
1326
- ...(moderate > 0 ? [{ severity: 'Moderate', count: moderate }] : []),
1327
- ...(low > 0 ? [{ severity: 'Low', count: low }] : []),
1328
- ...(info > 0 ? [{ severity: 'Info', count: info }] : []),
1329
- { severity: 'Total', count: totalVulns },
1330
- ],
1331
- });
1332
- if (critical > 0 || high > 0) {
1333
- output.printWarning(`${critical + high} high/critical vulnerabilities found. Run 'npm audit' for details.`);
1334
- }
1335
- }
1336
- }
1337
- catch {
1338
- output.printWarning('npm audit failed. Ensure npm is available and node_modules is installed.');
1339
- }
1340
- }
1341
- return { success: true };
1342
- }
1343
- catch (error) {
1344
- const message = error instanceof Error ? error.message : String(error);
1345
- output.printError(`Dependency analysis failed: ${message}`);
1346
- return { success: false, exitCode: 1 };
1347
- }
1348
- },
1349
- };
1350
- // ============================================================================
1351
- // Graph Analysis Subcommands (MinCut, Louvain, Circular Dependencies)
1352
- // ============================================================================
1353
- /**
1354
- * Analyze code boundaries using MinCut algorithm
1355
- */
1356
- const boundariesCommand = {
1357
- name: 'boundaries',
1358
- aliases: ['boundary', 'mincut'],
1359
- description: 'Find natural code boundaries using MinCut algorithm',
1360
- options: [
1361
- {
1362
- name: 'partitions',
1363
- short: 'p',
1364
- description: 'Number of partitions to find',
1365
- type: 'number',
1366
- default: 2,
1367
- },
1368
- {
1369
- name: 'output',
1370
- short: 'o',
1371
- description: 'Output file path',
1372
- type: 'string',
1373
- },
1374
- {
1375
- name: 'format',
1376
- short: 'f',
1377
- description: 'Output format (text, json, dot)',
1378
- type: 'string',
1379
- default: 'text',
1380
- choices: ['text', 'json', 'dot'],
1381
- },
1382
- ],
1383
- examples: [
1384
- { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries in src/' },
1385
- { command: 'claude-flow analyze boundaries -p 3 src/', description: 'Find 3 partitions' },
1386
- { command: 'claude-flow analyze boundaries -f dot -o graph.dot src/', description: 'Export to DOT format' },
1387
- ],
1388
- action: async (ctx) => {
1389
- const targetDir = ctx.args[0] || ctx.cwd;
1390
- const numPartitions = ctx.flags.partitions || 2;
1391
- const outputFile = ctx.flags.output;
1392
- const format = ctx.flags.format || 'text';
1393
- output.printInfo(`Analyzing code boundaries in: ${output.highlight(targetDir)}`);
1394
- output.writeln();
1395
- const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
1396
- spinner.start();
1397
- try {
1398
- const analyzer = await getGraphAnalyzer();
1399
- if (!analyzer) {
1400
- spinner.stop();
1401
- output.printError('Graph analyzer module not available');
1402
- return { success: false, exitCode: 1 };
1403
- }
1404
- const result = await analyzer.analyzeGraph(resolve(targetDir), {
1405
- includeBoundaries: true,
1406
- includeModules: false,
1407
- numPartitions,
1408
- });
1409
- spinner.stop();
1410
- // Handle different output formats
1411
- if (format === 'json') {
1412
- const jsonOutput = {
1413
- boundaries: result.boundaries,
1414
- statistics: result.statistics,
1415
- circularDependencies: result.circularDependencies,
1416
- };
1417
- if (outputFile) {
1418
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1419
- output.printSuccess(`Results written to ${outputFile}`);
1420
- }
1421
- else {
1422
- output.printJson(jsonOutput);
1423
- }
1424
- return { success: true, data: jsonOutput };
1425
- }
1426
- if (format === 'dot') {
1427
- const dotOutput = analyzer.exportToDot(result, {
1428
- includeLabels: true,
1429
- highlightCycles: true,
1430
- });
1431
- if (outputFile) {
1432
- await writeFile(outputFile, dotOutput);
1433
- output.printSuccess(`DOT graph written to ${outputFile}`);
1434
- output.writeln(output.dim('Visualize with: dot -Tpng -o graph.png ' + outputFile));
1435
- }
1436
- else {
1437
- output.writeln(dotOutput);
1438
- }
1439
- return { success: true };
1440
- }
1441
- // Text format (default)
1442
- output.printBox([
1443
- `Files analyzed: ${result.statistics.nodeCount}`,
1444
- `Dependencies: ${result.statistics.edgeCount}`,
1445
- `Avg degree: ${result.statistics.avgDegree.toFixed(2)}`,
1446
- `Density: ${(result.statistics.density * 100).toFixed(2)}%`,
1447
- `Components: ${result.statistics.componentCount}`,
1448
- ].join('\n'), 'Graph Statistics');
1449
- if (result.boundaries && result.boundaries.length > 0) {
1450
- output.writeln();
1451
- output.writeln(output.bold('MinCut Boundaries'));
1452
- output.writeln();
1453
- for (let i = 0; i < result.boundaries.length; i++) {
1454
- const boundary = result.boundaries[i];
1455
- output.writeln(output.bold(`Boundary ${i + 1} (cut value: ${boundary.cutValue})`));
1456
- output.writeln();
1457
- output.writeln(output.dim('Partition 1:'));
1458
- const p1Display = boundary.partition1.slice(0, 10);
1459
- output.printList(p1Display);
1460
- if (boundary.partition1.length > 10) {
1461
- output.writeln(output.dim(` ... and ${boundary.partition1.length - 10} more files`));
1462
- }
1463
- output.writeln();
1464
- output.writeln(output.dim('Partition 2:'));
1465
- const p2Display = boundary.partition2.slice(0, 10);
1466
- output.printList(p2Display);
1467
- if (boundary.partition2.length > 10) {
1468
- output.writeln(output.dim(` ... and ${boundary.partition2.length - 10} more files`));
1469
- }
1470
- output.writeln();
1471
- output.writeln(output.success('Suggestion:'));
1472
- output.writeln(` ${boundary.suggestion}`);
1473
- output.writeln();
1474
- }
1475
- }
1476
- // Show circular dependencies
1477
- if (result.circularDependencies.length > 0) {
1478
- output.writeln();
1479
- output.writeln(output.bold(output.warning('Circular Dependencies Detected')));
1480
- output.writeln();
1481
- for (const cycle of result.circularDependencies.slice(0, 5)) {
1482
- const severityColor = cycle.severity === 'high' ? output.error : cycle.severity === 'medium' ? output.warning : output.dim;
1483
- output.writeln(`${severityColor(`[${cycle.severity.toUpperCase()}]`)} ${cycle.cycle.join(' -> ')}`);
1484
- output.writeln(output.dim(` ${cycle.suggestion}`));
1485
- output.writeln();
1486
- }
1487
- if (result.circularDependencies.length > 5) {
1488
- output.writeln(output.dim(`... and ${result.circularDependencies.length - 5} more cycles`));
1489
- }
1490
- }
1491
- if (outputFile) {
1492
- await writeFile(outputFile, JSON.stringify(result, null, 2));
1493
- output.printSuccess(`Full results written to ${outputFile}`);
1494
- }
1495
- return { success: true, data: result };
1496
- }
1497
- catch (error) {
1498
- spinner.stop();
1499
- const message = error instanceof Error ? error.message : String(error);
1500
- output.printError(`Analysis failed: ${message}`);
1501
- return { success: false, exitCode: 1 };
1502
- }
1503
- },
1504
- };
1505
- /**
1506
- * Analyze modules/communities using Louvain algorithm
1507
- */
1508
- const modulesCommand = {
1509
- name: 'modules',
1510
- aliases: ['communities', 'louvain'],
1511
- description: 'Detect module communities using Louvain algorithm',
1512
- options: [
1513
- {
1514
- name: 'output',
1515
- short: 'o',
1516
- description: 'Output file path',
1517
- type: 'string',
1518
- },
1519
- {
1520
- name: 'format',
1521
- short: 'f',
1522
- description: 'Output format (text, json, dot)',
1523
- type: 'string',
1524
- default: 'text',
1525
- choices: ['text', 'json', 'dot'],
1526
- },
1527
- {
1528
- name: 'min-size',
1529
- short: 'm',
1530
- description: 'Minimum community size to display',
1531
- type: 'number',
1532
- default: 2,
1533
- },
1534
- ],
1535
- examples: [
1536
- { command: 'claude-flow analyze modules src/', description: 'Detect module communities' },
1537
- { command: 'claude-flow analyze modules -f dot -o modules.dot src/', description: 'Export colored DOT graph' },
1538
- { command: 'claude-flow analyze modules -m 3 src/', description: 'Only show communities with 3+ files' },
1539
- ],
1540
- action: async (ctx) => {
1541
- const targetDir = ctx.args[0] || ctx.cwd;
1542
- const outputFile = ctx.flags.output;
1543
- const format = ctx.flags.format || 'text';
1544
- const minSize = ctx.flags['min-size'] || 2;
1545
- output.printInfo(`Detecting module communities in: ${output.highlight(targetDir)}`);
1546
- output.writeln();
1547
- const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
1548
- spinner.start();
1549
- try {
1550
- const analyzer = await getGraphAnalyzer();
1551
- if (!analyzer) {
1552
- spinner.stop();
1553
- output.printError('Graph analyzer module not available');
1554
- return { success: false, exitCode: 1 };
1555
- }
1556
- const result = await analyzer.analyzeGraph(resolve(targetDir), {
1557
- includeBoundaries: false,
1558
- includeModules: true,
1559
- });
1560
- spinner.stop();
1561
- // Filter communities by size
1562
- const communities = result.communities?.filter(c => c.members.length >= minSize) || [];
1563
- // Handle different output formats
1564
- if (format === 'json') {
1565
- const jsonOutput = {
1566
- communities,
1567
- statistics: result.statistics,
1568
- };
1569
- if (outputFile) {
1570
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1571
- output.printSuccess(`Results written to ${outputFile}`);
1572
- }
1573
- else {
1574
- output.printJson(jsonOutput);
1575
- }
1576
- return { success: true, data: jsonOutput };
1577
- }
1578
- if (format === 'dot') {
1579
- const dotOutput = analyzer.exportToDot(result, {
1580
- includeLabels: true,
1581
- colorByCommunity: true,
1582
- highlightCycles: true,
1583
- });
1584
- if (outputFile) {
1585
- await writeFile(outputFile, dotOutput);
1586
- output.printSuccess(`DOT graph written to ${outputFile}`);
1587
- output.writeln(output.dim('Visualize with: dot -Tpng -o modules.png ' + outputFile));
1588
- }
1589
- else {
1590
- output.writeln(dotOutput);
1591
- }
1592
- return { success: true };
1593
- }
1594
- // Text format (default)
1595
- output.printBox([
1596
- `Files analyzed: ${result.statistics.nodeCount}`,
1597
- `Dependencies: ${result.statistics.edgeCount}`,
1598
- `Communities found: ${result.communities?.length || 0}`,
1599
- `Showing: ${communities.length} (min size: ${minSize})`,
1600
- ].join('\n'), 'Module Detection Results');
1601
- if (communities.length > 0) {
1602
- output.writeln();
1603
- output.writeln(output.bold('Detected Communities'));
1604
- output.writeln();
1605
- for (const community of communities.slice(0, 10)) {
1606
- const cohesionIndicator = community.cohesion > 0.5 ? output.success('High') :
1607
- community.cohesion > 0.2 ? output.warning('Medium') : output.dim('Low');
1608
- output.writeln(output.bold(`Community ${community.id}: ${community.suggestedName || 'unnamed'}`));
1609
- output.writeln(` ${output.dim('Cohesion:')} ${cohesionIndicator} (${(community.cohesion * 100).toFixed(1)}%)`);
1610
- output.writeln(` ${output.dim('Central node:')} ${community.centralNode || 'none'}`);
1611
- output.writeln(` ${output.dim('Members:')} ${community.members.length} files`);
1612
- const displayMembers = community.members.slice(0, 5);
1613
- for (const member of displayMembers) {
1614
- output.writeln(` - ${member}`);
1615
- }
1616
- if (community.members.length > 5) {
1617
- output.writeln(output.dim(` ... and ${community.members.length - 5} more`));
1618
- }
1619
- output.writeln();
1620
- }
1621
- if (communities.length > 10) {
1622
- output.writeln(output.dim(`... and ${communities.length - 10} more communities`));
1623
- }
1624
- }
1625
- if (outputFile) {
1626
- await writeFile(outputFile, JSON.stringify(result, null, 2));
1627
- output.printSuccess(`Full results written to ${outputFile}`);
1628
- }
1629
- return { success: true, data: result };
1630
- }
1631
- catch (error) {
1632
- spinner.stop();
1633
- const message = error instanceof Error ? error.message : String(error);
1634
- output.printError(`Analysis failed: ${message}`);
1635
- return { success: false, exitCode: 1 };
1636
- }
1637
- },
1638
- };
1639
- /**
1640
- * Build and export dependency graph
1641
- */
1642
- const dependenciesCommand = {
1643
- name: 'dependencies',
1644
- aliases: ['graph'],
1645
- description: 'Build and export full dependency graph',
1646
- options: [
1647
- {
1648
- name: 'output',
1649
- short: 'o',
1650
- description: 'Output file path',
1651
- type: 'string',
1652
- },
1653
- {
1654
- name: 'format',
1655
- short: 'f',
1656
- description: 'Output format (text, json, dot)',
1657
- type: 'string',
1658
- default: 'text',
1659
- choices: ['text', 'json', 'dot'],
1660
- },
1661
- {
1662
- name: 'include',
1663
- short: 'i',
1664
- description: 'File extensions to include (comma-separated)',
1665
- type: 'string',
1666
- default: '.ts,.tsx,.js,.jsx,.mjs,.cjs',
1667
- },
1668
- {
1669
- name: 'exclude',
1670
- short: 'e',
1671
- description: 'Patterns to exclude (comma-separated)',
1672
- type: 'string',
1673
- default: 'node_modules,dist,build,.git',
1674
- },
1675
- {
1676
- name: 'depth',
1677
- short: 'd',
1678
- description: 'Maximum directory depth',
1679
- type: 'number',
1680
- default: 10,
1681
- },
1682
- ],
1683
- examples: [
1684
- { command: 'claude-flow analyze dependencies src/', description: 'Build dependency graph' },
1685
- { command: 'claude-flow analyze dependencies -f dot -o deps.dot src/', description: 'Export to DOT' },
1686
- { command: 'claude-flow analyze dependencies -i .ts,.tsx src/', description: 'Only TypeScript files' },
1687
- ],
1688
- action: async (ctx) => {
1689
- const targetDir = ctx.args[0] || ctx.cwd;
1690
- const outputFile = ctx.flags.output;
1691
- const format = ctx.flags.format || 'text';
1692
- const include = (ctx.flags.include || '.ts,.tsx,.js,.jsx,.mjs,.cjs').split(',');
1693
- const exclude = (ctx.flags.exclude || 'node_modules,dist,build,.git').split(',');
1694
- const maxDepth = ctx.flags.depth || 10;
1695
- output.printInfo(`Building dependency graph for: ${output.highlight(targetDir)}`);
1696
- output.writeln();
1697
- const spinner = output.createSpinner({ text: 'Scanning files...', spinner: 'dots' });
1698
- spinner.start();
1699
- try {
1700
- const analyzer = await getGraphAnalyzer();
1701
- if (!analyzer) {
1702
- spinner.stop();
1703
- output.printError('Graph analyzer module not available');
1704
- return { success: false, exitCode: 1 };
1705
- }
1706
- const graph = await analyzer.buildDependencyGraph(resolve(targetDir), {
1707
- include,
1708
- exclude,
1709
- maxDepth,
1710
- });
1711
- spinner.stop();
1712
- // Detect circular dependencies
1713
- const circularDeps = analyzer.detectCircularDependencies(graph);
1714
- // Handle different output formats
1715
- if (format === 'json') {
1716
- const jsonOutput = {
1717
- nodes: Array.from(graph.nodes.values()),
1718
- edges: graph.edges,
1719
- metadata: graph.metadata,
1720
- circularDependencies: circularDeps,
1721
- };
1722
- if (outputFile) {
1723
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1724
- output.printSuccess(`Graph written to ${outputFile}`);
1725
- }
1726
- else {
1727
- output.printJson(jsonOutput);
1728
- }
1729
- return { success: true, data: jsonOutput };
1730
- }
1731
- if (format === 'dot') {
1732
- const result = { graph, circularDependencies: circularDeps, statistics: {
1733
- nodeCount: graph.nodes.size,
1734
- edgeCount: graph.edges.length,
1735
- avgDegree: 0,
1736
- maxDegree: 0,
1737
- density: 0,
1738
- componentCount: 0,
1739
- } };
1740
- const dotOutput = analyzer.exportToDot(result, {
1741
- includeLabels: true,
1742
- highlightCycles: true,
1743
- });
1744
- if (outputFile) {
1745
- await writeFile(outputFile, dotOutput);
1746
- output.printSuccess(`DOT graph written to ${outputFile}`);
1747
- output.writeln(output.dim('Visualize with: dot -Tpng -o deps.png ' + outputFile));
1748
- }
1749
- else {
1750
- output.writeln(dotOutput);
1751
- }
1752
- return { success: true };
1753
- }
1754
- // Text format (default)
1755
- output.printBox([
1756
- `Files: ${graph.metadata.totalFiles}`,
1757
- `Dependencies: ${graph.metadata.totalEdges}`,
1758
- `Build time: ${graph.metadata.buildTime}ms`,
1759
- `Root: ${graph.metadata.rootDir}`,
1760
- ].join('\n'), 'Dependency Graph');
1761
- // Show top files by imports
1762
- output.writeln();
1763
- output.writeln(output.bold('Most Connected Files'));
1764
- output.writeln();
1765
- const nodesByDegree = Array.from(graph.nodes.values())
1766
- .map(n => ({
1767
- ...n,
1768
- degree: graph.edges.filter(e => e.source === n.id || e.target === n.id).length,
1769
- }))
1770
- .sort((a, b) => b.degree - a.degree)
1771
- .slice(0, 10);
1772
- output.printTable({
1773
- columns: [
1774
- { key: 'path', header: 'File', width: 50 },
1775
- { key: 'degree', header: 'Connections', width: 12, align: 'right' },
1776
- { key: 'complexity', header: 'Complexity', width: 12, align: 'right' },
1777
- ],
1778
- data: nodesByDegree.map(n => ({
1779
- path: n.path.length > 48 ? '...' + n.path.slice(-45) : n.path,
1780
- degree: n.degree,
1781
- complexity: n.complexity || 0,
1782
- })),
1783
- });
1784
- // Show circular dependencies
1785
- if (circularDeps.length > 0) {
1786
- output.writeln();
1787
- output.writeln(output.bold(output.warning(`Circular Dependencies: ${circularDeps.length}`)));
1788
- output.writeln();
1789
- for (const cycle of circularDeps.slice(0, 3)) {
1790
- output.writeln(` ${cycle.cycle.join(' -> ')}`);
1791
- }
1792
- if (circularDeps.length > 3) {
1793
- output.writeln(output.dim(` ... and ${circularDeps.length - 3} more`));
1794
- }
1795
- }
1796
- if (outputFile) {
1797
- const fullOutput = {
1798
- nodes: Array.from(graph.nodes.values()),
1799
- edges: graph.edges,
1800
- metadata: graph.metadata,
1801
- circularDependencies: circularDeps,
1802
- };
1803
- await writeFile(outputFile, JSON.stringify(fullOutput, null, 2));
1804
- output.printSuccess(`Full results written to ${outputFile}`);
1805
- }
1806
- return { success: true };
1807
- }
1808
- catch (error) {
1809
- spinner.stop();
1810
- const message = error instanceof Error ? error.message : String(error);
1811
- output.printError(`Analysis failed: ${message}`);
1812
- return { success: false, exitCode: 1 };
1813
- }
1814
- },
1815
- };
1816
- /**
1817
- * Detect circular dependencies
1818
- */
1819
- const circularCommand = {
1820
- name: 'circular',
1821
- aliases: ['cycles'],
1822
- description: 'Detect circular dependencies in codebase',
1823
- options: [
1824
- {
1825
- name: 'output',
1826
- short: 'o',
1827
- description: 'Output file path',
1828
- type: 'string',
1829
- },
1830
- {
1831
- name: 'format',
1832
- short: 'f',
1833
- description: 'Output format (text, json)',
1834
- type: 'string',
1835
- default: 'text',
1836
- choices: ['text', 'json'],
1837
- },
1838
- {
1839
- name: 'severity',
1840
- short: 's',
1841
- description: 'Minimum severity to show (low, medium, high)',
1842
- type: 'string',
1843
- default: 'low',
1844
- choices: ['low', 'medium', 'high'],
1845
- },
1846
- ],
1847
- examples: [
1848
- { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
1849
- { command: 'claude-flow analyze circular -s high src/', description: 'Only high severity cycles' },
1850
- ],
1851
- action: async (ctx) => {
1852
- const targetDir = ctx.args[0] || ctx.cwd;
1853
- const outputFile = ctx.flags.output;
1854
- const format = ctx.flags.format || 'text';
1855
- const minSeverity = ctx.flags.severity || 'low';
1856
- output.printInfo(`Detecting circular dependencies in: ${output.highlight(targetDir)}`);
1857
- output.writeln();
1858
- const spinner = output.createSpinner({ text: 'Analyzing dependencies...', spinner: 'dots' });
1859
- spinner.start();
1860
- try {
1861
- const analyzer = await getGraphAnalyzer();
1862
- if (!analyzer) {
1863
- spinner.stop();
1864
- output.printError('Graph analyzer module not available');
1865
- return { success: false, exitCode: 1 };
1866
- }
1867
- const graph = await analyzer.buildDependencyGraph(resolve(targetDir));
1868
- const cycles = analyzer.detectCircularDependencies(graph);
1869
- spinner.stop();
1870
- // Filter by severity
1871
- const severityOrder = { low: 0, medium: 1, high: 2 };
1872
- const minLevel = severityOrder[minSeverity] || 0;
1873
- const filtered = cycles.filter(c => severityOrder[c.severity] >= minLevel);
1874
- if (format === 'json') {
1875
- const jsonOutput = { cycles: filtered, total: cycles.length, filtered: filtered.length };
1876
- if (outputFile) {
1877
- await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
1878
- output.printSuccess(`Results written to ${outputFile}`);
1879
- }
1880
- else {
1881
- output.printJson(jsonOutput);
1882
- }
1883
- return { success: true, data: jsonOutput };
1884
- }
1885
- // Text format
1886
- if (filtered.length === 0) {
1887
- output.printSuccess('No circular dependencies found!');
1888
- return { success: true };
1889
- }
1890
- output.printBox([
1891
- `Total cycles: ${cycles.length}`,
1892
- `Shown (${minSeverity}+): ${filtered.length}`,
1893
- `High severity: ${cycles.filter(c => c.severity === 'high').length}`,
1894
- `Medium severity: ${cycles.filter(c => c.severity === 'medium').length}`,
1895
- `Low severity: ${cycles.filter(c => c.severity === 'low').length}`,
1896
- ].join('\n'), 'Circular Dependencies');
1897
- output.writeln();
1898
- // Group by severity
1899
- const grouped = {
1900
- high: filtered.filter(c => c.severity === 'high'),
1901
- medium: filtered.filter(c => c.severity === 'medium'),
1902
- low: filtered.filter(c => c.severity === 'low'),
1903
- };
1904
- for (const [severity, items] of Object.entries(grouped)) {
1905
- if (items.length === 0)
1906
- continue;
1907
- const color = severity === 'high' ? output.error : severity === 'medium' ? output.warning : output.dim;
1908
- output.writeln(color(output.bold(`${severity.toUpperCase()} SEVERITY (${items.length})`)));
1909
- output.writeln();
1910
- for (const cycle of items.slice(0, 5)) {
1911
- output.writeln(` ${cycle.cycle.join(' -> ')}`);
1912
- output.writeln(output.dim(` Fix: ${cycle.suggestion}`));
1913
- output.writeln();
1914
- }
1915
- if (items.length > 5) {
1916
- output.writeln(output.dim(` ... and ${items.length - 5} more ${severity} cycles`));
1917
- output.writeln();
1918
- }
1919
- }
1920
- if (outputFile) {
1921
- await writeFile(outputFile, JSON.stringify({ cycles: filtered }, null, 2));
1922
- output.printSuccess(`Results written to ${outputFile}`);
1923
- }
1924
- return { success: true, data: { cycles: filtered } };
1925
- }
1926
- catch (error) {
1927
- spinner.stop();
1928
- const message = error instanceof Error ? error.message : String(error);
1929
- output.printError(`Analysis failed: ${message}`);
1930
- return { success: false, exitCode: 1 };
1931
- }
1932
- },
1933
- };
1934
- // Helper functions
1935
- function getRiskDisplay(risk) {
1936
- switch (risk) {
1937
- case 'critical':
1938
- return output.color(output.bold('CRITICAL'), 'bgRed', 'white');
1939
- case 'high-risk':
1940
- return output.error('HIGH');
1941
- case 'medium-risk':
1942
- return output.warning('MEDIUM');
1943
- case 'low-risk':
1944
- return output.success('LOW');
1945
- default:
1946
- return risk;
1947
- }
1948
- }
1949
- function getStatusDisplay(status) {
1950
- switch (status) {
1951
- case 'added':
1952
- return output.success('A');
1953
- case 'modified':
1954
- return output.warning('M');
1955
- case 'deleted':
1956
- return output.error('D');
1957
- case 'renamed':
1958
- return output.info('R');
1959
- default:
1960
- return status;
1961
- }
1962
- }
1963
- // Main analyze command
1964
- export const analyzeCommand = {
1965
- name: 'analyze',
1966
- description: 'Code analysis, diff classification, graph boundaries, and change risk assessment',
1967
- aliases: ['an'],
1968
- subcommands: [
1969
- diffCommand,
1970
- codeCommand,
1971
- depsCommand,
1972
- astCommand,
1973
- complexityAstCommand,
1974
- symbolsCommand,
1975
- importsCommand,
1976
- boundariesCommand,
1977
- modulesCommand,
1978
- dependenciesCommand,
1979
- circularCommand,
1980
- ],
1981
- options: [
1982
- {
1983
- name: 'format',
1984
- short: 'f',
1985
- description: 'Output format: text, json, table',
1986
- type: 'string',
1987
- default: 'text',
1988
- },
1989
- ],
1990
- examples: [
1991
- { command: 'claude-flow analyze ast src/', description: 'Analyze code with AST parsing' },
1992
- { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Find high-complexity files' },
1993
- { command: 'claude-flow analyze symbols src/ --type function', description: 'Extract all functions' },
1994
- { command: 'claude-flow analyze imports src/ --external', description: 'List npm dependencies' },
1995
- { command: 'claude-flow analyze diff --risk', description: 'Analyze diff with risk assessment' },
1996
- { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries using MinCut' },
1997
- { command: 'claude-flow analyze modules src/', description: 'Detect module communities with Louvain' },
1998
- { command: 'claude-flow analyze dependencies src/ --format dot', description: 'Export dependency graph as DOT' },
1999
- { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
2000
- { command: 'claude-flow analyze deps --security', description: 'Check dependency vulnerabilities' },
2001
- ],
2002
- action: async (ctx) => {
2003
- // If no subcommand, show help
2004
- output.writeln();
2005
- output.writeln(output.bold('Analyze Commands'));
2006
- output.writeln(output.dim('-'.repeat(50)));
2007
- output.writeln();
2008
- output.writeln(output.bold('Available subcommands:'));
2009
- output.writeln();
2010
- output.writeln(` ${output.highlight('diff')} Analyze git diff for change risk and classification`);
2011
- output.writeln(` ${output.highlight('code')} Static code analysis and quality assessment`);
2012
- output.writeln(` ${output.highlight('deps')} Analyze project dependencies`);
2013
- output.writeln(` ${output.highlight('ast')} AST analysis with symbol extraction and complexity`);
2014
- output.writeln(` ${output.highlight('complexity')} Analyze cyclomatic and cognitive complexity`);
2015
- output.writeln(` ${output.highlight('symbols')} Extract functions, classes, and types`);
2016
- output.writeln(` ${output.highlight('imports')} Analyze import dependencies`);
2017
- output.writeln(` ${output.highlight('boundaries')} Find code boundaries using MinCut algorithm`);
2018
- output.writeln(` ${output.highlight('modules')} Detect module communities using Louvain algorithm`);
2019
- output.writeln(` ${output.highlight('dependencies')} Build and export full dependency graph`);
2020
- output.writeln(` ${output.highlight('circular')} Detect circular dependencies in codebase`);
2021
- output.writeln();
2022
- output.writeln(output.bold('AST Analysis Examples:'));
2023
- output.writeln();
2024
- output.writeln(` ${output.dim('claude-flow analyze ast src/')} # Full AST analysis`);
2025
- output.writeln(` ${output.dim('claude-flow analyze ast src/index.ts -c')} # Include complexity`);
2026
- output.writeln(` ${output.dim('claude-flow analyze complexity src/ -t 15')} # Flag high complexity`);
2027
- output.writeln(` ${output.dim('claude-flow analyze symbols src/ --type fn')} # Extract functions`);
2028
- output.writeln(` ${output.dim('claude-flow analyze imports src/ --external')} # Only npm imports`);
2029
- output.writeln();
2030
- output.writeln(output.bold('Graph Analysis Examples:'));
2031
- output.writeln();
2032
- output.writeln(` ${output.dim('claude-flow analyze boundaries src/')} # Find natural code boundaries`);
2033
- output.writeln(` ${output.dim('claude-flow analyze modules src/')} # Detect module communities`);
2034
- output.writeln(` ${output.dim('claude-flow analyze dependencies -f dot src/')} # Export to DOT format`);
2035
- output.writeln(` ${output.dim('claude-flow analyze circular src/')} # Find circular deps`);
2036
- output.writeln();
2037
- output.writeln(output.bold('Diff Analysis Examples:'));
2038
- output.writeln();
2039
- output.writeln(` ${output.dim('claude-flow analyze diff --risk')} # Risk assessment`);
2040
- output.writeln(` ${output.dim('claude-flow analyze diff HEAD~1 --classify')} # Classify changes`);
2041
- output.writeln(` ${output.dim('claude-flow analyze diff main..feature')} # Compare branches`);
2042
- output.writeln();
2043
- return { success: true };
2044
- },
2045
- };
2046
- export default analyzeCommand;
2047
- //# sourceMappingURL=analyze.js.map