claude-flow 3.28.0 → 3.30.0

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 (690) hide show
  1. package/.claude/agents/MIGRATION_SUMMARY.md +221 -221
  2. package/.claude/agents/analysis/analyze-code-quality.md +57 -57
  3. package/.claude/agents/analysis/code-analyzer.md +188 -188
  4. package/.claude/agents/analysis/code-review/analyze-code-quality.md +57 -57
  5. package/.claude/agents/architecture/system-design/arch-system-design.md +35 -35
  6. package/.claude/agents/base-template-generator.md +41 -41
  7. package/.claude/agents/consensus/byzantine-coordinator.md +42 -42
  8. package/.claude/agents/consensus/crdt-synchronizer.md +976 -976
  9. package/.claude/agents/consensus/gossip-coordinator.md +42 -42
  10. package/.claude/agents/consensus/performance-benchmarker.md +830 -830
  11. package/.claude/agents/consensus/quorum-manager.md +802 -802
  12. package/.claude/agents/consensus/raft-manager.md +42 -42
  13. package/.claude/agents/consensus/security-manager.md +601 -601
  14. package/.claude/agents/core/coder.md +254 -254
  15. package/.claude/agents/core/planner.md +151 -151
  16. package/.claude/agents/core/researcher.md +173 -173
  17. package/.claude/agents/core/reviewer.md +308 -308
  18. package/.claude/agents/core/tester.md +299 -299
  19. package/.claude/agents/custom/test-long-runner.md +43 -43
  20. package/.claude/agents/data/ml/data-ml-model.md +75 -75
  21. package/.claude/agents/database-specialist.md +9 -9
  22. package/.claude/agents/development/backend/dev-backend-api.md +28 -28
  23. package/.claude/agents/development/dev-backend-api.md +177 -177
  24. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +51 -51
  25. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +62 -62
  26. package/.claude/agents/dual-mode/codex-coordinator.md +206 -206
  27. package/.claude/agents/dual-mode/codex-worker.md +190 -190
  28. package/.claude/agents/dual-mode/dual-orchestrator.md +253 -253
  29. package/.claude/agents/flow-nexus/app-store.md +87 -87
  30. package/.claude/agents/flow-nexus/authentication.md +68 -68
  31. package/.claude/agents/flow-nexus/challenges.md +80 -80
  32. package/.claude/agents/flow-nexus/neural-network.md +87 -87
  33. package/.claude/agents/flow-nexus/payments.md +82 -82
  34. package/.claude/agents/flow-nexus/sandbox.md +75 -75
  35. package/.claude/agents/flow-nexus/swarm.md +75 -75
  36. package/.claude/agents/flow-nexus/user-tools.md +95 -95
  37. package/.claude/agents/flow-nexus/workflow.md +83 -83
  38. package/.claude/agents/github/code-review-swarm.md +520 -520
  39. package/.claude/agents/github/github-modes.md +153 -153
  40. package/.claude/agents/github/issue-tracker.md +298 -298
  41. package/.claude/agents/github/multi-repo-swarm.md +524 -524
  42. package/.claude/agents/github/pr-manager.md +162 -162
  43. package/.claude/agents/github/project-board-sync.md +477 -477
  44. package/.claude/agents/github/release-manager.md +337 -337
  45. package/.claude/agents/github/release-swarm.md +550 -550
  46. package/.claude/agents/github/repo-architect.md +364 -364
  47. package/.claude/agents/github/swarm-issue.md +550 -550
  48. package/.claude/agents/github/swarm-pr.md +401 -401
  49. package/.claude/agents/github/sync-coordinator.md +424 -424
  50. package/.claude/agents/github/workflow-automation.md +604 -604
  51. package/.claude/agents/goal/agent.md +816 -816
  52. package/.claude/agents/goal/code-goal-planner.md +444 -444
  53. package/.claude/agents/goal/goal-planner.md +167 -167
  54. package/.claude/agents/hive-mind/collective-intelligence-coordinator.md +128 -128
  55. package/.claude/agents/hive-mind/queen-coordinator.md +201 -201
  56. package/.claude/agents/hive-mind/scout-explorer.md +240 -240
  57. package/.claude/agents/hive-mind/swarm-memory-manager.md +191 -191
  58. package/.claude/agents/hive-mind/worker-specialist.md +215 -215
  59. package/.claude/agents/neural/safla-neural.md +73 -73
  60. package/.claude/agents/optimization/benchmark-suite.md +662 -662
  61. package/.claude/agents/optimization/load-balancer.md +428 -428
  62. package/.claude/agents/optimization/performance-monitor.md +669 -669
  63. package/.claude/agents/optimization/resource-allocator.md +671 -671
  64. package/.claude/agents/optimization/topology-optimizer.md +805 -805
  65. package/.claude/agents/payments/agentic-payments.md +126 -126
  66. package/.claude/agents/project-coordinator.md +8 -8
  67. package/.claude/agents/python-specialist.md +9 -9
  68. package/.claude/agents/reasoning/agent.md +816 -816
  69. package/.claude/agents/reasoning/goal-planner.md +72 -72
  70. package/.claude/agents/security-auditor.md +9 -9
  71. package/.claude/agents/sona/sona-learning-optimizer.md +65 -65
  72. package/.claude/agents/sparc/architecture.md +452 -452
  73. package/.claude/agents/sparc/pseudocode.md +298 -298
  74. package/.claude/agents/sparc/refinement.md +503 -503
  75. package/.claude/agents/sparc/specification.md +257 -257
  76. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +87 -87
  77. package/.claude/agents/sublinear/consensus-coordinator.md +337 -337
  78. package/.claude/agents/sublinear/matrix-optimizer.md +184 -184
  79. package/.claude/agents/sublinear/pagerank-analyzer.md +298 -298
  80. package/.claude/agents/sublinear/performance-optimizer.md +367 -367
  81. package/.claude/agents/sublinear/trading-predictor.md +245 -245
  82. package/.claude/agents/swarm/adaptive-coordinator.md +363 -363
  83. package/.claude/agents/swarm/hierarchical-coordinator.md +299 -299
  84. package/.claude/agents/swarm/mesh-coordinator.md +362 -362
  85. package/.claude/agents/templates/automation-smart-agent.md +184 -184
  86. package/.claude/agents/templates/coordinator-swarm-init.md +82 -82
  87. package/.claude/agents/templates/github-pr-manager.md +154 -154
  88. package/.claude/agents/templates/implementer-sparc-coder.md +242 -242
  89. package/.claude/agents/templates/memory-coordinator.md +162 -162
  90. package/.claude/agents/templates/migration-plan.md +723 -723
  91. package/.claude/agents/templates/orchestrator-task.md +119 -119
  92. package/.claude/agents/templates/performance-analyzer.md +178 -178
  93. package/.claude/agents/templates/sparc-coordinator.md +162 -162
  94. package/.claude/agents/testing/production-validator.md +372 -372
  95. package/.claude/agents/testing/tdd-london-swarm.md +221 -221
  96. package/.claude/agents/testing/unit/tdd-london-swarm.md +221 -221
  97. package/.claude/agents/testing/validation/production-validator.md +372 -372
  98. package/.claude/agents/typescript-specialist.md +9 -9
  99. package/.claude/agents/v3/database-specialist.md +9 -9
  100. package/.claude/agents/v3/project-coordinator.md +8 -8
  101. package/.claude/agents/v3/python-specialist.md +9 -9
  102. package/.claude/agents/v3/test-architect.md +9 -9
  103. package/.claude/agents/v3/typescript-specialist.md +9 -9
  104. package/.claude/agents/v3/v3-integration-architect.md +311 -311
  105. package/.claude/agents/v3/v3-memory-specialist.md +280 -280
  106. package/.claude/agents/v3/v3-performance-engineer.md +362 -362
  107. package/.claude/agents/v3/v3-queen-coordinator.md +62 -62
  108. package/.claude/agents/v3/v3-security-architect.md +139 -139
  109. package/.claude/checkpoints/1767754460.json +8 -8
  110. package/.claude/commands/agents/README.md +10 -10
  111. package/.claude/commands/agents/agent-capabilities.md +21 -21
  112. package/.claude/commands/agents/agent-coordination.md +28 -28
  113. package/.claude/commands/agents/agent-spawning.md +28 -28
  114. package/.claude/commands/agents/agent-types.md +26 -26
  115. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +53 -53
  116. package/.claude/commands/analysis/README.md +9 -9
  117. package/.claude/commands/analysis/bottleneck-detect.md +162 -162
  118. package/.claude/commands/analysis/performance-bottlenecks.md +58 -58
  119. package/.claude/commands/analysis/performance-report.md +25 -25
  120. package/.claude/commands/analysis/token-efficiency.md +44 -44
  121. package/.claude/commands/analysis/token-usage.md +25 -25
  122. package/.claude/commands/automation/README.md +9 -9
  123. package/.claude/commands/automation/auto-agent.md +122 -122
  124. package/.claude/commands/automation/self-healing.md +105 -105
  125. package/.claude/commands/automation/session-memory.md +89 -89
  126. package/.claude/commands/automation/smart-agents.md +72 -72
  127. package/.claude/commands/automation/smart-spawn.md +25 -25
  128. package/.claude/commands/automation/workflow-select.md +25 -25
  129. package/.claude/commands/claude-flow-help.md +103 -103
  130. package/.claude/commands/claude-flow-memory.md +107 -107
  131. package/.claude/commands/claude-flow-swarm.md +205 -205
  132. package/.claude/commands/coordination/README.md +9 -9
  133. package/.claude/commands/coordination/agent-spawn.md +25 -25
  134. package/.claude/commands/coordination/init.md +44 -44
  135. package/.claude/commands/coordination/orchestrate.md +43 -43
  136. package/.claude/commands/coordination/spawn.md +45 -45
  137. package/.claude/commands/coordination/swarm-init.md +85 -85
  138. package/.claude/commands/coordination/task-orchestrate.md +25 -25
  139. package/.claude/commands/flow-nexus/app-store.md +123 -123
  140. package/.claude/commands/flow-nexus/challenges.md +119 -119
  141. package/.claude/commands/flow-nexus/login-registration.md +64 -64
  142. package/.claude/commands/flow-nexus/neural-network.md +133 -133
  143. package/.claude/commands/flow-nexus/payments.md +115 -115
  144. package/.claude/commands/flow-nexus/sandbox.md +82 -82
  145. package/.claude/commands/flow-nexus/swarm.md +86 -86
  146. package/.claude/commands/flow-nexus/user-tools.md +151 -151
  147. package/.claude/commands/flow-nexus/workflow.md +114 -114
  148. package/.claude/commands/github/README.md +11 -11
  149. package/.claude/commands/github/code-review-swarm.md +513 -513
  150. package/.claude/commands/github/code-review.md +25 -25
  151. package/.claude/commands/github/github-modes.md +146 -146
  152. package/.claude/commands/github/github-swarm.md +121 -121
  153. package/.claude/commands/github/issue-tracker.md +291 -291
  154. package/.claude/commands/github/issue-triage.md +25 -25
  155. package/.claude/commands/github/multi-repo-swarm.md +518 -518
  156. package/.claude/commands/github/pr-enhance.md +26 -26
  157. package/.claude/commands/github/pr-manager.md +169 -169
  158. package/.claude/commands/github/project-board-sync.md +470 -470
  159. package/.claude/commands/github/release-manager.md +337 -337
  160. package/.claude/commands/github/release-swarm.md +543 -543
  161. package/.claude/commands/github/repo-analyze.md +25 -25
  162. package/.claude/commands/github/repo-architect.md +366 -366
  163. package/.claude/commands/github/swarm-issue.md +481 -481
  164. package/.claude/commands/github/swarm-pr.md +284 -284
  165. package/.claude/commands/github/sync-coordinator.md +300 -300
  166. package/.claude/commands/github/workflow-automation.md +441 -441
  167. package/.claude/commands/hive-mind/README.md +17 -17
  168. package/.claude/commands/hive-mind/hive-mind-consensus.md +8 -8
  169. package/.claude/commands/hive-mind/hive-mind-init.md +18 -18
  170. package/.claude/commands/hive-mind/hive-mind-memory.md +8 -8
  171. package/.claude/commands/hive-mind/hive-mind-metrics.md +8 -8
  172. package/.claude/commands/hive-mind/hive-mind-resume.md +8 -8
  173. package/.claude/commands/hive-mind/hive-mind-sessions.md +8 -8
  174. package/.claude/commands/hive-mind/hive-mind-spawn.md +21 -21
  175. package/.claude/commands/hive-mind/hive-mind-status.md +8 -8
  176. package/.claude/commands/hive-mind/hive-mind-stop.md +8 -8
  177. package/.claude/commands/hive-mind/hive-mind-wizard.md +8 -8
  178. package/.claude/commands/hive-mind/hive-mind.md +27 -27
  179. package/.claude/commands/hooks/README.md +11 -11
  180. package/.claude/commands/hooks/overview.md +57 -57
  181. package/.claude/commands/hooks/post-edit.md +117 -117
  182. package/.claude/commands/hooks/post-task.md +112 -112
  183. package/.claude/commands/hooks/pre-edit.md +113 -113
  184. package/.claude/commands/hooks/pre-task.md +111 -111
  185. package/.claude/commands/hooks/session-end.md +118 -118
  186. package/.claude/commands/hooks/setup.md +102 -102
  187. package/.claude/commands/memory/README.md +9 -9
  188. package/.claude/commands/memory/memory-persist.md +25 -25
  189. package/.claude/commands/memory/memory-search.md +25 -25
  190. package/.claude/commands/memory/memory-usage.md +25 -25
  191. package/.claude/commands/memory/neural.md +47 -47
  192. package/.claude/commands/monitoring/README.md +9 -9
  193. package/.claude/commands/monitoring/agent-metrics.md +25 -25
  194. package/.claude/commands/monitoring/agents.md +44 -44
  195. package/.claude/commands/monitoring/real-time-view.md +25 -25
  196. package/.claude/commands/monitoring/status.md +46 -46
  197. package/.claude/commands/monitoring/swarm-monitor.md +25 -25
  198. package/.claude/commands/optimization/README.md +9 -9
  199. package/.claude/commands/optimization/auto-topology.md +61 -61
  200. package/.claude/commands/optimization/cache-manage.md +25 -25
  201. package/.claude/commands/optimization/parallel-execute.md +25 -25
  202. package/.claude/commands/optimization/parallel-execution.md +49 -49
  203. package/.claude/commands/optimization/topology-optimize.md +25 -25
  204. package/.claude/commands/pair/README.md +260 -260
  205. package/.claude/commands/pair/commands.md +545 -545
  206. package/.claude/commands/pair/config.md +509 -509
  207. package/.claude/commands/pair/examples.md +511 -511
  208. package/.claude/commands/pair/modes.md +347 -347
  209. package/.claude/commands/pair/session.md +406 -406
  210. package/.claude/commands/pair/start.md +208 -208
  211. package/.claude/commands/sparc/analyzer.md +51 -51
  212. package/.claude/commands/sparc/architect.md +53 -53
  213. package/.claude/commands/sparc/ask.md +97 -97
  214. package/.claude/commands/sparc/batch-executor.md +54 -54
  215. package/.claude/commands/sparc/code.md +89 -89
  216. package/.claude/commands/sparc/coder.md +54 -54
  217. package/.claude/commands/sparc/debug.md +83 -83
  218. package/.claude/commands/sparc/debugger.md +54 -54
  219. package/.claude/commands/sparc/designer.md +53 -53
  220. package/.claude/commands/sparc/devops.md +109 -109
  221. package/.claude/commands/sparc/docs-writer.md +80 -80
  222. package/.claude/commands/sparc/documenter.md +54 -54
  223. package/.claude/commands/sparc/innovator.md +54 -54
  224. package/.claude/commands/sparc/integration.md +83 -83
  225. package/.claude/commands/sparc/mcp.md +117 -117
  226. package/.claude/commands/sparc/memory-manager.md +54 -54
  227. package/.claude/commands/sparc/optimizer.md +54 -54
  228. package/.claude/commands/sparc/orchestrator.md +131 -131
  229. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -83
  230. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -83
  231. package/.claude/commands/sparc/researcher.md +54 -54
  232. package/.claude/commands/sparc/reviewer.md +54 -54
  233. package/.claude/commands/sparc/security-review.md +80 -80
  234. package/.claude/commands/sparc/sparc-modes.md +174 -174
  235. package/.claude/commands/sparc/sparc.md +111 -111
  236. package/.claude/commands/sparc/spec-pseudocode.md +80 -80
  237. package/.claude/commands/sparc/supabase-admin.md +348 -348
  238. package/.claude/commands/sparc/swarm-coordinator.md +54 -54
  239. package/.claude/commands/sparc/tdd.md +54 -54
  240. package/.claude/commands/sparc/tester.md +54 -54
  241. package/.claude/commands/sparc/tutorial.md +79 -79
  242. package/.claude/commands/sparc/workflow-manager.md +54 -54
  243. package/.claude/commands/sparc.md +166 -166
  244. package/.claude/commands/stream-chain/pipeline.md +120 -120
  245. package/.claude/commands/stream-chain/run.md +69 -69
  246. package/.claude/commands/swarm/README.md +15 -15
  247. package/.claude/commands/swarm/analysis.md +95 -95
  248. package/.claude/commands/swarm/development.md +96 -96
  249. package/.claude/commands/swarm/examples.md +168 -168
  250. package/.claude/commands/swarm/maintenance.md +102 -102
  251. package/.claude/commands/swarm/optimization.md +117 -117
  252. package/.claude/commands/swarm/research.md +136 -136
  253. package/.claude/commands/swarm/swarm-analysis.md +8 -8
  254. package/.claude/commands/swarm/swarm-background.md +8 -8
  255. package/.claude/commands/swarm/swarm-init.md +19 -19
  256. package/.claude/commands/swarm/swarm-modes.md +8 -8
  257. package/.claude/commands/swarm/swarm-monitor.md +8 -8
  258. package/.claude/commands/swarm/swarm-spawn.md +19 -19
  259. package/.claude/commands/swarm/swarm-status.md +8 -8
  260. package/.claude/commands/swarm/swarm-strategies.md +8 -8
  261. package/.claude/commands/swarm/swarm.md +27 -27
  262. package/.claude/commands/swarm/testing.md +131 -131
  263. package/.claude/commands/training/README.md +9 -9
  264. package/.claude/commands/training/model-update.md +25 -25
  265. package/.claude/commands/training/neural-patterns.md +73 -73
  266. package/.claude/commands/training/neural-train.md +25 -25
  267. package/.claude/commands/training/pattern-learn.md +25 -25
  268. package/.claude/commands/training/specialization.md +62 -62
  269. package/.claude/commands/truth/start.md +142 -142
  270. package/.claude/commands/verify/check.md +49 -49
  271. package/.claude/commands/verify/start.md +127 -127
  272. package/.claude/commands/workflows/README.md +9 -9
  273. package/.claude/commands/workflows/development.md +77 -77
  274. package/.claude/commands/workflows/research.md +62 -62
  275. package/.claude/commands/workflows/workflow-create.md +25 -25
  276. package/.claude/commands/workflows/workflow-execute.md +25 -25
  277. package/.claude/commands/workflows/workflow-export.md +25 -25
  278. package/.claude/config/v3-dependency-optimization.json +265 -265
  279. package/.claude/config/v3-performance-targets.json +250 -250
  280. package/.claude/helpers/.LOCKED +2 -0
  281. package/.claude/helpers/.helpers-version +1 -1
  282. package/.claude/helpers/README.md +96 -96
  283. package/.claude/helpers/adr-compliance.sh +186 -186
  284. package/.claude/helpers/aggressive-microcompact.mjs +36 -36
  285. package/.claude/helpers/auto-commit.sh +178 -178
  286. package/.claude/helpers/auto-memory-hook.mjs +430 -430
  287. package/.claude/helpers/checkpoint-manager.sh +251 -251
  288. package/.claude/helpers/context-persistence-hook.mjs +2001 -2001
  289. package/.claude/helpers/daemon-manager.sh +252 -252
  290. package/.claude/helpers/ddd-tracker.sh +144 -144
  291. package/.claude/helpers/github-safe.js +156 -156
  292. package/.claude/helpers/github-setup.sh +45 -45
  293. package/.claude/helpers/guidance-hook.sh +13 -13
  294. package/.claude/helpers/guidance-hooks.sh +102 -102
  295. package/.claude/helpers/health-monitor.sh +108 -108
  296. package/.claude/helpers/helpers.manifest.json +6 -5
  297. package/.claude/helpers/hook-handler.cjs +564 -460
  298. package/.claude/helpers/intelligence.cjs +1058 -1058
  299. package/.claude/helpers/learning-hooks.sh +329 -329
  300. package/.claude/helpers/learning-optimizer.sh +127 -127
  301. package/.claude/helpers/learning-service.mjs +1144 -1144
  302. package/.claude/helpers/memory.cjs +84 -84
  303. package/.claude/helpers/metrics-db.mjs +503 -503
  304. package/.claude/helpers/patch-aggressive-prune.mjs +184 -184
  305. package/.claude/helpers/pattern-consolidator.sh +86 -86
  306. package/.claude/helpers/perf-worker.sh +160 -160
  307. package/.claude/helpers/quick-start.sh +19 -19
  308. package/.claude/helpers/router.cjs +62 -62
  309. package/.claude/helpers/security-scanner.sh +127 -127
  310. package/.claude/helpers/session.cjs +125 -125
  311. package/.claude/helpers/setup-mcp.sh +18 -18
  312. package/.claude/helpers/standard-checkpoint-hooks.sh +189 -189
  313. package/.claude/helpers/statusline.cjs +999 -925
  314. package/.claude/helpers/swarm-comms.sh +353 -353
  315. package/.claude/helpers/swarm-hooks.sh +761 -761
  316. package/.claude/helpers/swarm-monitor.sh +210 -210
  317. package/.claude/helpers/sync-v3-metrics.sh +245 -245
  318. package/.claude/helpers/update-v3-progress.sh +165 -165
  319. package/.claude/helpers/v3-quick-status.sh +57 -57
  320. package/.claude/helpers/v3.sh +110 -110
  321. package/.claude/helpers/validate-v3-config.sh +215 -215
  322. package/.claude/helpers/worker-manager.sh +170 -170
  323. package/.claude/mcp.json +12 -12
  324. package/.claude/proven-config.json +1 -1
  325. package/.claude/settings.json +285 -285
  326. package/.claude/settings.json.bak +526 -526
  327. package/.claude/skills/agentdb-advanced/SKILL.md +550 -550
  328. package/.claude/skills/agentdb-learning/SKILL.md +545 -545
  329. package/.claude/skills/agentdb-memory-patterns/SKILL.md +339 -339
  330. package/.claude/skills/agentdb-optimization/SKILL.md +509 -509
  331. package/.claude/skills/agentdb-vector-search/SKILL.md +339 -339
  332. package/.claude/skills/agentic-jujutsu/SKILL.md +645 -645
  333. package/.claude/skills/browser/SKILL.md +204 -204
  334. package/.claude/skills/dual-mode/README.md +71 -71
  335. package/.claude/skills/dual-mode/dual-collect.md +103 -103
  336. package/.claude/skills/dual-mode/dual-coordinate.md +85 -85
  337. package/.claude/skills/dual-mode/dual-spawn.md +81 -81
  338. package/.claude/skills/flow-nexus-neural/SKILL.md +727 -727
  339. package/.claude/skills/flow-nexus-platform/SKILL.md +1154 -1154
  340. package/.claude/skills/flow-nexus-swarm/SKILL.md +604 -604
  341. package/.claude/skills/github-code-review/SKILL.md +1125 -1125
  342. package/.claude/skills/github-multi-repo/SKILL.md +862 -862
  343. package/.claude/skills/github-project-management/SKILL.md +1262 -1262
  344. package/.claude/skills/github-release-management/SKILL.md +1064 -1064
  345. package/.claude/skills/github-workflow-automation/SKILL.md +1047 -1047
  346. package/.claude/skills/hive-mind-advanced/SKILL.md +709 -709
  347. package/.claude/skills/hooks-automation/SKILL.md +1201 -1201
  348. package/.claude/skills/pair-programming/SKILL.md +1202 -1202
  349. package/.claude/skills/performance-analysis/SKILL.md +560 -560
  350. package/.claude/skills/reasoningbank-agentdb/SKILL.md +446 -446
  351. package/.claude/skills/reasoningbank-intelligence/SKILL.md +201 -201
  352. package/.claude/skills/skill-builder/SKILL.md +910 -910
  353. package/.claude/skills/sparc-methodology/SKILL.md +1106 -1106
  354. package/.claude/skills/stream-chain/SKILL.md +560 -560
  355. package/.claude/skills/swarm-advanced/SKILL.md +970 -970
  356. package/.claude/skills/swarm-orchestration/SKILL.md +179 -179
  357. package/.claude/skills/v3-cli-modernization/SKILL.md +871 -871
  358. package/.claude/skills/v3-core-implementation/SKILL.md +796 -796
  359. package/.claude/skills/v3-ddd-architecture/SKILL.md +441 -441
  360. package/.claude/skills/v3-integration-deep/SKILL.md +240 -240
  361. package/.claude/skills/v3-mcp-optimization/SKILL.md +776 -776
  362. package/.claude/skills/v3-memory-unification/SKILL.md +173 -173
  363. package/.claude/skills/v3-performance-optimization/SKILL.md +389 -389
  364. package/.claude/skills/v3-security-overhaul/SKILL.md +81 -81
  365. package/.claude/skills/v3-swarm-coordination/SKILL.md +339 -339
  366. package/.claude/skills/verification-quality/SKILL.md +691 -691
  367. package/.claude/skills/worker-benchmarks/SKILL.md +129 -129
  368. package/.claude/skills/worker-integration/SKILL.md +147 -147
  369. package/.claude/statusline-command.sh +176 -176
  370. package/.claude/statusline.mjs +109 -109
  371. package/.claude/statusline.sh +431 -431
  372. package/.claude/workflows/full-system-test.js +65 -65
  373. package/.claude/workflows/intelligence-system-hardening.js +120 -120
  374. package/.claude/workflows/plugin-contract-audit.js +91 -91
  375. package/.claude-plugin/README.md +720 -720
  376. package/.claude-plugin/docs/INSTALLATION.md +261 -261
  377. package/.claude-plugin/docs/PLUGIN_SUMMARY.md +361 -361
  378. package/.claude-plugin/docs/QUICKSTART.md +361 -361
  379. package/.claude-plugin/docs/STRUCTURE.md +128 -128
  380. package/.claude-plugin/hooks/hooks.json +77 -77
  381. package/.claude-plugin/marketplace.json +185 -185
  382. package/.claude-plugin/plugin.json +71 -71
  383. package/.claude-plugin/scripts/install.sh +234 -234
  384. package/.claude-plugin/scripts/ruflo-hook.cjs +166 -166
  385. package/.claude-plugin/scripts/ruflo-hook.sh +37 -37
  386. package/.claude-plugin/scripts/uninstall.sh +36 -36
  387. package/.claude-plugin/scripts/verify.sh +108 -108
  388. package/LICENSE +21 -21
  389. package/README.md +419 -419
  390. package/bin/cli.js +11 -11
  391. package/bin/npx-repair.js +7 -7
  392. package/bin/npx-safe-launch.js +9 -9
  393. package/package.json +185 -185
  394. package/v3/@claude-flow/cli/README.md +419 -419
  395. package/v3/@claude-flow/cli/bin/cli.js +314 -314
  396. package/v3/@claude-flow/cli/bin/mcp-server.js +224 -224
  397. package/v3/@claude-flow/cli/bin/preinstall.cjs +2 -2
  398. package/v3/@claude-flow/cli/catalog-manifest.json +2 -2
  399. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +24 -24
  400. package/v3/@claude-flow/cli/dist/src/business-pods/bbs-budget-tracker.js +53 -53
  401. package/v3/@claude-flow/cli/dist/src/commands/announcements.d.ts +17 -0
  402. package/v3/@claude-flow/cli/dist/src/commands/announcements.js +0 -0
  403. package/v3/@claude-flow/cli/dist/src/commands/completions.js +409 -409
  404. package/v3/@claude-flow/cli/dist/src/commands/daemon.js +44 -44
  405. package/v3/@claude-flow/cli/dist/src/commands/embeddings.js +26 -26
  406. package/v3/@claude-flow/cli/dist/src/commands/funnel.d.ts +10 -5
  407. package/v3/@claude-flow/cli/dist/src/commands/funnel.js +206 -7
  408. package/v3/@claude-flow/cli/dist/src/commands/hive-mind.js +97 -97
  409. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +9 -9
  410. package/v3/@claude-flow/cli/dist/src/commands/index.js +4 -0
  411. package/v3/@claude-flow/cli/dist/src/commands/init.js +94 -38
  412. package/v3/@claude-flow/cli/dist/src/commands/memory.js +85 -1
  413. package/v3/@claude-flow/cli/dist/src/commands/ruvector/backup.js +23 -23
  414. package/v3/@claude-flow/cli/dist/src/commands/ruvector/benchmark.js +31 -31
  415. package/v3/@claude-flow/cli/dist/src/commands/ruvector/import.js +14 -14
  416. package/v3/@claude-flow/cli/dist/src/commands/ruvector/init.js +115 -115
  417. package/v3/@claude-flow/cli/dist/src/commands/ruvector/migrate.js +99 -99
  418. package/v3/@claude-flow/cli/dist/src/commands/ruvector/optimize.js +51 -51
  419. package/v3/@claude-flow/cli/dist/src/commands/ruvector/setup.js +624 -624
  420. package/v3/@claude-flow/cli/dist/src/commands/ruvector/status.js +38 -38
  421. package/v3/@claude-flow/cli/dist/src/commands/spinner.d.ts +16 -0
  422. package/v3/@claude-flow/cli/dist/src/commands/spinner.js +329 -0
  423. package/v3/@claude-flow/cli/dist/src/config/proven-config.js +2 -2
  424. package/v3/@claude-flow/cli/dist/src/funnel/consent.js +3 -0
  425. package/v3/@claude-flow/cli/dist/src/funnel/disclosure.d.ts +1 -0
  426. package/v3/@claude-flow/cli/dist/src/funnel/disclosure.js +12 -0
  427. package/v3/@claude-flow/cli/dist/src/funnel/index.d.ts +2 -1
  428. package/v3/@claude-flow/cli/dist/src/funnel/index.js +2 -1
  429. package/v3/@claude-flow/cli/dist/src/funnel/payout.d.ts +40 -0
  430. package/v3/@claude-flow/cli/dist/src/funnel/payout.js +60 -0
  431. package/v3/@claude-flow/cli/dist/src/funnel/types.d.ts +13 -1
  432. package/v3/@claude-flow/cli/dist/src/init/claudemd-generator.js +231 -231
  433. package/v3/@claude-flow/cli/dist/src/init/executor.js +453 -453
  434. package/v3/@claude-flow/cli/dist/src/init/helper-refresh.js +17 -0
  435. package/v3/@claude-flow/cli/dist/src/init/helper-signing.d.ts +8 -1
  436. package/v3/@claude-flow/cli/dist/src/init/helper-signing.js +9 -2
  437. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +751 -751
  438. package/v3/@claude-flow/cli/dist/src/init/statusline-generator.js +955 -949
  439. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +15 -15
  440. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-intent-tools.js +19 -19
  441. package/v3/@claude-flow/cli/dist/src/memory/graph-edge-writer.js +22 -22
  442. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +10 -0
  443. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +139 -88
  444. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +18 -0
  445. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +539 -407
  446. package/v3/@claude-flow/cli/dist/src/memory/rabitq-index.js +5 -5
  447. package/v3/@claude-flow/cli/dist/src/runtime/headless.js +28 -28
  448. package/v3/@claude-flow/cli/dist/src/ruvector/flash-attention.d.ts +195 -0
  449. package/v3/@claude-flow/cli/dist/src/ruvector/flash-attention.js +643 -0
  450. package/v3/@claude-flow/cli/dist/src/ruvector/moe-router.d.ts +206 -0
  451. package/v3/@claude-flow/cli/dist/src/ruvector/moe-router.js +626 -0
  452. package/v3/@claude-flow/cli/dist/src/services/distill-tuning.js +7 -7
  453. package/v3/@claude-flow/cli/dist/src/services/event-stream.d.ts +25 -0
  454. package/v3/@claude-flow/cli/dist/src/services/event-stream.js +27 -0
  455. package/v3/@claude-flow/cli/dist/src/services/headless-worker-executor.js +84 -84
  456. package/v3/@claude-flow/cli/dist/src/services/loop-worker-runner.d.ts +16 -0
  457. package/v3/@claude-flow/cli/dist/src/services/loop-worker-runner.js +34 -0
  458. package/v3/@claude-flow/cli/dist/src/services/memory-distillation.js +4 -4
  459. package/v3/@claude-flow/cli/dist/src/services/runtime-capabilities.d.ts +22 -0
  460. package/v3/@claude-flow/cli/dist/src/services/runtime-capabilities.js +45 -0
  461. package/v3/@claude-flow/cli/dist/src/transfer/deploy-seraphine.js +23 -23
  462. package/v3/@claude-flow/cli/package.json +134 -133
  463. package/v3/@claude-flow/guidance/README.md +1195 -1195
  464. package/v3/@claude-flow/guidance/dist/adversarial.d.ts +284 -0
  465. package/v3/@claude-flow/guidance/dist/adversarial.js +572 -0
  466. package/v3/@claude-flow/guidance/dist/analyzer.d.ts +530 -0
  467. package/v3/@claude-flow/guidance/dist/analyzer.js +2587 -0
  468. package/v3/@claude-flow/guidance/dist/artifacts.d.ts +283 -0
  469. package/v3/@claude-flow/guidance/dist/artifacts.js +356 -0
  470. package/v3/@claude-flow/guidance/dist/authority.d.ts +290 -0
  471. package/v3/@claude-flow/guidance/dist/authority.js +558 -0
  472. package/v3/@claude-flow/guidance/dist/capabilities.d.ts +209 -0
  473. package/v3/@claude-flow/guidance/dist/capabilities.js +485 -0
  474. package/v3/@claude-flow/guidance/dist/coherence.d.ts +233 -0
  475. package/v3/@claude-flow/guidance/dist/coherence.js +372 -0
  476. package/v3/@claude-flow/guidance/dist/compiler.d.ts +87 -0
  477. package/v3/@claude-flow/guidance/dist/compiler.js +410 -0
  478. package/v3/@claude-flow/guidance/dist/conformance-kit.d.ts +225 -0
  479. package/v3/@claude-flow/guidance/dist/conformance-kit.js +629 -0
  480. package/v3/@claude-flow/guidance/dist/continue-gate.d.ts +214 -0
  481. package/v3/@claude-flow/guidance/dist/continue-gate.js +353 -0
  482. package/v3/@claude-flow/guidance/dist/crypto-utils.d.ts +17 -0
  483. package/v3/@claude-flow/guidance/dist/crypto-utils.js +24 -0
  484. package/v3/@claude-flow/guidance/dist/evolution.d.ts +282 -0
  485. package/v3/@claude-flow/guidance/dist/evolution.js +500 -0
  486. package/v3/@claude-flow/guidance/dist/gates.d.ts +79 -0
  487. package/v3/@claude-flow/guidance/dist/gates.js +302 -0
  488. package/v3/@claude-flow/guidance/dist/gateway.d.ts +206 -0
  489. package/v3/@claude-flow/guidance/dist/gateway.js +452 -0
  490. package/v3/@claude-flow/guidance/dist/generators.d.ts +153 -0
  491. package/v3/@claude-flow/guidance/dist/generators.js +682 -0
  492. package/v3/@claude-flow/guidance/dist/headless.d.ts +177 -0
  493. package/v3/@claude-flow/guidance/dist/headless.js +342 -0
  494. package/v3/@claude-flow/guidance/dist/hooks.d.ts +109 -0
  495. package/v3/@claude-flow/guidance/dist/hooks.js +347 -0
  496. package/v3/@claude-flow/guidance/dist/index.d.ts +205 -0
  497. package/v3/@claude-flow/guidance/dist/index.js +321 -0
  498. package/v3/@claude-flow/guidance/dist/ledger.d.ts +162 -0
  499. package/v3/@claude-flow/guidance/dist/ledger.js +375 -0
  500. package/v3/@claude-flow/guidance/dist/manifest-validator.d.ts +289 -0
  501. package/v3/@claude-flow/guidance/dist/manifest-validator.js +838 -0
  502. package/v3/@claude-flow/guidance/dist/memory-gate.d.ts +222 -0
  503. package/v3/@claude-flow/guidance/dist/memory-gate.js +382 -0
  504. package/v3/@claude-flow/guidance/dist/meta-governance.d.ts +265 -0
  505. package/v3/@claude-flow/guidance/dist/meta-governance.js +348 -0
  506. package/v3/@claude-flow/guidance/dist/optimizer.d.ts +104 -0
  507. package/v3/@claude-flow/guidance/dist/optimizer.js +329 -0
  508. package/v3/@claude-flow/guidance/dist/persistence.d.ts +189 -0
  509. package/v3/@claude-flow/guidance/dist/persistence.js +464 -0
  510. package/v3/@claude-flow/guidance/dist/proof.d.ts +185 -0
  511. package/v3/@claude-flow/guidance/dist/proof.js +238 -0
  512. package/v3/@claude-flow/guidance/dist/retriever.d.ts +172 -0
  513. package/v3/@claude-flow/guidance/dist/retriever.js +596 -0
  514. package/v3/@claude-flow/guidance/dist/ruvbot-integration.d.ts +370 -0
  515. package/v3/@claude-flow/guidance/dist/ruvbot-integration.js +738 -0
  516. package/v3/@claude-flow/guidance/dist/temporal.d.ts +426 -0
  517. package/v3/@claude-flow/guidance/dist/temporal.js +658 -0
  518. package/v3/@claude-flow/guidance/dist/trust.d.ts +283 -0
  519. package/v3/@claude-flow/guidance/dist/trust.js +473 -0
  520. package/v3/@claude-flow/guidance/dist/truth-anchors.d.ts +276 -0
  521. package/v3/@claude-flow/guidance/dist/truth-anchors.js +488 -0
  522. package/v3/@claude-flow/guidance/dist/types.d.ts +378 -0
  523. package/v3/@claude-flow/guidance/dist/types.js +10 -0
  524. package/v3/@claude-flow/guidance/dist/uncertainty.d.ts +372 -0
  525. package/v3/@claude-flow/guidance/dist/uncertainty.js +619 -0
  526. package/v3/@claude-flow/guidance/dist/wasm-kernel.d.ts +48 -0
  527. package/v3/@claude-flow/guidance/dist/wasm-kernel.js +158 -0
  528. package/v3/@claude-flow/guidance/package.json +198 -198
  529. package/v3/@claude-flow/shared/README.md +323 -323
  530. package/v3/@claude-flow/shared/dist/core/config/defaults.d.ts +41 -0
  531. package/v3/@claude-flow/shared/dist/core/config/defaults.js +186 -0
  532. package/v3/@claude-flow/shared/dist/core/config/index.d.ts +8 -0
  533. package/v3/@claude-flow/shared/dist/core/config/index.js +12 -0
  534. package/v3/@claude-flow/shared/dist/core/config/loader.d.ts +45 -0
  535. package/v3/@claude-flow/shared/dist/core/config/loader.js +238 -0
  536. package/v3/@claude-flow/shared/dist/core/config/schema.d.ts +1728 -0
  537. package/v3/@claude-flow/shared/dist/core/config/schema.js +160 -0
  538. package/v3/@claude-flow/shared/dist/core/config/validator.d.ts +92 -0
  539. package/v3/@claude-flow/shared/dist/core/config/validator.js +147 -0
  540. package/v3/@claude-flow/shared/dist/core/event-bus.d.ts +31 -0
  541. package/v3/@claude-flow/shared/dist/core/event-bus.js +197 -0
  542. package/v3/@claude-flow/shared/dist/core/index.d.ts +15 -0
  543. package/v3/@claude-flow/shared/dist/core/index.js +19 -0
  544. package/v3/@claude-flow/shared/dist/core/interfaces/agent.interface.d.ts +200 -0
  545. package/v3/@claude-flow/shared/dist/core/interfaces/agent.interface.js +6 -0
  546. package/v3/@claude-flow/shared/dist/core/interfaces/coordinator.interface.d.ts +310 -0
  547. package/v3/@claude-flow/shared/dist/core/interfaces/coordinator.interface.js +7 -0
  548. package/v3/@claude-flow/shared/dist/core/interfaces/event.interface.d.ts +224 -0
  549. package/v3/@claude-flow/shared/dist/core/interfaces/event.interface.js +46 -0
  550. package/v3/@claude-flow/shared/dist/core/interfaces/index.d.ts +10 -0
  551. package/v3/@claude-flow/shared/dist/core/interfaces/index.js +15 -0
  552. package/v3/@claude-flow/shared/dist/core/interfaces/memory.interface.d.ts +298 -0
  553. package/v3/@claude-flow/shared/dist/core/interfaces/memory.interface.js +7 -0
  554. package/v3/@claude-flow/shared/dist/core/interfaces/task.interface.d.ts +185 -0
  555. package/v3/@claude-flow/shared/dist/core/interfaces/task.interface.js +6 -0
  556. package/v3/@claude-flow/shared/dist/core/orchestrator/event-coordinator.d.ts +35 -0
  557. package/v3/@claude-flow/shared/dist/core/orchestrator/event-coordinator.js +101 -0
  558. package/v3/@claude-flow/shared/dist/core/orchestrator/health-monitor.d.ts +60 -0
  559. package/v3/@claude-flow/shared/dist/core/orchestrator/health-monitor.js +166 -0
  560. package/v3/@claude-flow/shared/dist/core/orchestrator/index.d.ts +46 -0
  561. package/v3/@claude-flow/shared/dist/core/orchestrator/index.js +64 -0
  562. package/v3/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.d.ts +56 -0
  563. package/v3/@claude-flow/shared/dist/core/orchestrator/lifecycle-manager.js +195 -0
  564. package/v3/@claude-flow/shared/dist/core/orchestrator/session-manager.d.ts +83 -0
  565. package/v3/@claude-flow/shared/dist/core/orchestrator/session-manager.js +193 -0
  566. package/v3/@claude-flow/shared/dist/core/orchestrator/task-manager.d.ts +49 -0
  567. package/v3/@claude-flow/shared/dist/core/orchestrator/task-manager.js +253 -0
  568. package/v3/@claude-flow/shared/dist/events/domain-events.d.ts +282 -0
  569. package/v3/@claude-flow/shared/dist/events/domain-events.js +165 -0
  570. package/v3/@claude-flow/shared/dist/events/event-store.d.ts +126 -0
  571. package/v3/@claude-flow/shared/dist/events/event-store.js +427 -0
  572. package/v3/@claude-flow/shared/dist/events/event-store.test.d.ts +8 -0
  573. package/v3/@claude-flow/shared/dist/events/event-store.test.js +293 -0
  574. package/v3/@claude-flow/shared/dist/events/example-usage.d.ts +10 -0
  575. package/v3/@claude-flow/shared/dist/events/example-usage.js +193 -0
  576. package/v3/@claude-flow/shared/dist/events/index.d.ts +21 -0
  577. package/v3/@claude-flow/shared/dist/events/index.js +22 -0
  578. package/v3/@claude-flow/shared/dist/events/projections.d.ts +177 -0
  579. package/v3/@claude-flow/shared/dist/events/projections.js +421 -0
  580. package/v3/@claude-flow/shared/dist/events/rvf-event-log.d.ts +82 -0
  581. package/v3/@claude-flow/shared/dist/events/rvf-event-log.js +340 -0
  582. package/v3/@claude-flow/shared/dist/events/state-reconstructor.d.ts +101 -0
  583. package/v3/@claude-flow/shared/dist/events/state-reconstructor.js +263 -0
  584. package/v3/@claude-flow/shared/dist/events.d.ts +80 -0
  585. package/v3/@claude-flow/shared/dist/events.js +249 -0
  586. package/v3/@claude-flow/shared/dist/hooks/example-usage.d.ts +42 -0
  587. package/v3/@claude-flow/shared/dist/hooks/example-usage.js +351 -0
  588. package/v3/@claude-flow/shared/dist/hooks/executor.d.ts +100 -0
  589. package/v3/@claude-flow/shared/dist/hooks/executor.js +267 -0
  590. package/v3/@claude-flow/shared/dist/hooks/hooks.test.d.ts +9 -0
  591. package/v3/@claude-flow/shared/dist/hooks/hooks.test.js +322 -0
  592. package/v3/@claude-flow/shared/dist/hooks/index.d.ts +52 -0
  593. package/v3/@claude-flow/shared/dist/hooks/index.js +51 -0
  594. package/v3/@claude-flow/shared/dist/hooks/registry.d.ts +133 -0
  595. package/v3/@claude-flow/shared/dist/hooks/registry.js +277 -0
  596. package/v3/@claude-flow/shared/dist/hooks/safety/bash-safety.d.ts +105 -0
  597. package/v3/@claude-flow/shared/dist/hooks/safety/bash-safety.js +481 -0
  598. package/v3/@claude-flow/shared/dist/hooks/safety/file-organization.d.ts +144 -0
  599. package/v3/@claude-flow/shared/dist/hooks/safety/file-organization.js +328 -0
  600. package/v3/@claude-flow/shared/dist/hooks/safety/git-commit.d.ts +158 -0
  601. package/v3/@claude-flow/shared/dist/hooks/safety/git-commit.js +450 -0
  602. package/v3/@claude-flow/shared/dist/hooks/safety/index.d.ts +17 -0
  603. package/v3/@claude-flow/shared/dist/hooks/safety/index.js +17 -0
  604. package/v3/@claude-flow/shared/dist/hooks/session-hooks.d.ts +234 -0
  605. package/v3/@claude-flow/shared/dist/hooks/session-hooks.js +334 -0
  606. package/v3/@claude-flow/shared/dist/hooks/task-hooks.d.ts +163 -0
  607. package/v3/@claude-flow/shared/dist/hooks/task-hooks.js +326 -0
  608. package/v3/@claude-flow/shared/dist/hooks/types.d.ts +267 -0
  609. package/v3/@claude-flow/shared/dist/hooks/types.js +62 -0
  610. package/v3/@claude-flow/shared/dist/hooks/verify-exports.test.d.ts +9 -0
  611. package/v3/@claude-flow/shared/dist/hooks/verify-exports.test.js +93 -0
  612. package/v3/@claude-flow/shared/dist/index.d.ts +20 -0
  613. package/v3/@claude-flow/shared/dist/index.js +50 -0
  614. package/v3/@claude-flow/shared/dist/mcp/connection-pool.d.ts +98 -0
  615. package/v3/@claude-flow/shared/dist/mcp/connection-pool.js +364 -0
  616. package/v3/@claude-flow/shared/dist/mcp/index.d.ts +69 -0
  617. package/v3/@claude-flow/shared/dist/mcp/index.js +84 -0
  618. package/v3/@claude-flow/shared/dist/mcp/server.d.ts +166 -0
  619. package/v3/@claude-flow/shared/dist/mcp/server.js +590 -0
  620. package/v3/@claude-flow/shared/dist/mcp/session-manager.d.ts +136 -0
  621. package/v3/@claude-flow/shared/dist/mcp/session-manager.js +335 -0
  622. package/v3/@claude-flow/shared/dist/mcp/tool-registry.d.ts +178 -0
  623. package/v3/@claude-flow/shared/dist/mcp/tool-registry.js +439 -0
  624. package/v3/@claude-flow/shared/dist/mcp/transport/http.d.ts +104 -0
  625. package/v3/@claude-flow/shared/dist/mcp/transport/http.js +476 -0
  626. package/v3/@claude-flow/shared/dist/mcp/transport/index.d.ts +102 -0
  627. package/v3/@claude-flow/shared/dist/mcp/transport/index.js +238 -0
  628. package/v3/@claude-flow/shared/dist/mcp/transport/stdio.d.ts +104 -0
  629. package/v3/@claude-flow/shared/dist/mcp/transport/stdio.js +263 -0
  630. package/v3/@claude-flow/shared/dist/mcp/transport/websocket.d.ts +133 -0
  631. package/v3/@claude-flow/shared/dist/mcp/transport/websocket.js +396 -0
  632. package/v3/@claude-flow/shared/dist/mcp/types.d.ts +436 -0
  633. package/v3/@claude-flow/shared/dist/mcp/types.js +54 -0
  634. package/v3/@claude-flow/shared/dist/plugin-interface.d.ts +544 -0
  635. package/v3/@claude-flow/shared/dist/plugin-interface.js +23 -0
  636. package/v3/@claude-flow/shared/dist/plugin-loader.d.ts +139 -0
  637. package/v3/@claude-flow/shared/dist/plugin-loader.js +434 -0
  638. package/v3/@claude-flow/shared/dist/plugin-registry.d.ts +183 -0
  639. package/v3/@claude-flow/shared/dist/plugin-registry.js +457 -0
  640. package/v3/@claude-flow/shared/dist/plugins/index.d.ts +10 -0
  641. package/v3/@claude-flow/shared/dist/plugins/index.js +10 -0
  642. package/v3/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.d.ts +106 -0
  643. package/v3/@claude-flow/shared/dist/plugins/official/hive-mind-plugin.js +241 -0
  644. package/v3/@claude-flow/shared/dist/plugins/official/index.d.ts +10 -0
  645. package/v3/@claude-flow/shared/dist/plugins/official/index.js +10 -0
  646. package/v3/@claude-flow/shared/dist/plugins/official/maestro-plugin.d.ts +121 -0
  647. package/v3/@claude-flow/shared/dist/plugins/official/maestro-plugin.js +355 -0
  648. package/v3/@claude-flow/shared/dist/plugins/types.d.ts +93 -0
  649. package/v3/@claude-flow/shared/dist/plugins/types.js +9 -0
  650. package/v3/@claude-flow/shared/dist/resilience/bulkhead.d.ts +105 -0
  651. package/v3/@claude-flow/shared/dist/resilience/bulkhead.js +206 -0
  652. package/v3/@claude-flow/shared/dist/resilience/circuit-breaker.d.ts +132 -0
  653. package/v3/@claude-flow/shared/dist/resilience/circuit-breaker.js +233 -0
  654. package/v3/@claude-flow/shared/dist/resilience/index.d.ts +19 -0
  655. package/v3/@claude-flow/shared/dist/resilience/index.js +19 -0
  656. package/v3/@claude-flow/shared/dist/resilience/rate-limiter.d.ts +168 -0
  657. package/v3/@claude-flow/shared/dist/resilience/rate-limiter.js +314 -0
  658. package/v3/@claude-flow/shared/dist/resilience/retry.d.ts +91 -0
  659. package/v3/@claude-flow/shared/dist/resilience/retry.js +159 -0
  660. package/v3/@claude-flow/shared/dist/security/index.d.ts +10 -0
  661. package/v3/@claude-flow/shared/dist/security/index.js +12 -0
  662. package/v3/@claude-flow/shared/dist/security/input-validation.d.ts +73 -0
  663. package/v3/@claude-flow/shared/dist/security/input-validation.js +201 -0
  664. package/v3/@claude-flow/shared/dist/security/secure-random.d.ts +92 -0
  665. package/v3/@claude-flow/shared/dist/security/secure-random.js +142 -0
  666. package/v3/@claude-flow/shared/dist/services/index.d.ts +7 -0
  667. package/v3/@claude-flow/shared/dist/services/index.js +7 -0
  668. package/v3/@claude-flow/shared/dist/services/v3-progress.service.d.ts +124 -0
  669. package/v3/@claude-flow/shared/dist/services/v3-progress.service.js +402 -0
  670. package/v3/@claude-flow/shared/dist/types/agent.types.d.ts +137 -0
  671. package/v3/@claude-flow/shared/dist/types/agent.types.js +6 -0
  672. package/v3/@claude-flow/shared/dist/types/index.d.ts +11 -0
  673. package/v3/@claude-flow/shared/dist/types/index.js +17 -0
  674. package/v3/@claude-flow/shared/dist/types/mcp.types.d.ts +266 -0
  675. package/v3/@claude-flow/shared/dist/types/mcp.types.js +7 -0
  676. package/v3/@claude-flow/shared/dist/types/memory.types.d.ts +236 -0
  677. package/v3/@claude-flow/shared/dist/types/memory.types.js +7 -0
  678. package/v3/@claude-flow/shared/dist/types/swarm.types.d.ts +186 -0
  679. package/v3/@claude-flow/shared/dist/types/swarm.types.js +65 -0
  680. package/v3/@claude-flow/shared/dist/types/task.types.d.ts +178 -0
  681. package/v3/@claude-flow/shared/dist/types/task.types.js +32 -0
  682. package/v3/@claude-flow/shared/dist/types.d.ts +197 -0
  683. package/v3/@claude-flow/shared/dist/types.js +21 -0
  684. package/v3/@claude-flow/shared/dist/utils/secure-logger.d.ts +69 -0
  685. package/v3/@claude-flow/shared/dist/utils/secure-logger.js +208 -0
  686. package/v3/@claude-flow/shared/package.json +43 -43
  687. package/v3/README.md +493 -493
  688. package/.claude/security-scans/scan-all-standard.json +0 -321
  689. package/.claude/security-scans/scan-code-deep.json +0 -1209
  690. package/.claude/security-scans/scan-deps-full.json +0 -14
@@ -1,925 +1,999 @@
1
- #!/usr/bin/env node
2
- /**
3
- * RuFlo V3 Statusline — delegation build (#2195)
4
- *
5
- * Fix for ruvnet/ruflo#2195: the previous version re-implemented all data
6
- * readers locally using fragile file probes that missed AgentDB patterns,
7
- * the v3/docs/adr/ ADR directory, and the real vector count.
8
- *
9
- * This version delegates to 'npx @claude-flow/cli hooks statusline --json'
10
- * as the single source of truth. That command queries AgentDB directly,
11
- * counts ADRs in both directories, and reports the real intelligence pct.
12
- *
13
- * ADR counting falls back to local file reads so the display still works
14
- * without network access (counts both v3/docs/adr/ and v3/implementation/adrs/).
15
- *
16
- * Cache: JSON result is cached in /tmp for 10s so rapid prompt triggers
17
- * (every keystroke in some shells) don't hammer the CLI on every call.
18
- *
19
- * Usage: node statusline.cjs [--json] [--compact] [--dashboard]
20
- */
21
-
22
- /* eslint-disable @typescript-eslint/no-var-requires */
23
- const fs = require('fs');
24
- const path = require('path');
25
- const { execSync } = require('child_process');
26
- const os = require('os');
27
-
28
- // Configuration
29
- const CONFIG = {
30
- maxAgents: 15,
31
- // Session-cost display. Claude Code's cost.total_cost_usd is a client-side
32
- // estimate that "may differ from your actual bill" and reads as misleading on
33
- // subscription plans, where token usage is not billed per dollar. These let
34
- // each user pick what the segment means to them without changing the default.
35
- // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. ⚡, €, 🌱);
36
- // set to an empty string for the number alone.
37
- // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.
38
- costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',
39
- hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),
40
- };
41
-
42
- const CWD = process.cwd();
43
-
44
- // ─── Delegation cache ───────────────────────────────────────────
45
- // Cache the CLI JSON result for 60s so rapid prompt re-renders
46
- // (Claude Code refreshes the statusline several times a second while
47
- // streaming) don't re-invoke the CLI each time. #2337: bumped 10s→60s
48
- // because 10s was far too short for how often Claude Code re-renders.
49
- const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
50
- const CACHE_TTL_MS = 60000;
51
-
52
- // The promo/insight row is designed to rotate on a 20s cadence (funnel/
53
- // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check —
54
- // duplicated here as a bare number since this generated script has no
55
- // runtime import of the funnel module; keep in sync if that constant ever
56
- // changes). The rotation slot is only ever (re)computed SERVER-SIDE inside
57
- // the CLI subprocess this file shells out to — so a general 60s data cache
58
- // (correct and necessary for #2337) silently made that 20s design
59
- // unreachable: cache.fresh stayed true across 2-3 whole rotation slots,
60
- // so the row visibly "didn't rotate" (user report). Fix: track promo
61
- // freshness on its OWN, tighter clock — when it lags behind the current
62
- // slot, fall through to a real CLI call even though the REST of the
63
- // cached data (security/swarm/system) is still within CACHE_TTL_MS. This
64
- // does not touch or regress #2337's fix; it only adds a narrower check.
65
- const PROMO_ROTATION_SLOT_MS = 20000;
66
-
67
- // Persistent last-known-good promo record. Lives outside the /tmp cache so it
68
- // survives a full cache wipe / cache write race / CLI failure combo. Written
69
- // every time we successfully render a promo; read as a last resort so the row
70
- // never blinks out mid-session (was: 'promo shows then hides' bug report).
71
- const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');
72
- const PROMO_MEMO_TTL_MS = 6 * 60 * 60 * 1000; // 6h — long enough to bridge any hiccup, short enough that a real disable takes effect fast.
73
-
74
- // #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we
75
- // can invoke it directly via `node`. The previous version called
76
- // `npx --yes @claude-flow/cli@latest` on every uncached render, which forces
77
- // a registry resolution + cold-start of the entire CLI per render. With
78
- // multiple concurrent Claude Code sessions this storms the host (reporter
79
- // saw load average 40-65 on a 12-core box).
80
- //
81
- // Returns EVERY existing bin/cli.js candidate, in preference order (project,
82
- // monorepo, plugin marketplace, global node_modules including custom-prefix
83
- // layouts like ~/.npm-global) — mirrors getPkgVersion()'s own path probing.
84
- //
85
- // Returns a list, not a single winner: `fs.existsSync` only proves a file is
86
- // present, not that it actually runs. A marketplace/npx-cached install can
87
- // exist on disk but be broken (observed in practice: a stale marketplace
88
- // checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',
89
- // that isn't bundled there — every invocation throws ERR_MODULE_NOT_FOUND).
90
- // Picking the first EXISTING path and never falling through meant a single
91
- // broken install silently killed the promo row for the entire session (the
92
- // CLI call always failed, so the memo could never refresh and eventually
93
- // expired). getStatuslineData() now walks this whole list and tries the next
94
- // candidate on failure, so one broken install can't permanently wedge it.
95
- function resolveCliBinCandidates() {
96
- const candidates = [];
97
- try {
98
- const home = os.homedir();
99
- candidates.push(
100
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
101
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
102
- path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),
103
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
104
- );
105
- try {
106
- const binDir = path.dirname(process.execPath);
107
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
108
- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
109
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
110
- }
111
- for (const gm of globalModuleDirs) {
112
- candidates.push(
113
- path.join(gm, 'ruflo', 'bin', 'cli.js'),
114
- path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),
115
- );
116
- }
117
- } catch { /* ignore */ }
118
- } catch { /* ignore */ }
119
- return candidates.filter((p) => {
120
- try {
121
- if (!fs.existsSync(p)) return false;
122
- // A candidate's bin/cli.js can exist on disk while its compiled
123
- // dist/ never got built (Claude Code's own plugin marketplace just
124
- // git-clones the repo — no install/build step — so every marketplace
125
- // install is a source-only checkout by construction). Importing
126
- // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on
127
- // every real command; only --version happens to survive it. Check
128
- // for the compiled entrypoint too so a doomed candidate is skipped
129
- // up front instead of wasting a spawn-and-fail on every render.
130
- return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
131
- } catch { return false; }
132
- });
133
- }
134
-
135
- // Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL
136
- // — but data is returned regardless (stale-while-revalidate). This lets us
137
- // serve last known state (specifically the promo row) when the CLI is
138
- // slow/unavailable, so users don't see the funnel row flicker in and out on
139
- // cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock
140
- // as PROMO_ROTATION_SLOT_MS — see that constant's comment for why the promo
141
- // row needs its own freshness bound distinct from the general 60s TTL.
142
- function readCache() {
143
- try {
144
- if (fs.existsSync(CACHE_FILE)) {
145
- const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
146
- if (raw && raw._ts && raw.data) {
147
- const age = Date.now() - raw._ts;
148
- return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };
149
- }
150
- }
151
- } catch { /* ignore */ }
152
- return { fresh: false, promoFresh: false, data: null };
153
- }
154
-
155
- function writeCache(data) {
156
- try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }
157
- // Also memoize any promo we saw so the row can survive future CLI hiccups.
158
- try {
159
- if (data && data.promo && typeof data.promo === 'object') {
160
- fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });
161
- fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });
162
- }
163
- } catch { /* ignore */ }
164
- }
165
-
166
- // Last resort: read a memoized promo (up to 6h old). Used when no cache and
167
- // no CLI response is available — the row still renders, so users don't see
168
- // the disclosure blink out. Returns null when the memo is absent, expired,
169
- // or malformed. Never throws.
170
- function readPromoMemo() {
171
- try {
172
- if (!fs.existsSync(PROMO_MEMO_FILE)) return null;
173
- const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));
174
- if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {
175
- return raw.promo;
176
- }
177
- } catch { /* ignore */ }
178
- return null;
179
- }
180
-
181
- /**
182
- * Single source of truth: delegate to the CLI hooks statusline --json command.
183
- * Falls back to a minimal static object on failure so the statusline still renders.
184
- *
185
- * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns
186
- * (missed the .swarm/memory.db → AgentDB path), computed dddProgress wrong,
187
- * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).
188
- */
189
- // Overlay the memoized promo onto any data object that's missing one. This is
190
- // the safety net that keeps the funnel row rendered when an OLDER cached CLI
191
- // version is picked up by npx — that older CLI succeeds but omits promo, so
192
- // the JSON round-trips clean but without our row. We patch it back here.
193
- function overlayMemoPromo(data) {
194
- if (data && !data.promo) {
195
- const memoPromo = readPromoMemo();
196
- if (memoPromo) data.promo = memoPromo;
197
- }
198
- return data;
199
- }
200
-
201
- function getStatuslineData() {
202
- const cache = readCache();
203
- // Both clocks must be satisfied to skip the CLI call entirely: the general
204
- // 60s TTL (#2337 — don't re-spawn the CLI on every rapid re-render) AND the
205
- // tighter promo-rotation clock (this fix — don't let a still-fresh 60s
206
- // cache silently freeze the promo/insight row across multiple 20s slots).
207
- if (cache.fresh && cache.promoFresh) return overlayMemoPromo(cache.data);
208
-
209
- // #2337: prefer an already-installed CLI bin via direct `node` invocation —
210
- // no npx, no registry round-trip, no @latest re-resolve per render. Try
211
- // every candidate that actually EXISTS (not just the first) before falling
212
- // back to `npx --prefer-offline @claude-flow/cli` (no @latest); an existing
213
- // but broken install (e.g. a stale marketplace checkout missing a bundled
214
- // workspace dep) must not block trying the next one.
215
- //
216
- // No `2>/dev/null` here (deliberately) — the execSync call below already
217
- // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the
218
- // Node level regardless of shell. The redirect was redundant on POSIX and
219
- // actively broke every candidate on Windows: cmd.exe (execSync's default
220
- // shell there) doesn't understand /dev/null, so the CLI delegation always
221
- // failed, silently degrading every render to buildLocalFallback() — 0%
222
- // intelligence and an empty promo row (the memo cache that keeps the row
223
- // populated across CLI hiccups is only ever written from a SUCCESSFUL
224
- // delegation, so it could never get seeded on Windows either).
225
- const cmds = resolveCliBinCandidates()
226
- .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')
227
- .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);
228
- for (const cmd of cmds) {
229
- try {
230
- const raw = execSync(
231
- cmd,
232
- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD }
233
- ).trim();
234
- // The CLI may emit preamble lines before the JSON — find the first '{'.
235
- const jsonStart = raw.indexOf('{');
236
- if (jsonStart === -1) throw new Error('no JSON in CLI output');
237
- const data = JSON.parse(raw.slice(jsonStart));
238
- // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)
239
- // with real local reads, so those segments reflect actual state instead of 0.
240
- applyLocalOverlays(data);
241
- overlayMemoPromo(data);
242
- writeCache(data);
243
- return data;
244
- } catch { /* this candidate unavailable, broken, or timed out — try the next */ }
245
- }
246
-
247
- // Stale-while-revalidate: if we have any cached data, keep serving it so the
248
- // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for
249
- // the segments the CLI JSON doesn't populate; the promo row survives.
250
- if (cache.data) {
251
- applyLocalOverlays(cache.data);
252
- overlayMemoPromo(cache.data);
253
- return cache.data;
254
- }
255
-
256
- // Last resort: local probes + memo. Users still see the funnel row.
257
- return overlayMemoPromo(buildLocalFallback());
258
- }
259
-
260
- // Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed
261
- // v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).
262
- function getLocalADRCount() {
263
- const adrDirs = [
264
- path.join(CWD, 'v3', 'implementation', 'adrs'),
265
- path.join(CWD, 'v3', 'docs', 'adr'),
266
- path.join(CWD, 'docs', 'adrs'),
267
- path.join(CWD, '.claude-flow', 'adrs'),
268
- ];
269
- let total = 0;
270
- for (const dir of adrDirs) {
271
- try {
272
- if (fs.existsSync(dir)) {
273
- const files = fs.readdirSync(dir).filter(function(f) {
274
- return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\d{4}-/.test(f));
275
- });
276
- total += files.length;
277
- }
278
- } catch { /* ignore */ }
279
- }
280
- return { count: total, implemented: total, compliance: 0 };
281
- }
282
-
283
- // ─── Local overlays for segments the CLI JSON omits ──────────────
284
- // 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.
285
- // agentdb/tests/hooks/integration are never populated, so without these overlays
286
- // they render as a permanent 0. Each reader is cheap and degrades to zeros.
287
-
288
- // Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db
289
- // (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.
290
- // One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).
291
- function getLocalAgentDB() {
292
- const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };
293
- try {
294
- let bytes = 0;
295
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
296
- try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }
297
- }
298
- result.dbSizeKB = Math.round(bytes / 1024);
299
-
300
- const memDb = path.join(CWD, '.swarm', 'memory.db');
301
- if (fs.existsSync(memDb)) {
302
- const Q = String.fromCharCode(34);
303
- // Two INDEPENDENT statements -- do NOT combine into one. Coupling the
304
- // vector count with the vector_indexes row count in a single statement
305
- // meant that on a DB missing the vector_indexes table (older/agentdb-
306
- // written DBs), the whole statement failed at PREPARE time (SQLite
307
- // compiles the full SQL before running), so the valid memory_entries
308
- // count was discarded too and the statusline showed Vectors 0 despite
309
- // thousands of real vectors. Split so a missing table can only zero the
310
- // HNSW flag, never the count. The init self-heal provisions the table so
311
- // the flag recovers on the next ruflo init / MCP start.
312
- const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;
313
- const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);
314
- if (vc) result.vectorCount = parseInt(vc, 10) || 0;
315
- // HNSW flag: separate statement. If vector_indexes is absent, sqlite3
316
- // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact
317
- // original semantics: at least one index-config row present).
318
- const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;
319
- const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);
320
- if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;
321
- }
322
- } catch { /* ignore */ }
323
- return result;
324
- }
325
-
326
- // Count test files via a bounded directory walk (no file reads).
327
- function getLocalTests() {
328
- let testFiles = 0;
329
- function countTests(dir, depth) {
330
- if ((depth || 0) > 4) return;
331
- try {
332
- if (!fs.existsSync(dir)) return;
333
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
334
- if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {
335
- countTests(path.join(dir, e.name), (depth || 0) + 1);
336
- } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {
337
- testFiles++;
338
- }
339
- }
340
- } catch { /* ignore */ }
341
- }
342
- for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));
343
- return { testFiles, testCases: testFiles * 4 };
344
- }
345
-
346
- // Count configured hooks from project .claude/settings.json. Claude Code hooks
347
- // have no enabled/disabled flag, so every configured hook counts as enabled.
348
- function getLocalHooks() {
349
- const result = { enabled: 0, total: 0 };
350
- try {
351
- const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));
352
- const hooks = settings && settings.hooks;
353
- if (hooks && typeof hooks === 'object') {
354
- let n = 0;
355
- for (const ev of Object.keys(hooks)) {
356
- const groups = hooks[ev];
357
- if (Array.isArray(groups)) {
358
- for (const g of groups) {
359
- if (g && Array.isArray(g.hooks)) n += g.hooks.length;
360
- }
361
- }
362
- }
363
- result.total = n;
364
- result.enabled = n;
365
- }
366
- } catch { /* ignore */ }
367
- return result;
368
- }
369
-
370
- // Best-effort integration block: DB presence + locally-configured stdio MCP
371
- // servers (project .mcp.json + global ~/.claude.json). Remote connectors are
372
- // account-managed and not present in local config, so they are not counted.
373
- function getLocalIntegration() {
374
- const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };
375
- try {
376
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
377
- if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }
378
- }
379
- const names = new Set();
380
- const projMcp = readJSON(path.join(CWD, '.mcp.json'));
381
- if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);
382
- const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));
383
- if (claudeJson) {
384
- if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);
385
- const proj = claudeJson.projects && claudeJson.projects[CWD];
386
- if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {
387
- for (const k of Object.keys(proj.mcpServers)) names.add(k);
388
- }
389
- }
390
- integration.mcpServers.total = names.size;
391
- integration.mcpServers.enabled = names.size;
392
- } catch { /* ignore */ }
393
- return integration;
394
- }
395
-
396
- // Overlay every locally-derived block onto the CLI data (mutates in place).
397
- function applyLocalOverlays(data) {
398
- data.adrs = getLocalADRCount();
399
- data.agentdb = getLocalAgentDB();
400
- data.tests = getLocalTests();
401
- data.hooks = getLocalHooks();
402
- data.integration = getLocalIntegration();
403
- return data;
404
- }
405
-
406
- // Minimal local fallback when the CLI is not installed or times out.
407
- // Returns a structure that matches the CLI JSON schema so the renderer works.
408
- function buildLocalFallback() {
409
- const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
410
-
411
- return applyLocalOverlays({
412
- user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },
413
- v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },
414
- security: { status: 'NONE', cvesFixed: 0, totalCves: 0 },
415
- swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },
416
- system: { memoryMB: memMB, contextPct: 0, intelligencePct: 0, subAgents: 0 },
417
- lastUpdated: new Date().toISOString(),
418
- });
419
- }
420
-
421
- // ANSI colors
422
- const c = {
423
- reset: '\x1b[0m',
424
- bold: '\x1b[1m',
425
- dim: '\x1b[2m',
426
- red: '\x1b[0;31m',
427
- green: '\x1b[0;32m',
428
- yellow: '\x1b[0;33m',
429
- blue: '\x1b[0;34m',
430
- purple: '\x1b[0;35m',
431
- cyan: '\x1b[0;36m',
432
- brightRed: '\x1b[1;31m',
433
- brightGreen: '\x1b[1;32m',
434
- brightYellow: '\x1b[1;33m',
435
- brightBlue: '\x1b[1;34m',
436
- brightPurple: '\x1b[1;35m',
437
- brightCyan: '\x1b[1;36m',
438
- brightWhite: '\x1b[1;37m',
439
- };
440
-
441
- // Safe execSync with strict timeout (returns empty string on failure)
442
- function safeExec(cmd, timeoutMs) {
443
- try {
444
- return execSync(cmd, {
445
- encoding: 'utf-8',
446
- timeout: timeoutMs || 2000,
447
- stdio: ['pipe', 'pipe', 'pipe'],
448
- }).trim();
449
- } catch {
450
- return '';
451
- }
452
- }
453
-
454
- // Safe JSON file reader (returns null on failure)
455
- function readJSON(filePath) {
456
- try {
457
- if (fs.existsSync(filePath)) {
458
- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
459
- }
460
- } catch { /* ignore */ }
461
- return null;
462
- }
463
-
464
- // ─── Git info (pure-Node / single exec — needed for branch display) ──────────
465
-
466
- function getGitInfo() {
467
- const result = {
468
- name: 'user', gitBranch: '', modified: 0, untracked: 0,
469
- staged: 0, ahead: 0, behind: 0,
470
- };
471
-
472
- const script = [
473
- 'git config user.name 2>/dev/null || echo user',
474
- 'echo "---SEP---"',
475
- 'git branch --show-current 2>/dev/null',
476
- 'echo "---SEP---"',
477
- 'git status --porcelain 2>/dev/null',
478
- 'echo "---SEP---"',
479
- 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',
480
- ].join('; ');
481
-
482
- const raw = safeExec("sh -c '" + script + "'", 3000);
483
- if (!raw) return result;
484
-
485
- const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });
486
- if (parts.length >= 4) {
487
- result.name = parts[0] || 'user';
488
- result.gitBranch = parts[1] || '';
489
-
490
- if (parts[2]) {
491
- for (const line of parts[2].split('\n')) {
492
- if (!line || line.length < 2) continue;
493
- const x = line[0], y = line[1];
494
- if (x === '?' && y === '?') { result.untracked++; continue; }
495
- if (x !== ' ' && x !== '?') result.staged++;
496
- if (y !== ' ' && y !== '?') result.modified++;
497
- }
498
- }
499
-
500
- const ab = (parts[3] || '0 0').split(/\s+/);
501
- result.ahead = parseInt(ab[0]) || 0;
502
- result.behind = parseInt(ab[1]) || 0;
503
- }
504
-
505
- return result;
506
- }
507
-
508
- // Detect model name from Claude config (pure file reads, no exec)
509
- function getModelName() {
510
- try {
511
- const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));
512
- if (claudeConfig && claudeConfig.projects) {
513
- for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
514
- if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {
515
- const usage = projectConfig.lastModelUsage;
516
- if (usage) {
517
- const ids = Object.keys(usage);
518
- if (ids.length > 0) {
519
- let modelId = ids[ids.length - 1];
520
- let latest = 0;
521
- for (const id of ids) {
522
- const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
523
- if (ts > latest) { latest = ts; modelId = id; }
524
- }
525
- if (modelId.includes('opus')) return 'Opus 4.8';
526
- if (modelId.includes('sonnet')) return 'Sonnet 4.6';
527
- if (modelId.includes('haiku')) return 'Haiku 4.5';
528
- return modelId.split('-').slice(1, 3).join(' ');
529
- }
530
- }
531
- break;
532
- }
533
- }
534
- }
535
- } catch { /* ignore */ }
536
-
537
- // Fallback: settings.json model field
538
- const settings = getSettings();
539
- if (settings && settings.model) {
540
- const m = settings.model;
541
- if (m.includes('opus')) return 'Opus 4.8';
542
- if (m.includes('sonnet')) return 'Sonnet 4.6';
543
- if (m.includes('haiku')) return 'Haiku 4.5';
544
- }
545
- return 'Claude Code';
546
- }
547
-
548
- // ─── Stdin reader (Claude Code pipes session JSON) ──────────────
549
- // Claude Code sends session JSON via stdin. Read synchronously so the
550
- // script works both when invoked by Claude Code (stdin has JSON) and
551
- // when run manually from terminal (stdin is empty/tty).
552
- let _stdinData = null;
553
- function getStdinData() {
554
- if (_stdinData !== undefined && _stdinData !== null) return _stdinData;
555
- try {
556
- if (process.stdin.isTTY) { _stdinData = null; return null; }
557
- const chunks = [];
558
- const buf = Buffer.alloc(4096);
559
- let bytesRead;
560
- try {
561
- while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {
562
- chunks.push(buf.slice(0, bytesRead));
563
- }
564
- } catch { /* EOF or read error */ }
565
- const raw = Buffer.concat(chunks).toString('utf-8').trim();
566
- _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;
567
- } catch {
568
- _stdinData = null;
569
- }
570
- return _stdinData;
571
- }
572
-
573
- function getModelFromStdin() {
574
- const data = getStdinData();
575
- return (data && data.model && data.model.display_name) ? data.model.display_name : null;
576
- }
577
-
578
- function getContextFromStdin() {
579
- const data = getStdinData();
580
- if (data && data.context_window) {
581
- return { usedPct: Math.floor(data.context_window.used_percentage || 0) };
582
- }
583
- return null;
584
- }
585
-
586
- function getCostFromStdin() {
587
- const data = getStdinData();
588
- if (data && data.cost) {
589
- const durationMs = data.cost.total_duration_ms || 0;
590
- const mins = Math.floor(durationMs / 60000);
591
- const secs = Math.floor((durationMs % 60000) / 1000);
592
- return {
593
- costUsd: data.cost.total_cost_usd || 0,
594
- duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',
595
- };
596
- }
597
- return null;
598
- }
599
-
600
- // Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").
601
- // Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately
602
- // simple (no prerelease/build-metadata handling) — this only orders local
603
- // package.json versions against each other, never anything untrusted from
604
- // a payload, so a full semver implementation would be dead weight here.
605
- function compareVersions(a, b) {
606
- const pa = String(a).split('.').map((n) => parseInt(n, 10));
607
- const pb = String(b).split('.').map((n) => parseInt(n, 10));
608
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
609
- const na = Number.isFinite(pa[i]) ? pa[i] : 0;
610
- const nb = Number.isFinite(pb[i]) ? pb[i] : 0;
611
- if (na !== nb) return na - nb;
612
- }
613
- return 0;
614
- }
615
-
616
- function getPkgVersion() {
617
- // Baked in at generation time from the real running CLI's own resolved
618
- // version (see generateStatuslineScript()'s doc comment) — correct even
619
- // when this renders via a pure npx invocation with no local install for
620
- // the candidate scan below to find.
621
- let ver = "3.28.0";
622
- try {
623
- const home = os.homedir();
624
- const pkgPaths = [
625
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),
626
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),
627
- path.join(CWD, 'node_modules', 'ruflo', 'package.json'),
628
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),
629
- ];
630
- // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the
631
- // probes above all miss and the version falls back to the hard-coded default.
632
- // Derive the global node_modules dir from the running node binary (no npm spawn —
633
- // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows
634
- // (bin/node_modules) layouts.
635
- try {
636
- const binDir = path.dirname(process.execPath);
637
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
638
- // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from
639
- // the node binary location, so the binDir-derived probes above all miss. Also
640
- // probe the npm prefix from the environment and the common ~/.npm-global default.
641
- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
642
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
643
- }
644
- for (const gm of globalModuleDirs) {
645
- pkgPaths.push(
646
- path.join(gm, 'ruflo', 'package.json'),
647
- path.join(gm, '@claude-flow', 'cli', 'package.json'),
648
- );
649
- }
650
- } catch { /* ignore */ }
651
- // Pick the HIGHEST version among every candidate that exists, not the
652
- // first one found. The marketplace plugin path is probed first (list
653
- // order above), but Claude Code's own plugin marketplace mechanism
654
- // syncs on its own git-pull cadence, independent of npm publishes — a
655
- // freshly-published npm version can sit alongside a stale marketplace
656
- // checkout for a while (observed live: marketplace one release behind
657
- // right after a publish). Taking the first EXISTING candidate meant the
658
- // header could show a stale version even when a newer install (e.g.
659
- // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.
660
- let found = false;
661
- for (const p of pkgPaths) {
662
- if (!fs.existsSync(p)) continue;
663
- try {
664
- const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
665
- if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
666
- if (!found || compareVersions(pkg.version, ver) > 0) ver = pkg.version;
667
- found = true;
668
- }
669
- } catch { /* ignore */ }
670
- }
671
- } catch { /* ignore */ }
672
- return ver;
673
- }
674
-
675
- // ─── Rendering ──────────────────────────────────────────────────
676
-
677
- function progressBar(current, total) {
678
- const width = 5;
679
- const filled = Math.round((current / total) * width);
680
- return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
681
- }
682
-
683
- function generateStatusline() {
684
- const d = getStatuslineData();
685
- const git = getGitInfo();
686
- const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
687
- const ctxInfo = getContextFromStdin();
688
- const costInfo = getCostFromStdin();
689
- // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard
690
- // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted
691
- // .cjs artifact — without it the header silently reverts to a hard-coded
692
- // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.
693
- const RUFLO_VERSION = getPkgVersion();
694
-
695
- const progress = d.v3Progress || {};
696
- const security = d.security || {};
697
- const swarm = d.swarm || {};
698
- const system = d.system || {};
699
- const adrs = d.adrs || {};
700
- const hooks = d.hooks || {};
701
- const agentdb = d.agentdb || {};
702
- const tests = d.tests || {};
703
-
704
- const domainsCompleted = progress.domainsCompleted || 0;
705
- const totalDomains = progress.totalDomains || 5;
706
- const dddProgress = progress.dddProgress || 0;
707
- const patternsLearned = progress.patternsLearned || 0;
708
- const activeAgents = swarm.activeAgents || 0;
709
- const maxAgents = swarm.maxAgents || CONFIG.maxAgents;
710
- const coordinationActive = swarm.coordinationActive || false;
711
- const intelligencePct = system.intelligencePct || 0;
712
- const memoryMB = system.memoryMB || 0;
713
- const subAgents = system.subAgents || 0;
714
- const cvesFixed = security.cvesFixed || 0;
715
- const totalCves = security.totalCves || 0;
716
- const secStatus = security.status || 'NONE';
717
- const adrCount = adrs.count || 0;
718
- const adrImpl = adrs.implemented || 0;
719
- const hooksEnabled = hooks.enabled || 0;
720
- const hooksTotal = hooks.total || 0;
721
- const vectorCount = agentdb.vectorCount || 0;
722
- const hasHnsw = agentdb.hasHnsw || false;
723
- const dbSizeKB = agentdb.dbSizeKB || 0;
724
- const testFiles = tests.testFiles || 0;
725
- const testCases = tests.testCases || testFiles * 4;
726
-
727
- const lines = [];
728
-
729
- // 3-line design (fits Claude Code's visible statusline area — line 4+ gets
730
- // replaced by the system guidance / input prompt line):
731
- // Line 1 — Header (RuFlo version · git · model · timing · context · cost)
732
- // Line 2 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health)
733
- // Line 3 — Promo / disclosure row (funnel surface, ADR-301)
734
-
735
- // ─── Line 1: header ────────────────────────────────────────────
736
- let header = c.bold + c.brightPurple + '▊ RuFlo V' + RUFLO_VERSION + ' ' + c.reset;
737
- header += (coordinationActive ? c.brightCyan : c.dim) + '● ' + c.brightCyan + git.name + c.reset;
738
- if (git.gitBranch) {
739
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightBlue + '⏇ ' + git.gitBranch + c.reset;
740
- const changes = git.modified + git.staged + git.untracked;
741
- if (changes > 0) {
742
- let ind = '';
743
- if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;
744
- if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;
745
- if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;
746
- header += ' ' + ind;
747
- }
748
- if (git.ahead > 0) header += ' ' + c.brightGreen + '↑' + git.ahead + c.reset;
749
- if (git.behind > 0) header += ' ' + c.brightRed + '↓' + git.behind + c.reset;
750
- }
751
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.purple + modelName + c.reset;
752
- const duration = costInfo ? costInfo.duration : '';
753
- if (duration) header += ' ' + c.dim + '│' + c.reset + ' ' + c.cyan + '⏱ ' + duration + c.reset;
754
- if (ctxInfo && ctxInfo.usedPct > 0) {
755
- const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;
756
- header += ' ' + c.dim + '│' + c.reset + ' ' + ctxColor + '● ' + ctxInfo.usedPct + '% ctx' + c.reset;
757
- }
758
- if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {
759
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;
760
- }
761
- lines.push(header);
762
-
763
- // ─── Line 2: compressed ops ────────────────────────────────────
764
- // Everything actionable in one dense row. Show only what changes what you
765
- // do next; diagnostic detail moves to `ruflo status --verbose`.
766
- const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;
767
- const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;
768
- const intellColor = intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;
769
- const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset + ' ' : c.dim + '○' + c.reset + ' ';
770
- const cvesClean = totalCves === 0 || cvesFixed === totalCves;
771
- const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && cvesClean;
772
- const opsParts = [];
773
- opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);
774
- if (subAgents > 0) opsParts.push(c.brightPurple + '👥 ' + subAgents + c.reset);
775
- opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);
776
- opsParts.push(intellColor + '🧠 ' + intelligencePct + '%' + c.reset);
777
- opsParts.push(c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset);
778
- // Health: one glyph when green, terse copy when there's something to act on.
779
- if (healthAllGreen) {
780
- opsParts.push(c.brightGreen + '🛡 ✓' + c.reset);
781
- } else {
782
- if (secStatus === 'PENDING') opsParts.push(c.brightYellow + '🛡 scan pending' + c.reset);
783
- else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + '🛡 scanning…' + c.reset);
784
- else if (secStatus === 'STALE') opsParts.push(c.brightYellow + '🛡 scan stale' + c.reset);
785
- else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + '🛡 ' + secStatus.toLowerCase() + c.reset);
786
- if (totalCves > 0 && cvesFixed < totalCves) {
787
- const unfixed = totalCves - cvesFixed;
788
- opsParts.push(c.brightRed + '⚠ ' + unfixed + ' CVE' + (unfixed === 1 ? '' : 's') + c.reset);
789
- }
790
- }
791
- lines.push(opsParts.join(' ' + c.dim + '·' + c.reset + ' '));
792
-
793
- // ─── Line 3: promo / disclosure / insight ───────────────────────
794
- // Colored by content kind so it reads as *what it is*, not as noise:
795
- // disclosure → brightCyan (announcement / capability link)
796
- // promotional → brightPurple (Cognitum sponsor spot)
797
- // educational → yellow (a tip)
798
- // insight → brightRed (environment/task-aware, local, actionable —
799
- // distinct from remote content on purpose)
800
- const promoRow = getPromoRow(d);
801
- if (promoRow) {
802
- const kind = (d && d.promo && d.promo.kind) || 'disclosure';
803
- const promoColor = kind === 'promotional' ? c.brightPurple
804
- : kind === 'educational' ? c.yellow
805
- : kind === 'insight' ? c.brightRed
806
- : c.brightCyan;
807
- lines.push(promoColor + promoRow + c.reset);
808
- }
809
-
810
- // Trailing blank line so Claude Code's input prompt gets breathing room
811
- // instead of butting directly against the last statusline row.
812
- return lines.join('\n') + '\n';
813
- }
814
-
815
- // ─── Funnel promo row (ADR-301) ─────────────────────────────────
816
- // Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so
817
- // no message can smuggle a link to an unapproved host.
818
- //
819
- // The final destination hosts (cognitum.one / agentics.org) AND the
820
- // click-redirect host are both allowlisted here: promo.ts routes every
821
- // clickable message through the server-side click-redirect (ADR-311 §7)
822
- // so promo_open + geo are captured before the 302 to the real target —
823
- // so the OSC 8 link the renderer emits points at the redirect host, not
824
- // the final destination directly.
825
- const PROMO_LINK_HOSTS = new Set([
826
- 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
827
- // agentics.org — OSS foundation, distinct sponsor domain. Kept in sync
828
- // with messages.ts ALLOWED_URL_HOSTS.
829
- 'agentics.org', 'www.agentics.org',
830
- // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw
831
- // Cloud Run hostname is allowlisted too since event-transport.ts /
832
- // message-transport.ts / attribution.ts currently point at it as a TEMP
833
- // fallback while the domain mapping's cert provisions).
834
- 'funnel.ruv.io',
835
- 'cognitum-analytics-63rzcdswba-uc.a.run.app',
836
- ]);
837
-
838
- // Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles
839
- // raw OSC 8 (see anthropics/claude-code#27047) — opt in via env if wrapped.
840
- function terminalSupportsHyperlinks() {
841
- if (process.env.CI || process.env.GITHUB_ACTIONS) return false;
842
- if (process.env.TERM === 'dumb') return false;
843
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;
844
- if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;
845
- return true;
846
- }
847
-
848
- // Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw
849
- // label whenever the URL is not an allowlisted https target, when the terminal
850
- // can't render hyperlinks, or when parsing fails — a broken link must never
851
- // leave a raw URL or stray escape in the statusline output.
852
- function safeTerminalLink(label, url) {
853
- if (!terminalSupportsHyperlinks()) return label;
854
- if (typeof url !== 'string' || url.length === 0) return label;
855
- let parsed;
856
- try { parsed = new URL(url); } catch { return label; }
857
- if (parsed.protocol !== 'https:') return label;
858
- if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;
859
- const cleanLabel = String(label).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');
860
- if (cleanLabel.length === 0) return label;
861
- const ESC = '\u001b';
862
- return ESC + ']8;;' + parsed.href + ESC + '\\' + cleanLabel + ESC + ']8;;' + ESC + '\\';
863
- }
864
-
865
- function getPromoRow(d) {
866
- try {
867
- if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
868
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
869
- const promo = d && d.promo;
870
- if (!promo || typeof promo.text !== 'string') return null;
871
- // Strip control chars / ANSI / bidi overrides and hard-cap length —
872
- // promo copy is data and must never emit its own terminal sequences.
873
- const text = promo.text
874
- .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
875
- .slice(0, 100)
876
- .trim();
877
- if (text.length === 0) return null;
878
- // Split the label from the trailing "· manage: ruflo settings" instruction
879
- // so each part gets styling that matches what it actually IS:
880
- // 1. label — OSC 8 hyperlink + underline. A real clickable link.
881
- // 2. "manage:" — dim. Just a connector word, no action implied.
882
- // 3. "ruflo settings" — bold/bright, NOT underlined. This is a shell
883
- // command the user TYPES, not a link they CLICK — a terminal can
884
- // never safely execute a command from a click (that would let any
885
- // server-served message run arbitrary commands), so we deliberately
886
- // avoid the underline/OSC8 cues that imply "clickable". Bold+bright
887
- // instead signals "this is the important bit — copy/type it".
888
- // Educational tips have no manage tail and no URL — plain text through.
889
- const manageIdx = text.indexOf(' · manage: ');
890
- const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;
891
- const manageWord = manageIdx > 0 ? ' · manage: ' : '';
892
- const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';
893
- const UL_ON = '\u001b[4m';
894
- const UL_OFF = '\u001b[24m';
895
- const DIM_ON = '\u001b[2m';
896
- const DIM_OFF = '\u001b[22m';
897
- const BOLD_ON = '\u001b[1m';
898
- const BOLD_OFF = '\u001b[22m';
899
- const linked = promo.url ? UL_ON + safeTerminalLink(label, promo.url) + UL_OFF : label;
900
- if (!command) return linked;
901
- return linked + DIM_ON + manageWord + DIM_OFF + BOLD_ON + command + BOLD_OFF;
902
- } catch (e) {
903
- return null; // the promo row must never break the statusline
904
- }
905
- }
906
-
907
- // JSON output — delegates to CLI for accuracy; caller can use --json flag
908
- function generateJSON() {
909
- const d = getStatuslineData();
910
- const git = getGitInfo();
911
- return Object.assign({}, d, {
912
- user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),
913
- git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },
914
- lastUpdated: new Date().toISOString(),
915
- });
916
- }
917
-
918
- // ─── Main ───────────────────────────────────────────────────────
919
- if (process.argv.includes('--json')) {
920
- console.log(JSON.stringify(generateJSON(), null, 2));
921
- } else if (process.argv.includes('--compact')) {
922
- console.log(JSON.stringify(generateJSON()));
923
- } else {
924
- console.log(generateStatusline());
925
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * RuFlo V3 Statusline — delegation build (#2195)
4
+ *
5
+ * Fix for ruvnet/ruflo#2195: the previous version re-implemented all data
6
+ * readers locally using fragile file probes that missed AgentDB patterns,
7
+ * the v3/docs/adr/ ADR directory, and the real vector count.
8
+ *
9
+ * This version delegates to 'npx @claude-flow/cli hooks statusline --json'
10
+ * as the single source of truth. That command queries AgentDB directly,
11
+ * counts ADRs in both directories, and reports the real intelligence pct.
12
+ *
13
+ * ADR counting falls back to local file reads so the display still works
14
+ * without network access (counts both v3/docs/adr/ and v3/implementation/adrs/).
15
+ *
16
+ * Cache: JSON result is cached in /tmp for 10s so rapid prompt triggers
17
+ * (every keystroke in some shells) don't hammer the CLI on every call.
18
+ *
19
+ * Usage: node statusline.cjs [--json] [--compact] [--dashboard]
20
+ */
21
+
22
+ /* eslint-disable @typescript-eslint/no-var-requires */
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const { execSync } = require('child_process');
26
+ const os = require('os');
27
+
28
+ // Configuration
29
+ const CONFIG = {
30
+ maxAgents: 15,
31
+ // Session-cost display. Claude Code's cost.total_cost_usd is a client-side
32
+ // estimate that "may differ from your actual bill" and reads as misleading on
33
+ // subscription plans, where token usage is not billed per dollar. These let
34
+ // each user pick what the segment means to them without changing the default.
35
+ // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. ⚡, €, 🌱);
36
+ // set to an empty string for the number alone.
37
+ // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.
38
+ costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',
39
+ hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),
40
+ };
41
+
42
+ const CWD = process.cwd();
43
+
44
+ // ─── Delegation cache ───────────────────────────────────────────
45
+ // Cache the CLI JSON result so rapid prompt re-renders (Claude Code
46
+ // refreshes the statusline several times a second while streaming) don't
47
+ // re-invoke the CLI each time.
48
+ // #2337 bumped 10s → 60s.
49
+ // Followup for anthropics/claude-code#70200 (Windows console-flash bug —
50
+ // claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,
51
+ // producing a visible cmd flash on every render): bumped 60s → 300s to
52
+ // reduce the flash rate 5x on Windows until the upstream fix ships.
53
+ // Tradeoff: stat/git counters update every 5min instead of every 1min;
54
+ // promo/insight row still rotates on its own tighter 20s promoFresh clock.
55
+ const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
56
+ const CACHE_TTL_MS = 300000;
57
+
58
+ // The promo/insight row is designed to rotate on a 20s cadence (funnel/
59
+ // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check —
60
+ // duplicated here as a bare number since this generated script has no
61
+ // runtime import of the funnel module; keep in sync if that constant ever
62
+ // changes). The rotation slot is only ever (re)computed SERVER-SIDE inside
63
+ // the CLI subprocess this file shells out to — so a general 60s data cache
64
+ // (correct and necessary for #2337) silently made that 20s design
65
+ // unreachable: cache.fresh stayed true across 2-3 whole rotation slots,
66
+ // so the row visibly "didn't rotate" (user report). Fix: track promo
67
+ // freshness on its OWN, tighter clock — when it lags behind the current
68
+ // slot, fall through to a real CLI call even though the REST of the
69
+ // cached data (security/swarm/system) is still within CACHE_TTL_MS. This
70
+ // does not touch or regress #2337's fix; it only adds a narrower check.
71
+ const PROMO_ROTATION_SLOT_MS = 20000;
72
+
73
+ // Persistent last-known-good promo record. Lives outside the /tmp cache so it
74
+ // survives a full cache wipe / cache write race / CLI failure combo. Written
75
+ // every time we successfully render a promo; read as a last resort so the row
76
+ // never blinks out mid-session (was: 'promo shows then hides' bug report).
77
+ const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');
78
+ const PROMO_MEMO_TTL_MS = 6 * 60 * 60 * 1000; // 6h — long enough to bridge any hiccup, short enough that a real disable takes effect fast.
79
+
80
+ // #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we
81
+ // can invoke it directly via `node`. The previous version called
82
+ // `npx --yes @claude-flow/cli@latest` on every uncached render, which forces
83
+ // a registry resolution + cold-start of the entire CLI per render. With
84
+ // multiple concurrent Claude Code sessions this storms the host (reporter
85
+ // saw load average 40-65 on a 12-core box).
86
+ //
87
+ // Returns EVERY existing bin/cli.js candidate, in preference order (project,
88
+ // monorepo, plugin marketplace, global node_modules including custom-prefix
89
+ // layouts like ~/.npm-global) — mirrors getPkgVersion()'s own path probing.
90
+ //
91
+ // Returns a list, not a single winner: `fs.existsSync` only proves a file is
92
+ // present, not that it actually runs. A marketplace/npx-cached install can
93
+ // exist on disk but be broken (observed in practice: a stale marketplace
94
+ // checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',
95
+ // that isn't bundled there — every invocation throws ERR_MODULE_NOT_FOUND).
96
+ // Picking the first EXISTING path and never falling through meant a single
97
+ // broken install silently killed the promo row for the entire session (the
98
+ // CLI call always failed, so the memo could never refresh and eventually
99
+ // expired). getStatuslineData() now walks this whole list and tries the next
100
+ // candidate on failure, so one broken install can't permanently wedge it.
101
+ function resolveCliBinCandidates() {
102
+ const candidates = [];
103
+ try {
104
+ const home = os.homedir();
105
+ candidates.push(
106
+ path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
107
+ path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
108
+ path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),
109
+ path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
110
+ );
111
+ try {
112
+ const binDir = path.dirname(process.execPath);
113
+ const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
114
+ for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
115
+ if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
116
+ }
117
+ for (const gm of globalModuleDirs) {
118
+ candidates.push(
119
+ path.join(gm, 'ruflo', 'bin', 'cli.js'),
120
+ path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),
121
+ );
122
+ }
123
+ } catch { /* ignore */ }
124
+ } catch { /* ignore */ }
125
+ return candidates.filter((p) => {
126
+ try {
127
+ if (!fs.existsSync(p)) return false;
128
+ // A candidate's bin/cli.js can exist on disk while its compiled
129
+ // dist/ never got built (Claude Code's own plugin marketplace just
130
+ // git-clones the repo — no install/build step — so every marketplace
131
+ // install is a source-only checkout by construction). Importing
132
+ // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on
133
+ // every real command; only --version happens to survive it. Check
134
+ // for the compiled entrypoint too so a doomed candidate is skipped
135
+ // up front instead of wasting a spawn-and-fail on every render.
136
+ return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
137
+ } catch { return false; }
138
+ });
139
+ }
140
+
141
+ // Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL
142
+ // — but data is returned regardless (stale-while-revalidate). This lets us
143
+ // serve last known state (specifically the promo row) when the CLI is
144
+ // slow/unavailable, so users don't see the funnel row flicker in and out on
145
+ // cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock
146
+ // as PROMO_ROTATION_SLOT_MS — see that constant's comment for why the promo
147
+ // row needs its own freshness bound distinct from the general 60s TTL.
148
+ function readCache() {
149
+ try {
150
+ if (fs.existsSync(CACHE_FILE)) {
151
+ const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
152
+ if (raw && raw._ts && raw.data) {
153
+ const age = Date.now() - raw._ts;
154
+ return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };
155
+ }
156
+ }
157
+ } catch { /* ignore */ }
158
+ return { fresh: false, promoFresh: false, data: null };
159
+ }
160
+
161
+ function writeCache(data) {
162
+ try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }
163
+ // Also memoize any promo we saw so the row can survive future CLI hiccups.
164
+ try {
165
+ if (data && data.promo && typeof data.promo === 'object') {
166
+ fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });
167
+ fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });
168
+ }
169
+ } catch { /* ignore */ }
170
+ }
171
+
172
+ // Last resort: read a memoized promo (up to 6h old). Used when no cache and
173
+ // no CLI response is available — the row still renders, so users don't see
174
+ // the disclosure blink out. Returns null when the memo is absent, expired,
175
+ // or malformed. Never throws.
176
+ function readPromoMemo() {
177
+ try {
178
+ if (!fs.existsSync(PROMO_MEMO_FILE)) return null;
179
+ const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));
180
+ if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {
181
+ return raw.promo;
182
+ }
183
+ } catch { /* ignore */ }
184
+ return null;
185
+ }
186
+
187
+ /**
188
+ * Single source of truth: delegate to the CLI hooks statusline --json command.
189
+ * Falls back to a minimal static object on failure so the statusline still renders.
190
+ *
191
+ * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns
192
+ * (missed the .swarm/memory.db → AgentDB path), computed dddProgress wrong,
193
+ * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).
194
+ */
195
+ // Overlay the memoized promo onto any data object that's missing one. This is
196
+ // the safety net that keeps the funnel row rendered when an OLDER cached CLI
197
+ // version is picked up by npx — that older CLI succeeds but omits promo, so
198
+ // the JSON round-trips clean but without our row. We patch it back here.
199
+ function overlayMemoPromo(data) {
200
+ if (data && !data.promo) {
201
+ const memoPromo = readPromoMemo();
202
+ if (memoPromo) data.promo = memoPromo;
203
+ }
204
+ return data;
205
+ }
206
+
207
+ function getStatuslineData() {
208
+ const cache = readCache();
209
+ // Both clocks must be satisfied to skip the CLI call entirely: the general
210
+ // 60s TTL (#2337 — don't re-spawn the CLI on every rapid re-render) AND the
211
+ // tighter promo-rotation clock (this fix — don't let a still-fresh 60s
212
+ // cache silently freeze the promo/insight row across multiple 20s slots).
213
+ if (cache.fresh && cache.promoFresh) return overlayMemoPromo(cache.data);
214
+
215
+ // #2337: prefer an already-installed CLI bin via direct `node` invocation —
216
+ // no npx, no registry round-trip, no @latest re-resolve per render. Try
217
+ // every candidate that actually EXISTS (not just the first) before falling
218
+ // back to `npx --prefer-offline @claude-flow/cli` (no @latest); an existing
219
+ // but broken install (e.g. a stale marketplace checkout missing a bundled
220
+ // workspace dep) must not block trying the next one.
221
+ //
222
+ // No `2>/dev/null` here (deliberately) — the execSync call below already
223
+ // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the
224
+ // Node level regardless of shell. The redirect was redundant on POSIX and
225
+ // actively broke every candidate on Windows: cmd.exe (execSync's default
226
+ // shell there) doesn't understand /dev/null, so the CLI delegation always
227
+ // failed, silently degrading every render to buildLocalFallback() — 0%
228
+ // intelligence and an empty promo row (the memo cache that keeps the row
229
+ // populated across CLI hiccups is only ever written from a SUCCESSFUL
230
+ // delegation, so it could never get seeded on Windows either).
231
+ const cmds = resolveCliBinCandidates()
232
+ .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')
233
+ .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);
234
+ for (const cmd of cmds) {
235
+ try {
236
+ const raw = execSync(
237
+ cmd,
238
+ { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true }
239
+ ).trim();
240
+ // The CLI may emit preamble lines before the JSON — find the first '{'.
241
+ const jsonStart = raw.indexOf('{');
242
+ if (jsonStart === -1) throw new Error('no JSON in CLI output');
243
+ const data = JSON.parse(raw.slice(jsonStart));
244
+ // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)
245
+ // with real local reads, so those segments reflect actual state instead of 0.
246
+ applyLocalOverlays(data);
247
+ overlayMemoPromo(data);
248
+ writeCache(data);
249
+ return data;
250
+ } catch { /* this candidate unavailable, broken, or timed out — try the next */ }
251
+ }
252
+
253
+ // Stale-while-revalidate: if we have any cached data, keep serving it so the
254
+ // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for
255
+ // the segments the CLI JSON doesn't populate; the promo row survives.
256
+ if (cache.data) {
257
+ applyLocalOverlays(cache.data);
258
+ overlayMemoPromo(cache.data);
259
+ return cache.data;
260
+ }
261
+
262
+ // Last resort: local probes + memo. Users still see the funnel row.
263
+ return overlayMemoPromo(buildLocalFallback());
264
+ }
265
+
266
+ // Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed
267
+ // v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).
268
+ function getLocalADRCount() {
269
+ const adrDirs = [
270
+ path.join(CWD, 'v3', 'implementation', 'adrs'),
271
+ path.join(CWD, 'v3', 'docs', 'adr'),
272
+ path.join(CWD, 'docs', 'adrs'),
273
+ path.join(CWD, '.claude-flow', 'adrs'),
274
+ ];
275
+ let total = 0;
276
+ for (const dir of adrDirs) {
277
+ try {
278
+ if (fs.existsSync(dir)) {
279
+ const files = fs.readdirSync(dir).filter(function(f) {
280
+ return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\d{4}-/.test(f));
281
+ });
282
+ total += files.length;
283
+ }
284
+ } catch { /* ignore */ }
285
+ }
286
+ return { count: total, implemented: total, compliance: 0 };
287
+ }
288
+
289
+ // ─── Local overlays for segments the CLI JSON omits ──────────────
290
+ // 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.
291
+ // agentdb/tests/hooks/integration are never populated, so without these overlays
292
+ // they render as a permanent 0. Each reader is cheap and degrades to zeros.
293
+
294
+ // Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db
295
+ // (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.
296
+ // One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).
297
+ function getLocalAgentDB() {
298
+ const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };
299
+ try {
300
+ let bytes = 0;
301
+ for (const f of ['.swarm/memory.db', 'ruvector.db']) {
302
+ try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }
303
+ }
304
+ result.dbSizeKB = Math.round(bytes / 1024);
305
+
306
+ const memDb = path.join(CWD, '.swarm', 'memory.db');
307
+ if (fs.existsSync(memDb)) {
308
+ const Q = String.fromCharCode(34);
309
+ // Two INDEPENDENT statements -- do NOT combine into one. Coupling the
310
+ // vector count with the vector_indexes row count in a single statement
311
+ // meant that on a DB missing the vector_indexes table (older/agentdb-
312
+ // written DBs), the whole statement failed at PREPARE time (SQLite
313
+ // compiles the full SQL before running), so the valid memory_entries
314
+ // count was discarded too and the statusline showed Vectors 0 despite
315
+ // thousands of real vectors. Split so a missing table can only zero the
316
+ // HNSW flag, never the count. The init self-heal provisions the table so
317
+ // the flag recovers on the next ruflo init / MCP start.
318
+ const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;
319
+ const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);
320
+ if (vc) result.vectorCount = parseInt(vc, 10) || 0;
321
+ // HNSW flag: separate statement. If vector_indexes is absent, sqlite3
322
+ // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact
323
+ // original semantics: at least one index-config row present).
324
+ const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;
325
+ const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);
326
+ if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;
327
+ }
328
+ } catch { /* ignore */ }
329
+ return result;
330
+ }
331
+
332
+ // Count test files via a bounded directory walk (no file reads).
333
+ function getLocalTests() {
334
+ let testFiles = 0;
335
+ function countTests(dir, depth) {
336
+ if ((depth || 0) > 4) return;
337
+ try {
338
+ if (!fs.existsSync(dir)) return;
339
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
340
+ if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {
341
+ countTests(path.join(dir, e.name), (depth || 0) + 1);
342
+ } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {
343
+ testFiles++;
344
+ }
345
+ }
346
+ } catch { /* ignore */ }
347
+ }
348
+ for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));
349
+ return { testFiles, testCases: testFiles * 4 };
350
+ }
351
+
352
+ // Count configured hooks from project .claude/settings.json. Claude Code hooks
353
+ // have no enabled/disabled flag, so every configured hook counts as enabled.
354
+ function getLocalHooks() {
355
+ const result = { enabled: 0, total: 0 };
356
+ try {
357
+ const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));
358
+ const hooks = settings && settings.hooks;
359
+ if (hooks && typeof hooks === 'object') {
360
+ let n = 0;
361
+ for (const ev of Object.keys(hooks)) {
362
+ const groups = hooks[ev];
363
+ if (Array.isArray(groups)) {
364
+ for (const g of groups) {
365
+ if (g && Array.isArray(g.hooks)) n += g.hooks.length;
366
+ }
367
+ }
368
+ }
369
+ result.total = n;
370
+ result.enabled = n;
371
+ }
372
+ } catch { /* ignore */ }
373
+ return result;
374
+ }
375
+
376
+ // Best-effort integration block: DB presence + locally-configured stdio MCP
377
+ // servers (project .mcp.json + global ~/.claude.json). Remote connectors are
378
+ // account-managed and not present in local config, so they are not counted.
379
+ function getLocalIntegration() {
380
+ const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };
381
+ try {
382
+ for (const f of ['.swarm/memory.db', 'ruvector.db']) {
383
+ if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }
384
+ }
385
+ const names = new Set();
386
+ const projMcp = readJSON(path.join(CWD, '.mcp.json'));
387
+ if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);
388
+ const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));
389
+ if (claudeJson) {
390
+ if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);
391
+ const proj = claudeJson.projects && claudeJson.projects[CWD];
392
+ if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {
393
+ for (const k of Object.keys(proj.mcpServers)) names.add(k);
394
+ }
395
+ }
396
+ integration.mcpServers.total = names.size;
397
+ integration.mcpServers.enabled = names.size;
398
+ } catch { /* ignore */ }
399
+ return integration;
400
+ }
401
+
402
+ // Overlay every locally-derived block onto the CLI data (mutates in place).
403
+ function applyLocalOverlays(data) {
404
+ data.adrs = getLocalADRCount();
405
+ data.agentdb = getLocalAgentDB();
406
+ data.tests = getLocalTests();
407
+ data.hooks = getLocalHooks();
408
+ data.integration = getLocalIntegration();
409
+ return data;
410
+ }
411
+
412
+ // Minimal local fallback when the CLI is not installed or times out.
413
+ // Returns a structure that matches the CLI JSON schema so the renderer works.
414
+ function buildLocalFallback() {
415
+ const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
416
+
417
+ return applyLocalOverlays({
418
+ user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },
419
+ v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },
420
+ security: { status: 'NONE', cvesFixed: 0, totalCves: 0 },
421
+ swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },
422
+ system: { memoryMB: memMB, contextPct: 0, intelligencePct: 0, subAgents: 0 },
423
+ lastUpdated: new Date().toISOString(),
424
+ });
425
+ }
426
+
427
+ // ANSI colors
428
+ const c = {
429
+ reset: '\x1b[0m',
430
+ bold: '\x1b[1m',
431
+ dim: '\x1b[2m',
432
+ red: '\x1b[0;31m',
433
+ green: '\x1b[0;32m',
434
+ yellow: '\x1b[0;33m',
435
+ blue: '\x1b[0;34m',
436
+ purple: '\x1b[0;35m',
437
+ cyan: '\x1b[0;36m',
438
+ brightRed: '\x1b[1;31m',
439
+ brightGreen: '\x1b[1;32m',
440
+ brightYellow: '\x1b[1;33m',
441
+ brightBlue: '\x1b[1;34m',
442
+ brightPurple: '\x1b[1;35m',
443
+ brightCyan: '\x1b[1;36m',
444
+ brightWhite: '\x1b[1;37m',
445
+ };
446
+
447
+ // Safe execSync with strict timeout (returns empty string on failure)
448
+ function safeExec(cmd, timeoutMs) {
449
+ try {
450
+ return execSync(cmd, {
451
+ encoding: 'utf-8',
452
+ timeout: timeoutMs || 2000,
453
+ stdio: ['pipe', 'pipe', 'pipe'],
454
+ // Windows: without this, every execSync spawns cmd.exe /d /s /c which
455
+ // flashes a visible console window every render (~1/min via the 60s
456
+ // cache TTL). windowsHide runs the child in a hidden window instead.
457
+ // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening").
458
+ windowsHide: true,
459
+ }).trim();
460
+ } catch {
461
+ return '';
462
+ }
463
+ }
464
+
465
+ // Safe JSON file reader (returns null on failure)
466
+ function readJSON(filePath) {
467
+ try {
468
+ if (fs.existsSync(filePath)) {
469
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
470
+ }
471
+ } catch { /* ignore */ }
472
+ return null;
473
+ }
474
+
475
+ // ─── Git info (pure-Node / single exec — needed for branch display) ──────────
476
+
477
+ function getGitInfo() {
478
+ const result = {
479
+ name: 'user', gitBranch: '', modified: 0, untracked: 0,
480
+ staged: 0, ahead: 0, behind: 0,
481
+ };
482
+
483
+ const script = [
484
+ 'git config user.name 2>/dev/null || echo user',
485
+ 'echo "---SEP---"',
486
+ 'git branch --show-current 2>/dev/null',
487
+ 'echo "---SEP---"',
488
+ 'git status --porcelain 2>/dev/null',
489
+ 'echo "---SEP---"',
490
+ 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',
491
+ ].join('; ');
492
+
493
+ const raw = safeExec("sh -c '" + script + "'", 3000);
494
+ if (!raw) return result;
495
+
496
+ const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });
497
+ if (parts.length >= 4) {
498
+ result.name = parts[0] || 'user';
499
+ result.gitBranch = parts[1] || '';
500
+
501
+ if (parts[2]) {
502
+ for (const line of parts[2].split('\n')) {
503
+ if (!line || line.length < 2) continue;
504
+ const x = line[0], y = line[1];
505
+ if (x === '?' && y === '?') { result.untracked++; continue; }
506
+ if (x !== ' ' && x !== '?') result.staged++;
507
+ if (y !== ' ' && y !== '?') result.modified++;
508
+ }
509
+ }
510
+
511
+ const ab = (parts[3] || '0 0').split(/\s+/);
512
+ result.ahead = parseInt(ab[0]) || 0;
513
+ result.behind = parseInt(ab[1]) || 0;
514
+ }
515
+
516
+ return result;
517
+ }
518
+
519
+ // Detect model name from Claude config (pure file reads, no exec)
520
+ function getModelName() {
521
+ try {
522
+ const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));
523
+ if (claudeConfig && claudeConfig.projects) {
524
+ for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
525
+ if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {
526
+ const usage = projectConfig.lastModelUsage;
527
+ if (usage) {
528
+ const ids = Object.keys(usage);
529
+ if (ids.length > 0) {
530
+ let modelId = ids[ids.length - 1];
531
+ let latest = 0;
532
+ for (const id of ids) {
533
+ const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
534
+ if (ts > latest) { latest = ts; modelId = id; }
535
+ }
536
+ if (modelId.includes('opus')) return 'Opus 4.8';
537
+ if (modelId.includes('sonnet')) return 'Sonnet 4.6';
538
+ if (modelId.includes('haiku')) return 'Haiku 4.5';
539
+ return modelId.split('-').slice(1, 3).join(' ');
540
+ }
541
+ }
542
+ break;
543
+ }
544
+ }
545
+ }
546
+ } catch { /* ignore */ }
547
+
548
+ // Fallback: settings.json model field
549
+ const settings = getSettings();
550
+ if (settings && settings.model) {
551
+ const m = settings.model;
552
+ if (m.includes('opus')) return 'Opus 4.8';
553
+ if (m.includes('sonnet')) return 'Sonnet 4.6';
554
+ if (m.includes('haiku')) return 'Haiku 4.5';
555
+ }
556
+ return 'Claude Code';
557
+ }
558
+
559
+ // ─── Stdin reader (Claude Code pipes session JSON) ──────────────
560
+ // Claude Code sends session JSON via stdin. Read synchronously so the
561
+ // script works both when invoked by Claude Code (stdin has JSON) and
562
+ // when run manually from terminal (stdin is empty/tty).
563
+ let _stdinData = null;
564
+ function getStdinData() {
565
+ if (_stdinData !== undefined && _stdinData !== null) return _stdinData;
566
+ try {
567
+ if (process.stdin.isTTY) { _stdinData = null; return null; }
568
+ const chunks = [];
569
+ const buf = Buffer.alloc(4096);
570
+ let bytesRead;
571
+ try {
572
+ while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {
573
+ chunks.push(buf.slice(0, bytesRead));
574
+ }
575
+ } catch { /* EOF or read error */ }
576
+ const raw = Buffer.concat(chunks).toString('utf-8').trim();
577
+ _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;
578
+ } catch {
579
+ _stdinData = null;
580
+ }
581
+ return _stdinData;
582
+ }
583
+
584
+ function getModelFromStdin() {
585
+ const data = getStdinData();
586
+ return (data && data.model && data.model.display_name) ? data.model.display_name : null;
587
+ }
588
+
589
+ function getContextFromStdin() {
590
+ const data = getStdinData();
591
+ if (data && data.context_window) {
592
+ return { usedPct: Math.floor(data.context_window.used_percentage || 0) };
593
+ }
594
+ return null;
595
+ }
596
+
597
+ function getCostFromStdin() {
598
+ const data = getStdinData();
599
+ if (data && data.cost) {
600
+ const durationMs = data.cost.total_duration_ms || 0;
601
+ const mins = Math.floor(durationMs / 60000);
602
+ const secs = Math.floor((durationMs % 60000) / 1000);
603
+ return {
604
+ costUsd: data.cost.total_cost_usd || 0,
605
+ duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',
606
+ };
607
+ }
608
+ return null;
609
+ }
610
+
611
+ // Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").
612
+ // Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately
613
+ // simple (no prerelease/build-metadata handling) — this only orders local
614
+ // package.json versions against each other, never anything untrusted from
615
+ // a payload, so a full semver implementation would be dead weight here.
616
+ function compareVersions(a, b) {
617
+ const pa = String(a).split('.').map((n) => parseInt(n, 10));
618
+ const pb = String(b).split('.').map((n) => parseInt(n, 10));
619
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
620
+ const na = Number.isFinite(pa[i]) ? pa[i] : 0;
621
+ const nb = Number.isFinite(pb[i]) ? pb[i] : 0;
622
+ if (na !== nb) return na - nb;
623
+ }
624
+ return 0;
625
+ }
626
+
627
+ function getPkgVersion() {
628
+ // Baked in at generation time from the real running CLI's own resolved
629
+ // version (see generateStatuslineScript()'s doc comment) — correct even
630
+ // when this renders via a pure npx invocation with no local install for
631
+ // the candidate scan below to find.
632
+ let ver = "3.28.0";
633
+ try {
634
+ const home = os.homedir();
635
+ const pkgPaths = [
636
+ path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),
637
+ path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),
638
+ path.join(CWD, 'node_modules', 'ruflo', 'package.json'),
639
+ path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),
640
+ ];
641
+ // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the
642
+ // probes above all miss and the version falls back to the hard-coded default.
643
+ // Derive the global node_modules dir from the running node binary (no npm spawn —
644
+ // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows
645
+ // (bin/node_modules) layouts.
646
+ try {
647
+ const binDir = path.dirname(process.execPath);
648
+ const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
649
+ // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from
650
+ // the node binary location, so the binDir-derived probes above all miss. Also
651
+ // probe the npm prefix from the environment and the common ~/.npm-global default.
652
+ for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
653
+ if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
654
+ }
655
+ for (const gm of globalModuleDirs) {
656
+ pkgPaths.push(
657
+ path.join(gm, 'ruflo', 'package.json'),
658
+ path.join(gm, '@claude-flow', 'cli', 'package.json'),
659
+ );
660
+ }
661
+ } catch { /* ignore */ }
662
+ // Pick the HIGHEST version among every candidate that exists, not the
663
+ // first one found. The marketplace plugin path is probed first (list
664
+ // order above), but Claude Code's own plugin marketplace mechanism
665
+ // syncs on its own git-pull cadence, independent of npm publishes — a
666
+ // freshly-published npm version can sit alongside a stale marketplace
667
+ // checkout for a while (observed live: marketplace one release behind
668
+ // right after a publish). Taking the first EXISTING candidate meant the
669
+ // header could show a stale version even when a newer install (e.g.
670
+ // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.
671
+ let found = false;
672
+ for (const p of pkgPaths) {
673
+ if (!fs.existsSync(p)) continue;
674
+ try {
675
+ const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
676
+ if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
677
+ if (!found || compareVersions(pkg.version, ver) > 0) ver = pkg.version;
678
+ found = true;
679
+ }
680
+ } catch { /* ignore */ }
681
+ }
682
+ } catch { /* ignore */ }
683
+ return ver;
684
+ }
685
+
686
+ // ─── Rendering ──────────────────────────────────────────────────
687
+
688
+ function progressBar(current, total) {
689
+ const width = 5;
690
+ const filled = Math.round((current / total) * width);
691
+ return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
692
+ }
693
+
694
+ function generateStatusline() {
695
+ const d = getStatuslineData();
696
+ const git = getGitInfo();
697
+ const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
698
+ const ctxInfo = getContextFromStdin();
699
+ const costInfo = getCostFromStdin();
700
+ // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard
701
+ // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted
702
+ // .cjs artifact — without it the header silently reverts to a hard-coded
703
+ // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.
704
+ const RUFLO_VERSION = getPkgVersion();
705
+
706
+ const progress = d.v3Progress || {};
707
+ const security = d.security || {};
708
+ const swarm = d.swarm || {};
709
+ const system = d.system || {};
710
+ const adrs = d.adrs || {};
711
+ const hooks = d.hooks || {};
712
+ const agentdb = d.agentdb || {};
713
+ const tests = d.tests || {};
714
+
715
+ const domainsCompleted = progress.domainsCompleted || 0;
716
+ const totalDomains = progress.totalDomains || 5;
717
+ const dddProgress = progress.dddProgress || 0;
718
+ const patternsLearned = progress.patternsLearned || 0;
719
+ const activeAgents = swarm.activeAgents || 0;
720
+ const maxAgents = swarm.maxAgents || CONFIG.maxAgents;
721
+ const coordinationActive = swarm.coordinationActive || false;
722
+ const intelligencePct = system.intelligencePct || 0;
723
+ const memoryMB = system.memoryMB || 0;
724
+ const subAgents = system.subAgents || 0;
725
+ const cvesFixed = security.cvesFixed || 0;
726
+ const totalCves = security.totalCves || 0;
727
+ const secStatus = security.status || 'NONE';
728
+ const adrCount = adrs.count || 0;
729
+ const adrImpl = adrs.implemented || 0;
730
+ const hooksEnabled = hooks.enabled || 0;
731
+ const hooksTotal = hooks.total || 0;
732
+ const vectorCount = agentdb.vectorCount || 0;
733
+ const hasHnsw = agentdb.hasHnsw || false;
734
+ const dbSizeKB = agentdb.dbSizeKB || 0;
735
+ const testFiles = tests.testFiles || 0;
736
+ const testCases = tests.testCases || testFiles * 4;
737
+
738
+ const lines = [];
739
+
740
+ // 3-line design (fits Claude Code's visible statusline area — line 4+ gets
741
+ // replaced by the system guidance / input prompt line):
742
+ // Line 1 — Header (RuFlo version · git · model · timing · context · cost)
743
+ // Line 2 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health)
744
+ // Line 3 — Promo / disclosure row (funnel surface, ADR-301)
745
+
746
+ // ─── Line 1: header ────────────────────────────────────────────
747
+ let header = c.bold + c.brightPurple + '▊ RuFlo V' + RUFLO_VERSION + ' ' + c.reset;
748
+ header += (coordinationActive ? c.brightCyan : c.dim) + '● ' + c.brightCyan + git.name + c.reset;
749
+ if (git.gitBranch) {
750
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightBlue + '⏇ ' + git.gitBranch + c.reset;
751
+ const changes = git.modified + git.staged + git.untracked;
752
+ if (changes > 0) {
753
+ let ind = '';
754
+ if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;
755
+ if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;
756
+ if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;
757
+ header += ' ' + ind;
758
+ }
759
+ if (git.ahead > 0) header += ' ' + c.brightGreen + '↑' + git.ahead + c.reset;
760
+ if (git.behind > 0) header += ' ' + c.brightRed + '↓' + git.behind + c.reset;
761
+ }
762
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.purple + modelName + c.reset;
763
+ const duration = costInfo ? costInfo.duration : '';
764
+ if (duration) header += ' ' + c.dim + '│' + c.reset + ' ' + c.cyan + '⏱ ' + duration + c.reset;
765
+ if (ctxInfo && ctxInfo.usedPct > 0) {
766
+ const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;
767
+ header += ' ' + c.dim + '│' + c.reset + ' ' + ctxColor + '● ' + ctxInfo.usedPct + '% ctx' + c.reset;
768
+ }
769
+ if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {
770
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;
771
+ }
772
+ lines.push(header);
773
+
774
+ // ─── Line 2: compressed ops ────────────────────────────────────
775
+ // Everything actionable in one dense row. Show only what changes what you
776
+ // do next; diagnostic detail moves to `ruflo status --verbose`.
777
+ const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;
778
+ const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;
779
+ const intellColor = intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;
780
+ const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset + ' ' : c.dim + '○' + c.reset + ' ';
781
+ const cvesClean = totalCves === 0 || cvesFixed === totalCves;
782
+ const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && cvesClean;
783
+ const opsParts = [];
784
+ opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);
785
+ if (subAgents > 0) opsParts.push(c.brightPurple + '👥 ' + subAgents + c.reset);
786
+ opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);
787
+ opsParts.push(intellColor + '🧠 ' + intelligencePct + '%' + c.reset);
788
+ opsParts.push(c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset);
789
+ // Health: one glyph when green, terse copy when there's something to act on.
790
+ if (healthAllGreen) {
791
+ opsParts.push(c.brightGreen + '🛡 ✓' + c.reset);
792
+ } else {
793
+ if (secStatus === 'PENDING') opsParts.push(c.brightYellow + '🛡 scan pending' + c.reset);
794
+ else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + '🛡 scanning…' + c.reset);
795
+ else if (secStatus === 'STALE') opsParts.push(c.brightYellow + '🛡 scan stale' + c.reset);
796
+ else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + '🛡 ' + secStatus.toLowerCase() + c.reset);
797
+ if (totalCves > 0 && cvesFixed < totalCves) {
798
+ const unfixed = totalCves - cvesFixed;
799
+ opsParts.push(c.brightRed + '⚠ ' + unfixed + ' CVE' + (unfixed === 1 ? '' : 's') + c.reset);
800
+ }
801
+ }
802
+ lines.push(opsParts.join(' ' + c.dim + '·' + c.reset + ' '));
803
+
804
+ // ─── Line 3: promo / disclosure / insight ───────────────────────
805
+ // Colored by content kind so it reads as *what it is*, not as noise:
806
+ // disclosure → brightCyan (announcement / capability link)
807
+ // promotional → brightPurple (Cognitum sponsor spot)
808
+ // educational → yellow (a tip)
809
+ // insight → brightRed (environment/task-aware, local, actionable —
810
+ // distinct from remote content on purpose)
811
+ const promoRow = getPromoRow(d);
812
+ if (promoRow) {
813
+ const kind = (d && d.promo && d.promo.kind) || 'disclosure';
814
+ const promoColor = kind === 'promotional' ? c.brightPurple
815
+ : kind === 'educational' ? c.yellow
816
+ : kind === 'insight' ? c.brightRed
817
+ : c.brightCyan;
818
+ lines.push(promoColor + promoRow + c.reset);
819
+ }
820
+
821
+ // Trailing blank line so Claude Code's input prompt gets breathing room
822
+ // instead of butting directly against the last statusline row.
823
+ return lines.join('\n') + '\n';
824
+ }
825
+
826
+ // ─── Funnel promo row (ADR-301) ─────────────────────────────────
827
+ // Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so
828
+ // no message can smuggle a link to an unapproved host.
829
+ //
830
+ // The final destination hosts (cognitum.one / agentics.org) AND the
831
+ // click-redirect host are both allowlisted here: promo.ts routes every
832
+ // clickable message through the server-side click-redirect (ADR-311 §7)
833
+ // so promo_open + geo are captured before the 302 to the real target —
834
+ // so the OSC 8 link the renderer emits points at the redirect host, not
835
+ // the final destination directly.
836
+ const PROMO_LINK_HOSTS = new Set([
837
+ 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
838
+ // agentics.org — OSS foundation, distinct sponsor domain. Kept in sync
839
+ // with messages.ts ALLOWED_URL_HOSTS.
840
+ 'agentics.org', 'www.agentics.org',
841
+ // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw
842
+ // Cloud Run hostname is allowlisted too since event-transport.ts /
843
+ // message-transport.ts / attribution.ts currently point at it as a TEMP
844
+ // fallback while the domain mapping's cert provisions).
845
+ 'funnel.ruv.io',
846
+ 'cognitum-analytics-63rzcdswba-uc.a.run.app',
847
+ ]);
848
+
849
+ // Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles
850
+ // raw OSC 8 (see anthropics/claude-code#27047) — opt in via env if wrapped.
851
+ function terminalSupportsHyperlinks() {
852
+ if (process.env.CI || process.env.GITHUB_ACTIONS) return false;
853
+ if (process.env.TERM === 'dumb') return false;
854
+ if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;
855
+ if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;
856
+ return true;
857
+ }
858
+
859
+ // Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw
860
+ // label whenever the URL is not an allowlisted https target, when the terminal
861
+ // can't render hyperlinks, or when parsing fails — a broken link must never
862
+ // leave a raw URL or stray escape in the statusline output.
863
+ function safeTerminalLink(label, url) {
864
+ if (!terminalSupportsHyperlinks()) return label;
865
+ if (typeof url !== 'string' || url.length === 0) return label;
866
+ let parsed;
867
+ try { parsed = new URL(url); } catch { return label; }
868
+ if (parsed.protocol !== 'https:') return label;
869
+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;
870
+ const cleanLabel = String(label).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');
871
+ if (cleanLabel.length === 0) return label;
872
+ const ESC = '\u001b';
873
+ return ESC + ']8;;' + parsed.href + ESC + '\\' + cleanLabel + ESC + ']8;;' + ESC + '\\';
874
+ }
875
+
876
+ function getPromoRow(d) {
877
+ try {
878
+ if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
879
+ if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
880
+ const promo = d && d.promo;
881
+ if (!promo || typeof promo.text !== 'string') return null;
882
+ // Strip control chars / ANSI / bidi overrides — promo copy is data and
883
+ // must never emit its own terminal sequences. Hard-cap length AFTER the
884
+ // strip; append an ellipsis when the cap fires so the row visibly reads
885
+ // as truncated instead of chopping a word mid-character (was: silent
886
+ // slice(0,100) that could produce output that looked like corrupt data).
887
+ const MAX_LEN = 100;
888
+ const sanitized = promo.text
889
+ .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
890
+ ;
891
+ const text = (sanitized.length > MAX_LEN ? sanitized.slice(0, MAX_LEN - 1).trimEnd() + '…' : sanitized).trim();
892
+ if (text.length === 0) return null;
893
+ // Split the label from the trailing "· manage: ruflo settings" instruction
894
+ // so each part gets styling that matches what it actually IS:
895
+ // 1. label — OSC 8 hyperlink + underline. A real clickable link.
896
+ // 2. "manage:" — dim. Just a connector word, no action implied.
897
+ // 3. "ruflo settings" — bold/bright, NOT underlined. This is a shell
898
+ // command the user TYPES, not a link they CLICK — a terminal can
899
+ // never safely execute a command from a click (that would let any
900
+ // server-served message run arbitrary commands), so we deliberately
901
+ // avoid the underline/OSC8 cues that imply "clickable". Bold+bright
902
+ // instead signals "this is the important bit — copy/type it".
903
+ // Educational tips have no manage tail and no URL — plain text through.
904
+ const manageIdx = text.indexOf(' · manage: ');
905
+ const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;
906
+ const manageWord = manageIdx > 0 ? ' · manage: ' : '';
907
+ const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';
908
+ const UL_ON = '\u001b[4m';
909
+ const UL_OFF = '\u001b[24m';
910
+ const DIM_ON = '\u001b[2m';
911
+ const DIM_OFF = '\u001b[22m';
912
+ const BOLD_ON = '\u001b[1m';
913
+ const BOLD_OFF = '\u001b[22m';
914
+ const FG_BRIGHT_WHITE = '';
915
+ // Reset FG to default so the caller's row-color code resumes coloring the
916
+ // rest of the row after the command portion. Without this the row-color
917
+ // escape wouldn't visibly re-apply because we already emitted an explicit FG.
918
+ const FG_DEFAULT = '';
919
+ // Some hosts (Claude Code's Windows UI, cmd.exe, older mintty) don't
920
+ // render OSC 8 hyperlinks as clickable — the label just underlines and
921
+ // clicks do nothing. Append a "(domain)" suffix so the destination is
922
+ // visible/copyable everywhere. Wrap the suffix in OSC 8 too so terminals
923
+ // that DO support hyperlinks give users TWO click targets (label AND
924
+ // domain hint) instead of one — some Windows hosts render one but not
925
+ // the other depending on how the statusline row is parsed.
926
+ // Only for URLs (not educational tips), and only when the label doesn't
927
+ // already end in the domain to avoid duplication.
928
+ let visibleUrlHint = '';
929
+ if (promo.url) {
930
+ try {
931
+ const host = new URL(promo.url).hostname.replace(/^www\./, '');
932
+ // Strip the click-redirect wrapper so users see the FINAL destination,
933
+ // not funnel.ruv.io. If the URL is /v1/click/<id>?to=<encoded>, pull the target.
934
+ let displayHost = host;
935
+ try {
936
+ const to = new URL(promo.url).searchParams.get('to');
937
+ if (to) displayHost = new URL(to).hostname.replace(/^www\./, '');
938
+ } catch { /* not a click-redirect, keep the raw host */ }
939
+ if (displayHost && !label.toLowerCase().endsWith(displayHost.toLowerCase())) {
940
+ // safeTerminalLink returns the plain string if URL isn't allowlisted
941
+ // or the terminal can't do OSC 8 — either way the domain stays visible.
942
+ const clickableDomain = safeTerminalLink(displayHost, promo.url);
943
+ visibleUrlHint = DIM_ON + ' (' + clickableDomain + ')' + DIM_OFF;
944
+ }
945
+ } catch { /* malformed URL — omit hint, never break the row */ }
946
+ }
947
+ // "Entire row clickable" (user request) — wrap the whole assembled
948
+ // string in ONE OSC 8 hyperlink instead of just the label. The command
949
+ // portion keeps its bold + bright-white treatment (no underline) so it
950
+ // still VISUALLY reads as a shell command the user should type, not a
951
+ // link — but if the user clicks anywhere on the row (label, domain
952
+ // hint, connector, even the command text), the terminal opens the URL.
953
+ // Clicking DOES NOT execute the command; it just opens the target URL,
954
+ // which is safe. Terminals that ignore OSC 8 render the whole row as
955
+ // styled text and no click behavior — the previous fallback (visible
956
+ // domain suffix) still keeps the destination readable.
957
+ const wrapWholeRowInHyperlink = (assembled) => {
958
+ if (!promo.url) return assembled;
959
+ if (!terminalSupportsHyperlinks()) return assembled;
960
+ let parsed;
961
+ try { parsed = new URL(promo.url); } catch { return assembled; }
962
+ if (parsed.protocol !== 'https:') return assembled;
963
+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return assembled;
964
+ const ESC = '';
965
+ return ESC + ']8;;' + parsed.href + ESC + '\\' + assembled + ESC + ']8;;' + ESC + '\\';
966
+ };
967
+ // Visual styling stays per-part. We only add the OSC 8 wrap around the
968
+ // combined string, so the whole row is one click target.
969
+ const labelStyled = promo.url ? UL_ON + label + UL_OFF : label;
970
+ if (!command) return wrapWholeRowInHyperlink(labelStyled + visibleUrlHint);
971
+ return wrapWholeRowInHyperlink(
972
+ labelStyled + visibleUrlHint
973
+ + DIM_ON + manageWord + DIM_OFF
974
+ + BOLD_ON + FG_BRIGHT_WHITE + command + FG_DEFAULT + BOLD_OFF
975
+ );
976
+ } catch (e) {
977
+ return null; // the promo row must never break the statusline
978
+ }
979
+ }
980
+
981
+ // JSON output — delegates to CLI for accuracy; caller can use --json flag
982
+ function generateJSON() {
983
+ const d = getStatuslineData();
984
+ const git = getGitInfo();
985
+ return Object.assign({}, d, {
986
+ user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),
987
+ git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },
988
+ lastUpdated: new Date().toISOString(),
989
+ });
990
+ }
991
+
992
+ // ─── Main ───────────────────────────────────────────────────────
993
+ if (process.argv.includes('--json')) {
994
+ console.log(JSON.stringify(generateJSON(), null, 2));
995
+ } else if (process.argv.includes('--compact')) {
996
+ console.log(JSON.stringify(generateJSON()));
997
+ } else {
998
+ console.log(generateStatusline());
999
+ }