@claude-flow/cli 3.42.1 → 3.42.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (458) hide show
  1. package/.claude/agents/analysis/analyze-code-quality.md +178 -178
  2. package/.claude/agents/analysis/code-analyzer.md +209 -209
  3. package/.claude/agents/analysis/code-review/analyze-code-quality.md +178 -178
  4. package/.claude/agents/architecture/arch-system-design.md +156 -156
  5. package/.claude/agents/architecture/system-design/arch-system-design.md +154 -154
  6. package/.claude/agents/browser/browser-agent.yaml +182 -182
  7. package/.claude/agents/consensus/byzantine-coordinator.md +62 -62
  8. package/.claude/agents/consensus/crdt-synchronizer.md +996 -996
  9. package/.claude/agents/consensus/gossip-coordinator.md +62 -62
  10. package/.claude/agents/consensus/performance-benchmarker.md +850 -850
  11. package/.claude/agents/consensus/quorum-manager.md +822 -822
  12. package/.claude/agents/consensus/raft-manager.md +62 -62
  13. package/.claude/agents/consensus/security-manager.md +621 -621
  14. package/.claude/agents/core/planner.md +374 -374
  15. package/.claude/agents/custom/test-long-runner.md +44 -44
  16. package/.claude/agents/data/data-ml-model.md +444 -444
  17. package/.claude/agents/data/ml/data-ml-model.md +192 -192
  18. package/.claude/agents/development/backend/dev-backend-api.md +141 -141
  19. package/.claude/agents/development/dev-backend-api.md +344 -344
  20. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +163 -163
  21. package/.claude/agents/devops/ops-cicd-github.md +164 -164
  22. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +173 -173
  23. package/.claude/agents/documentation/docs-api-openapi.md +354 -354
  24. package/.claude/agents/flow-nexus/app-store.md +87 -87
  25. package/.claude/agents/flow-nexus/authentication.md +68 -68
  26. package/.claude/agents/flow-nexus/challenges.md +80 -80
  27. package/.claude/agents/flow-nexus/neural-network.md +87 -87
  28. package/.claude/agents/flow-nexus/payments.md +82 -82
  29. package/.claude/agents/flow-nexus/sandbox.md +75 -75
  30. package/.claude/agents/flow-nexus/swarm.md +75 -75
  31. package/.claude/agents/flow-nexus/user-tools.md +95 -95
  32. package/.claude/agents/flow-nexus/workflow.md +83 -83
  33. package/.claude/agents/github/code-review-swarm.md +377 -377
  34. package/.claude/agents/github/github-modes.md +172 -172
  35. package/.claude/agents/github/issue-tracker.md +575 -575
  36. package/.claude/agents/github/multi-repo-swarm.md +552 -552
  37. package/.claude/agents/github/pr-manager.md +437 -437
  38. package/.claude/agents/github/project-board-sync.md +508 -508
  39. package/.claude/agents/github/release-manager.md +604 -604
  40. package/.claude/agents/github/release-swarm.md +582 -582
  41. package/.claude/agents/github/repo-architect.md +397 -397
  42. package/.claude/agents/github/swarm-issue.md +572 -572
  43. package/.claude/agents/github/swarm-pr.md +427 -427
  44. package/.claude/agents/github/sync-coordinator.md +451 -451
  45. package/.claude/agents/github/workflow-automation.md +902 -902
  46. package/.claude/agents/goal/agent.md +815 -815
  47. package/.claude/agents/optimization/benchmark-suite.md +664 -664
  48. package/.claude/agents/optimization/load-balancer.md +430 -430
  49. package/.claude/agents/optimization/performance-monitor.md +671 -671
  50. package/.claude/agents/optimization/resource-allocator.md +673 -673
  51. package/.claude/agents/optimization/topology-optimizer.md +807 -807
  52. package/.claude/agents/payments/agentic-payments.md +126 -126
  53. package/.claude/agents/sona/sona-learning-optimizer.md +74 -74
  54. package/.claude/agents/sparc/architecture.md +698 -698
  55. package/.claude/agents/sparc/pseudocode.md +519 -519
  56. package/.claude/agents/sparc/refinement.md +801 -801
  57. package/.claude/agents/sparc/specification.md +477 -477
  58. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +224 -224
  59. package/.claude/agents/specialized/spec-mobile-react-native.md +226 -226
  60. package/.claude/agents/sublinear/consensus-coordinator.md +337 -337
  61. package/.claude/agents/sublinear/matrix-optimizer.md +184 -184
  62. package/.claude/agents/sublinear/pagerank-analyzer.md +298 -298
  63. package/.claude/agents/sublinear/performance-optimizer.md +367 -367
  64. package/.claude/agents/sublinear/trading-predictor.md +245 -245
  65. package/.claude/agents/swarm/adaptive-coordinator.md +1126 -1126
  66. package/.claude/agents/swarm/hierarchical-coordinator.md +709 -709
  67. package/.claude/agents/swarm/mesh-coordinator.md +962 -962
  68. package/.claude/agents/templates/automation-smart-agent.md +204 -204
  69. package/.claude/agents/templates/base-template-generator.md +289 -289
  70. package/.claude/agents/templates/coordinator-swarm-init.md +89 -89
  71. package/.claude/agents/templates/github-pr-manager.md +176 -176
  72. package/.claude/agents/templates/implementer-sparc-coder.md +258 -258
  73. package/.claude/agents/templates/memory-coordinator.md +186 -186
  74. package/.claude/agents/templates/orchestrator-task.md +138 -138
  75. package/.claude/agents/templates/performance-analyzer.md +198 -198
  76. package/.claude/agents/templates/sparc-coordinator.md +513 -513
  77. package/.claude/agents/testing/production-validator.md +394 -394
  78. package/.claude/agents/testing/tdd-london-swarm.md +243 -243
  79. package/.claude/agents/v3/aidefence-guardian.md +282 -282
  80. package/.claude/agents/v3/claims-authorizer.md +208 -208
  81. package/.claude/agents/v3/collective-intelligence-coordinator.md +993 -993
  82. package/.claude/agents/v3/ddd-domain-expert.md +220 -220
  83. package/.claude/agents/v3/injection-analyst.md +236 -236
  84. package/.claude/agents/v3/performance-engineer.md +1233 -1233
  85. package/.claude/agents/v3/pii-detector.md +151 -151
  86. package/.claude/agents/v3/reasoningbank-learner.md +213 -213
  87. package/.claude/agents/v3/security-architect-aidefence.md +410 -410
  88. package/.claude/agents/v3/security-architect.md +867 -867
  89. package/.claude/agents/v3/swarm-memory-manager.md +157 -157
  90. package/.claude/agents/v3/v3-integration-architect.md +205 -205
  91. package/.claude/commands/agents/README.md +50 -50
  92. package/.claude/commands/agents/agent-capabilities.md +140 -140
  93. package/.claude/commands/agents/agent-coordination.md +28 -28
  94. package/.claude/commands/agents/agent-spawning.md +28 -28
  95. package/.claude/commands/agents/agent-types.md +216 -216
  96. package/.claude/commands/agents/health.md +139 -139
  97. package/.claude/commands/agents/list.md +100 -100
  98. package/.claude/commands/agents/logs.md +130 -130
  99. package/.claude/commands/agents/metrics.md +122 -122
  100. package/.claude/commands/agents/pool.md +127 -127
  101. package/.claude/commands/agents/spawn.md +140 -140
  102. package/.claude/commands/agents/status.md +115 -115
  103. package/.claude/commands/agents/stop.md +102 -102
  104. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +53 -53
  105. package/.claude/commands/analysis/README.md +9 -9
  106. package/.claude/commands/analysis/bottleneck-detect.md +162 -162
  107. package/.claude/commands/analysis/performance-bottlenecks.md +58 -58
  108. package/.claude/commands/analysis/performance-report.md +25 -25
  109. package/.claude/commands/analysis/token-efficiency.md +44 -44
  110. package/.claude/commands/analysis/token-usage.md +25 -25
  111. package/.claude/commands/automation/README.md +9 -9
  112. package/.claude/commands/automation/auto-agent.md +122 -122
  113. package/.claude/commands/automation/self-healing.md +105 -105
  114. package/.claude/commands/automation/session-memory.md +89 -89
  115. package/.claude/commands/automation/smart-agents.md +72 -72
  116. package/.claude/commands/automation/smart-spawn.md +25 -25
  117. package/.claude/commands/automation/workflow-select.md +25 -25
  118. package/.claude/commands/claude-flow-help.md +103 -103
  119. package/.claude/commands/claude-flow-memory.md +107 -107
  120. package/.claude/commands/claude-flow-swarm.md +205 -205
  121. package/.claude/commands/coordination/README.md +9 -9
  122. package/.claude/commands/coordination/agent-spawn.md +25 -25
  123. package/.claude/commands/coordination/init.md +44 -44
  124. package/.claude/commands/coordination/orchestrate.md +43 -43
  125. package/.claude/commands/coordination/spawn.md +45 -45
  126. package/.claude/commands/coordination/swarm-init.md +85 -85
  127. package/.claude/commands/coordination/task-orchestrate.md +25 -25
  128. package/.claude/commands/github/README.md +11 -11
  129. package/.claude/commands/github/code-review-swarm.md +513 -513
  130. package/.claude/commands/github/code-review.md +25 -25
  131. package/.claude/commands/github/github-modes.md +146 -146
  132. package/.claude/commands/github/github-swarm.md +121 -121
  133. package/.claude/commands/github/issue-tracker.md +291 -291
  134. package/.claude/commands/github/issue-triage.md +25 -25
  135. package/.claude/commands/github/multi-repo-swarm.md +518 -518
  136. package/.claude/commands/github/pr-enhance.md +26 -26
  137. package/.claude/commands/github/pr-manager.md +169 -169
  138. package/.claude/commands/github/project-board-sync.md +470 -470
  139. package/.claude/commands/github/release-manager.md +339 -339
  140. package/.claude/commands/github/release-swarm.md +543 -543
  141. package/.claude/commands/github/repo-analyze.md +25 -25
  142. package/.claude/commands/github/repo-architect.md +366 -366
  143. package/.claude/commands/github/swarm-issue.md +484 -484
  144. package/.claude/commands/github/swarm-pr.md +287 -287
  145. package/.claude/commands/github/sync-coordinator.md +302 -302
  146. package/.claude/commands/github/workflow-automation.md +441 -441
  147. package/.claude/commands/hive-mind/README.md +17 -17
  148. package/.claude/commands/hive-mind/hive-mind-consensus.md +8 -8
  149. package/.claude/commands/hive-mind/hive-mind-init.md +18 -18
  150. package/.claude/commands/hive-mind/hive-mind-memory.md +8 -8
  151. package/.claude/commands/hive-mind/hive-mind-metrics.md +8 -8
  152. package/.claude/commands/hive-mind/hive-mind-resume.md +8 -8
  153. package/.claude/commands/hive-mind/hive-mind-sessions.md +8 -8
  154. package/.claude/commands/hive-mind/hive-mind-spawn.md +21 -21
  155. package/.claude/commands/hive-mind/hive-mind-status.md +8 -8
  156. package/.claude/commands/hive-mind/hive-mind-stop.md +8 -8
  157. package/.claude/commands/hive-mind/hive-mind-wizard.md +8 -8
  158. package/.claude/commands/hive-mind/hive-mind.md +27 -27
  159. package/.claude/commands/hooks/README.md +11 -11
  160. package/.claude/commands/hooks/overview.md +57 -57
  161. package/.claude/commands/hooks/post-edit.md +117 -117
  162. package/.claude/commands/hooks/post-task.md +112 -112
  163. package/.claude/commands/hooks/pre-edit.md +113 -113
  164. package/.claude/commands/hooks/pre-task.md +111 -111
  165. package/.claude/commands/hooks/session-end.md +118 -118
  166. package/.claude/commands/hooks/setup.md +102 -102
  167. package/.claude/commands/memory/README.md +9 -9
  168. package/.claude/commands/memory/memory-persist.md +25 -25
  169. package/.claude/commands/memory/memory-search.md +25 -25
  170. package/.claude/commands/memory/memory-usage.md +25 -25
  171. package/.claude/commands/memory/neural.md +47 -47
  172. package/.claude/commands/monitoring/README.md +9 -9
  173. package/.claude/commands/monitoring/agent-metrics.md +25 -25
  174. package/.claude/commands/monitoring/agents.md +44 -44
  175. package/.claude/commands/monitoring/real-time-view.md +25 -25
  176. package/.claude/commands/monitoring/status.md +46 -46
  177. package/.claude/commands/monitoring/swarm-monitor.md +25 -25
  178. package/.claude/commands/optimization/README.md +9 -9
  179. package/.claude/commands/optimization/auto-topology.md +61 -61
  180. package/.claude/commands/optimization/cache-manage.md +25 -25
  181. package/.claude/commands/optimization/parallel-execute.md +25 -25
  182. package/.claude/commands/optimization/parallel-execution.md +49 -49
  183. package/.claude/commands/optimization/topology-optimize.md +25 -25
  184. package/.claude/commands/pair/README.md +260 -260
  185. package/.claude/commands/pair/commands.md +545 -545
  186. package/.claude/commands/pair/config.md +509 -509
  187. package/.claude/commands/pair/examples.md +511 -511
  188. package/.claude/commands/pair/modes.md +347 -347
  189. package/.claude/commands/pair/session.md +406 -406
  190. package/.claude/commands/pair/start.md +208 -208
  191. package/.claude/commands/sparc/analyzer.md +51 -51
  192. package/.claude/commands/sparc/architect.md +53 -53
  193. package/.claude/commands/sparc/ask.md +97 -97
  194. package/.claude/commands/sparc/batch-executor.md +54 -54
  195. package/.claude/commands/sparc/code.md +89 -89
  196. package/.claude/commands/sparc/coder.md +54 -54
  197. package/.claude/commands/sparc/debug.md +83 -83
  198. package/.claude/commands/sparc/debugger.md +54 -54
  199. package/.claude/commands/sparc/designer.md +53 -53
  200. package/.claude/commands/sparc/devops.md +109 -109
  201. package/.claude/commands/sparc/docs-writer.md +80 -80
  202. package/.claude/commands/sparc/documenter.md +54 -54
  203. package/.claude/commands/sparc/innovator.md +54 -54
  204. package/.claude/commands/sparc/integration.md +83 -83
  205. package/.claude/commands/sparc/mcp.md +117 -117
  206. package/.claude/commands/sparc/memory-manager.md +54 -54
  207. package/.claude/commands/sparc/optimizer.md +54 -54
  208. package/.claude/commands/sparc/orchestrator.md +131 -131
  209. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -83
  210. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -83
  211. package/.claude/commands/sparc/researcher.md +54 -54
  212. package/.claude/commands/sparc/reviewer.md +54 -54
  213. package/.claude/commands/sparc/security-review.md +80 -80
  214. package/.claude/commands/sparc/sparc-modes.md +174 -174
  215. package/.claude/commands/sparc/sparc.md +111 -111
  216. package/.claude/commands/sparc/spec-pseudocode.md +80 -80
  217. package/.claude/commands/sparc/supabase-admin.md +348 -348
  218. package/.claude/commands/sparc/swarm-coordinator.md +54 -54
  219. package/.claude/commands/sparc/tdd.md +54 -54
  220. package/.claude/commands/sparc/tester.md +54 -54
  221. package/.claude/commands/sparc/tutorial.md +79 -79
  222. package/.claude/commands/sparc/workflow-manager.md +54 -54
  223. package/.claude/commands/sparc.md +166 -166
  224. package/.claude/commands/stream-chain/pipeline.md +120 -120
  225. package/.claude/commands/stream-chain/run.md +69 -69
  226. package/.claude/commands/swarm/README.md +15 -15
  227. package/.claude/commands/swarm/analysis.md +95 -95
  228. package/.claude/commands/swarm/development.md +96 -96
  229. package/.claude/commands/swarm/examples.md +168 -168
  230. package/.claude/commands/swarm/maintenance.md +102 -102
  231. package/.claude/commands/swarm/optimization.md +117 -117
  232. package/.claude/commands/swarm/research.md +136 -136
  233. package/.claude/commands/swarm/swarm-analysis.md +8 -8
  234. package/.claude/commands/swarm/swarm-background.md +8 -8
  235. package/.claude/commands/swarm/swarm-init.md +19 -19
  236. package/.claude/commands/swarm/swarm-modes.md +8 -8
  237. package/.claude/commands/swarm/swarm-monitor.md +8 -8
  238. package/.claude/commands/swarm/swarm-spawn.md +19 -19
  239. package/.claude/commands/swarm/swarm-status.md +8 -8
  240. package/.claude/commands/swarm/swarm-strategies.md +8 -8
  241. package/.claude/commands/swarm/swarm.md +87 -87
  242. package/.claude/commands/swarm/testing.md +131 -131
  243. package/.claude/commands/training/README.md +9 -9
  244. package/.claude/commands/training/model-update.md +25 -25
  245. package/.claude/commands/training/neural-patterns.md +107 -107
  246. package/.claude/commands/training/neural-train.md +75 -75
  247. package/.claude/commands/training/pattern-learn.md +25 -25
  248. package/.claude/commands/training/specialization.md +62 -62
  249. package/.claude/commands/truth/start.md +142 -142
  250. package/.claude/commands/verify/check.md +49 -49
  251. package/.claude/commands/verify/start.md +127 -127
  252. package/.claude/commands/workflows/README.md +9 -9
  253. package/.claude/commands/workflows/development.md +77 -77
  254. package/.claude/commands/workflows/research.md +62 -62
  255. package/.claude/commands/workflows/workflow-create.md +25 -25
  256. package/.claude/commands/workflows/workflow-execute.md +25 -25
  257. package/.claude/commands/workflows/workflow-export.md +25 -25
  258. package/.claude/eval/human-relevance-frozen-v1.json +17 -17
  259. package/.claude/evolve-proof/generation-0.json +211 -211
  260. package/.claude/evolve-proof/real-generation-0.json +406 -406
  261. package/.claude/evolve-proof/real-generation-1.json +406 -406
  262. package/.claude/helpers/README.md +96 -96
  263. package/.claude/helpers/adr-compliance.sh +186 -186
  264. package/.claude/helpers/auto-commit.sh +178 -178
  265. package/.claude/helpers/auto-memory-hook.mjs +430 -430
  266. package/.claude/helpers/checkpoint-manager.sh +251 -251
  267. package/.claude/helpers/daemon-manager.sh +252 -252
  268. package/.claude/helpers/ddd-tracker.sh +144 -144
  269. package/.claude/helpers/github-safe.js +156 -156
  270. package/.claude/helpers/github-setup.sh +45 -45
  271. package/.claude/helpers/guidance-hook.sh +13 -13
  272. package/.claude/helpers/guidance-hooks.sh +102 -102
  273. package/.claude/helpers/health-monitor.sh +108 -108
  274. package/.claude/helpers/helpers.manifest.json +6 -6
  275. package/.claude/helpers/hook-handler.cjs +606 -606
  276. package/.claude/helpers/intelligence.cjs +1169 -1169
  277. package/.claude/helpers/learning-hooks.sh +329 -329
  278. package/.claude/helpers/learning-optimizer.sh +127 -127
  279. package/.claude/helpers/learning-service.mjs +1144 -1144
  280. package/.claude/helpers/memory.js +83 -83
  281. package/.claude/helpers/metrics-db.mjs +503 -503
  282. package/.claude/helpers/pattern-consolidator.sh +86 -86
  283. package/.claude/helpers/perf-worker.sh +160 -160
  284. package/.claude/helpers/post-commit +16 -16
  285. package/.claude/helpers/pre-commit +26 -26
  286. package/.claude/helpers/quick-start.sh +19 -19
  287. package/.claude/helpers/router.js +105 -105
  288. package/.claude/helpers/security-scanner.sh +127 -127
  289. package/.claude/helpers/session.js +157 -157
  290. package/.claude/helpers/setup-mcp.sh +18 -18
  291. package/.claude/helpers/standard-checkpoint-hooks.sh +189 -189
  292. package/.claude/helpers/statusline-hook.sh +21 -21
  293. package/.claude/helpers/statusline.cjs +1290 -1290
  294. package/.claude/helpers/statusline.js +340 -340
  295. package/.claude/helpers/swarm-comms.sh +353 -353
  296. package/.claude/helpers/swarm-hooks.sh +761 -761
  297. package/.claude/helpers/swarm-monitor.sh +210 -210
  298. package/.claude/helpers/sync-v3-metrics.sh +245 -245
  299. package/.claude/helpers/update-v3-progress.sh +165 -165
  300. package/.claude/helpers/v3-quick-status.sh +57 -57
  301. package/.claude/helpers/v3.sh +110 -110
  302. package/.claude/helpers/validate-v3-config.sh +215 -215
  303. package/.claude/helpers/worker-manager.sh +170 -170
  304. package/.claude/proven-config.json +41 -41
  305. package/.claude/proven-config.manifest.json +37 -37
  306. package/.claude/proven-config.signed.json +41 -41
  307. package/.claude/settings.json +182 -182
  308. package/.claude/skills/agentdb-advanced/SKILL.md +550 -550
  309. package/.claude/skills/agentdb-learning/SKILL.md +545 -545
  310. package/.claude/skills/agentdb-memory-patterns/SKILL.md +339 -339
  311. package/.claude/skills/agentdb-optimization/SKILL.md +509 -509
  312. package/.claude/skills/agentdb-vector-search/SKILL.md +339 -339
  313. package/.claude/skills/browser/SKILL.md +204 -204
  314. package/.claude/skills/dual-mode/README.md +71 -71
  315. package/.claude/skills/dual-mode/dual-collect.md +103 -103
  316. package/.claude/skills/dual-mode/dual-coordinate.md +85 -85
  317. package/.claude/skills/dual-mode/dual-spawn.md +81 -81
  318. package/.claude/skills/flow-nexus-neural/SKILL.md +727 -727
  319. package/.claude/skills/flow-nexus-platform/SKILL.md +1154 -1154
  320. package/.claude/skills/flow-nexus-swarm/SKILL.md +604 -604
  321. package/.claude/skills/github-code-review/SKILL.md +1125 -1125
  322. package/.claude/skills/github-multi-repo/SKILL.md +862 -862
  323. package/.claude/skills/github-project-management/SKILL.md +1262 -1262
  324. package/.claude/skills/github-release-management/SKILL.md +1064 -1064
  325. package/.claude/skills/github-workflow-automation/SKILL.md +1047 -1047
  326. package/.claude/skills/hooks-automation/SKILL.md +1201 -1201
  327. package/.claude/skills/pair-programming/SKILL.md +1202 -1202
  328. package/.claude/skills/reasoningbank-agentdb/SKILL.md +446 -446
  329. package/.claude/skills/reasoningbank-intelligence/SKILL.md +201 -201
  330. package/.claude/skills/skill-builder/SKILL.md +910 -910
  331. package/.claude/skills/sparc-methodology/SKILL.md +1106 -1106
  332. package/.claude/skills/stream-chain/SKILL.md +560 -560
  333. package/.claude/skills/swarm-advanced/SKILL.md +970 -970
  334. package/.claude/skills/swarm-orchestration/SKILL.md +179 -179
  335. package/.claude/skills/v3-cli-modernization/SKILL.md +871 -871
  336. package/.claude/skills/v3-core-implementation/SKILL.md +796 -796
  337. package/.claude/skills/v3-ddd-architecture/SKILL.md +441 -441
  338. package/.claude/skills/v3-integration-deep/SKILL.md +240 -240
  339. package/.claude/skills/v3-mcp-optimization/SKILL.md +776 -776
  340. package/.claude/skills/v3-memory-unification/SKILL.md +173 -173
  341. package/.claude/skills/v3-performance-optimization/SKILL.md +389 -389
  342. package/.claude/skills/v3-security-overhaul/SKILL.md +81 -81
  343. package/.claude/skills/v3-swarm-coordination/SKILL.md +339 -339
  344. package/.claude/skills/verification-quality/SKILL.md +691 -691
  345. package/README.md +422 -422
  346. package/bin/cli.js +338 -338
  347. package/bin/mcp-server.js +224 -224
  348. package/bin/preinstall.cjs +2 -2
  349. package/catalog-manifest.json +2 -2
  350. package/dist/src/benchmarks/gaia-critic.js +24 -24
  351. package/dist/src/business-pods/bbs-budget-tracker.js +53 -53
  352. package/dist/src/commands/completions.js +409 -409
  353. package/dist/src/commands/daemon.js +44 -44
  354. package/dist/src/commands/doctor.js +4 -4
  355. package/dist/src/commands/embeddings.js +26 -26
  356. package/dist/src/commands/hive-mind.js +97 -97
  357. package/dist/src/commands/hooks.js +9 -9
  358. package/dist/src/commands/init.js +75 -75
  359. package/dist/src/commands/ruvector/backup.js +23 -23
  360. package/dist/src/commands/ruvector/benchmark.js +31 -31
  361. package/dist/src/commands/ruvector/import.js +14 -14
  362. package/dist/src/commands/ruvector/init.js +115 -115
  363. package/dist/src/commands/ruvector/migrate.js +99 -99
  364. package/dist/src/commands/ruvector/optimize.js +51 -51
  365. package/dist/src/commands/ruvector/setup.js +624 -624
  366. package/dist/src/commands/ruvector/status.js +38 -38
  367. package/dist/src/config/proven-config.js +2 -2
  368. package/dist/src/init/claudemd-generator.js +273 -273
  369. package/dist/src/init/executor.js +453 -453
  370. package/dist/src/init/helper-signing.js +2 -2
  371. package/dist/src/init/helpers-generator.js +917 -751
  372. package/dist/src/init/statusline-generator.js +24 -24
  373. package/dist/src/mcp-tools/agentdb-tools.js +15 -15
  374. package/dist/src/mcp-tools/browser-intent-tools.js +19 -19
  375. package/dist/src/mcp-tools/seraphina-tools.js +4 -4
  376. package/dist/src/memory/graph-edge-writer.js +22 -22
  377. package/dist/src/memory/memory-bridge.js +114 -114
  378. package/dist/src/memory/memory-initializer.js +416 -416
  379. package/dist/src/memory/rabitq-index.js +5 -5
  380. package/dist/src/proxy/verify.js +2 -2
  381. package/dist/src/runtime/headless.js +28 -28
  382. package/dist/src/ruvector/diskann-backend.d.ts +78 -0
  383. package/dist/src/ruvector/diskann-backend.js +310 -0
  384. package/dist/src/services/distill-tuning.js +7 -7
  385. package/dist/src/services/headless-worker-executor.js +84 -84
  386. package/dist/src/services/memory-distillation.js +18 -18
  387. package/dist/src/transfer/deploy-seraphine.js +23 -23
  388. package/node_modules/@claude-flow/codex/.agents/skills/github-automation/SKILL.md +32 -32
  389. package/node_modules/@claude-flow/codex/.agents/skills/memory-management/SKILL.md +45 -45
  390. package/node_modules/@claude-flow/codex/.agents/skills/performance-analysis/SKILL.md +32 -32
  391. package/node_modules/@claude-flow/codex/.agents/skills/security-audit/SKILL.md +46 -46
  392. package/node_modules/@claude-flow/codex/.agents/skills/sparc-methodology/SKILL.md +46 -46
  393. package/node_modules/@claude-flow/codex/.agents/skills/swarm-orchestration/SKILL.md +53 -53
  394. package/node_modules/@claude-flow/codex/README.md +1044 -1044
  395. package/node_modules/@claude-flow/codex/dist/dual-mode/orchestrator.js +13 -13
  396. package/node_modules/@claude-flow/codex/dist/generators/agents-md.js +664 -664
  397. package/node_modules/@claude-flow/codex/dist/generators/config-toml.js +455 -455
  398. package/node_modules/@claude-flow/codex/dist/generators/skill-md.js +45 -45
  399. package/node_modules/@claude-flow/codex/dist/initializer.js +167 -167
  400. package/node_modules/@claude-flow/codex/dist/templates/index.js +15 -15
  401. package/node_modules/@claude-flow/mcp/README.md +429 -429
  402. package/node_modules/@claude-flow/plugin-agent-federation/README.md +49 -49
  403. package/node_modules/@claude-flow/security/README.md +292 -292
  404. package/node_modules/@claude-flow/security/dist/credential-generator.js +9 -9
  405. package/node_modules/@claude-flow/security/dist/input-validator.d.ts +6 -6
  406. package/node_modules/@claude-flow/security/dist/oauth/callback-server.js +9 -9
  407. package/package.json +181 -181
  408. package/plugins/ruflo-metaharness/.claude-plugin/plugin.json +32 -32
  409. package/plugins/ruflo-metaharness/README.md +72 -72
  410. package/plugins/ruflo-metaharness/agents/metaharness-architect.md +58 -58
  411. package/plugins/ruflo-metaharness/commands/ruflo-metaharness.md +50 -50
  412. package/plugins/ruflo-metaharness/scripts/_darwin.mjs +210 -210
  413. package/plugins/ruflo-metaharness/scripts/_harness.mjs +334 -334
  414. package/plugins/ruflo-metaharness/scripts/_invoke.mjs +230 -230
  415. package/plugins/ruflo-metaharness/scripts/_redblue.mjs +143 -143
  416. package/plugins/ruflo-metaharness/scripts/_similarity.mjs +161 -161
  417. package/plugins/ruflo-metaharness/scripts/_spike-similarity.mjs +223 -223
  418. package/plugins/ruflo-metaharness/scripts/audit-list.mjs +158 -158
  419. package/plugins/ruflo-metaharness/scripts/audit-trend.mjs +272 -272
  420. package/plugins/ruflo-metaharness/scripts/bench-parse-mcp-scan.mjs +146 -146
  421. package/plugins/ruflo-metaharness/scripts/bench-recordpair-overhead.mjs +186 -186
  422. package/plugins/ruflo-metaharness/scripts/bench-similarity.mjs +177 -177
  423. package/plugins/ruflo-metaharness/scripts/bench.mjs +95 -95
  424. package/plugins/ruflo-metaharness/scripts/drift-from-history.mjs +363 -363
  425. package/plugins/ruflo-metaharness/scripts/evolve.mjs +404 -404
  426. package/plugins/ruflo-metaharness/scripts/genome.mjs +105 -105
  427. package/plugins/ruflo-metaharness/scripts/gepa.mjs +153 -153
  428. package/plugins/ruflo-metaharness/scripts/learn.mjs +127 -127
  429. package/plugins/ruflo-metaharness/scripts/mcp-scan.mjs +110 -110
  430. package/plugins/ruflo-metaharness/scripts/mint.mjs +126 -126
  431. package/plugins/ruflo-metaharness/scripts/oia-audit.mjs +228 -228
  432. package/plugins/ruflo-metaharness/scripts/redblue.mjs +286 -286
  433. package/plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs +250 -250
  434. package/plugins/ruflo-metaharness/scripts/score.mjs +92 -92
  435. package/plugins/ruflo-metaharness/scripts/security-bench.mjs +174 -174
  436. package/plugins/ruflo-metaharness/scripts/similarity.mjs +158 -158
  437. package/plugins/ruflo-metaharness/scripts/smoke.sh +2422 -2422
  438. package/plugins/ruflo-metaharness/scripts/test-graceful-degradation.mjs +165 -165
  439. package/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs +498 -498
  440. package/plugins/ruflo-metaharness/scripts/test-parallel-pipeline.mjs +204 -204
  441. package/plugins/ruflo-metaharness/scripts/test-pipeline-roundtrip.mjs +586 -586
  442. package/plugins/ruflo-metaharness/scripts/test-similarity.mjs +372 -372
  443. package/plugins/ruflo-metaharness/scripts/test-with-openrouter.mjs +229 -229
  444. package/plugins/ruflo-metaharness/scripts/threat-model.mjs +62 -62
  445. package/plugins/ruflo-metaharness/skills/harness-bench/SKILL.md +64 -64
  446. package/plugins/ruflo-metaharness/skills/harness-drift-from-history/SKILL.md +65 -65
  447. package/plugins/ruflo-metaharness/skills/harness-evolve/SKILL.md +131 -131
  448. package/plugins/ruflo-metaharness/skills/harness-genome/SKILL.md +57 -57
  449. package/plugins/ruflo-metaharness/skills/harness-gepa/SKILL.md +65 -65
  450. package/plugins/ruflo-metaharness/skills/harness-learn/SKILL.md +65 -65
  451. package/plugins/ruflo-metaharness/skills/harness-mcp-scan/SKILL.md +49 -49
  452. package/plugins/ruflo-metaharness/skills/harness-mint/SKILL.md +72 -72
  453. package/plugins/ruflo-metaharness/skills/harness-oia-audit/SKILL.md +79 -79
  454. package/plugins/ruflo-metaharness/skills/harness-score/SKILL.md +66 -66
  455. package/plugins/ruflo-metaharness/skills/harness-security-bench/SKILL.md +101 -101
  456. package/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md +67 -67
  457. package/plugins/ruflo-metaharness/skills/harness-threat-model/SKILL.md +41 -41
  458. package/scripts/postinstall.cjs +153 -153
@@ -1,1290 +1,1290 @@
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
- // Header identity defaults to project/repository name. Set `author` to
32
- // retain the previous `git config user.name` display (#2682).
33
- identityMode: (process.env.RUFLO_STATUSLINE_IDENTITY || 'project').toLowerCase(),
34
- // Session-cost display. Claude Code's cost.total_cost_usd is a client-side
35
- // estimate that "may differ from your actual bill" and reads as misleading on
36
- // subscription plans, where token usage is not billed per dollar. These let
37
- // each user pick what the segment means to them without changing the default.
38
- // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. ⚡, €, 🌱);
39
- // set to an empty string for the number alone.
40
- // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.
41
- costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',
42
- hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),
43
- };
44
-
45
- const CWD = process.env.CLAUDE_PROJECT_DIR || process.cwd();
46
- // Replaced by statusline-generator with the package root of the CLI that
47
- // installed this helper. This survives custom npm prefixes and bundled Node
48
- // runtimes whose process.execPath belongs to a different tree (#2811).
49
- const BAKED_INSTALL_ROOT = "";
50
-
51
- // ─── Delegation cache ───────────────────────────────────────────
52
- // Cache the CLI JSON result so rapid prompt re-renders (Claude Code
53
- // refreshes the statusline several times a second while streaming) don't
54
- // re-invoke the CLI each time.
55
- // #2337 bumped 10s → 60s.
56
- // Followup for anthropics/claude-code#70200 (Windows console-flash bug —
57
- // claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,
58
- // producing a visible cmd flash on every render): bumped 60s → 300s to
59
- // reduce the flash rate 5x on Windows until the upstream fix ships.
60
- // Tradeoff: stat/git counters update every 5min instead of every 1min;
61
- // promo/insight row still rotates on its own tighter 20s promoFresh clock.
62
- const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
63
- const CACHE_TTL_MS = 300000;
64
-
65
- // The promo/insight row is designed to rotate on a 20s cadence (funnel/
66
- // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check —
67
- // duplicated here as a bare number since this generated script has no
68
- // runtime import of the funnel module; keep in sync if that constant ever
69
- // changes). The rotation slot is only ever (re)computed SERVER-SIDE inside
70
- // the CLI subprocess this file shells out to — so a general 60s data cache
71
- // (correct and necessary for #2337) silently made that 20s design
72
- // unreachable: cache.fresh stayed true across 2-3 whole rotation slots,
73
- // so the row visibly "didn't rotate" (user report). Fix: track promo
74
- // freshness on its OWN, tighter clock — when it lags behind the current
75
- // slot, fall through to a real CLI call even though the REST of the
76
- // cached data (security/swarm/system) is still within CACHE_TTL_MS. This
77
- // does not touch or regress #2337's fix; it only adds a narrower check.
78
- const PROMO_ROTATION_SLOT_MS = 20000;
79
-
80
- // Persistent last-known-good promo record. Lives outside the /tmp cache so it
81
- // survives a full cache wipe / cache write race / CLI failure combo. Written
82
- // every time we successfully render a promo; read as a last resort so the row
83
- // never blinks out mid-session (was: 'promo shows then hides' bug report).
84
- const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');
85
- 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.
86
-
87
- // #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we
88
- // can invoke it directly via `node`. The previous version called
89
- // `npx --yes @claude-flow/cli@latest` on every uncached render, which forces
90
- // a registry resolution + cold-start of the entire CLI per render. With
91
- // multiple concurrent Claude Code sessions this storms the host (reporter
92
- // saw load average 40-65 on a 12-core box).
93
- //
94
- // Returns EVERY existing bin/cli.js candidate, in preference order (project,
95
- // monorepo, plugin marketplace, global node_modules including custom-prefix
96
- // layouts like ~/.npm-global) — mirrors getPkgVersion()'s own path probing.
97
- //
98
- // Returns a list, not a single winner: `fs.existsSync` only proves a file is
99
- // present, not that it actually runs. A marketplace/npx-cached install can
100
- // exist on disk but be broken (observed in practice: a stale marketplace
101
- // checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',
102
- // that isn't bundled there — every invocation throws ERR_MODULE_NOT_FOUND).
103
- // Picking the first EXISTING path and never falling through meant a single
104
- // broken install silently killed the promo row for the entire session (the
105
- // CLI call always failed, so the memo could never refresh and eventually
106
- // expired). getStatuslineData() now walks this whole list and tries the next
107
- // candidate on failure, so one broken install can't permanently wedge it.
108
- function resolveCliBinCandidates() {
109
- const candidates = [];
110
- try {
111
- const home = os.homedir();
112
- candidates.push(
113
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
114
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
115
- path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),
116
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
117
- );
118
- try {
119
- const binDir = path.dirname(process.execPath);
120
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
121
- for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
122
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
123
- }
124
- for (const gm of globalModuleDirs) {
125
- candidates.push(
126
- path.join(gm, 'ruflo', 'bin', 'cli.js'),
127
- path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),
128
- );
129
- }
130
- } catch { /* ignore */ }
131
- } catch { /* ignore */ }
132
- return candidates.filter((p) => {
133
- try {
134
- if (!fs.existsSync(p)) return false;
135
- // A candidate's bin/cli.js can exist on disk while its compiled
136
- // dist/ never got built (Claude Code's own plugin marketplace just
137
- // git-clones the repo — no install/build step — so every marketplace
138
- // install is a source-only checkout by construction). Importing
139
- // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on
140
- // every real command; only --version happens to survive it. Check
141
- // for the compiled entrypoint too so a doomed candidate is skipped
142
- // up front instead of wasting a spawn-and-fail on every render.
143
- return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
144
- } catch { return false; }
145
- });
146
- }
147
-
148
- // Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL
149
- // — but data is returned regardless (stale-while-revalidate). This lets us
150
- // serve last known state (specifically the promo row) when the CLI is
151
- // slow/unavailable, so users don't see the funnel row flicker in and out on
152
- // cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock
153
- // as PROMO_ROTATION_SLOT_MS — see that constant's comment for why the promo
154
- // row needs its own freshness bound distinct from the general 60s TTL.
155
- function readCache() {
156
- try {
157
- if (fs.existsSync(CACHE_FILE)) {
158
- const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
159
- if (raw && raw._ts && raw.data) {
160
- const age = Date.now() - raw._ts;
161
- return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };
162
- }
163
- }
164
- } catch { /* ignore */ }
165
- return { fresh: false, promoFresh: false, data: null };
166
- }
167
-
168
- function writeCache(data) {
169
- try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }
170
- // Also memoize any promo we saw so the row can survive future CLI hiccups.
171
- try {
172
- if (data && data.promo && typeof data.promo === 'object') {
173
- fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });
174
- fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });
175
- }
176
- } catch { /* ignore */ }
177
- }
178
-
179
- // Last resort: read a memoized promo (up to 6h old). Used when no cache and
180
- // no CLI response is available — the row still renders, so users don't see
181
- // the disclosure blink out. Returns null when the memo is absent, expired,
182
- // or malformed. Never throws.
183
- function readPromoMemo() {
184
- try {
185
- if (!fs.existsSync(PROMO_MEMO_FILE)) return null;
186
- const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));
187
- if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {
188
- return raw.promo;
189
- }
190
- } catch { /* ignore */ }
191
- return null;
192
- }
193
-
194
- /**
195
- * Single source of truth: delegate to the CLI hooks statusline --json command.
196
- * Falls back to a minimal static object on failure so the statusline still renders.
197
- *
198
- * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns
199
- * (missed the .swarm/memory.db → AgentDB path), computed dddProgress wrong,
200
- * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).
201
- */
202
- // Overlay the memoized promo onto any data object that's missing one. This is
203
- // the safety net that keeps the funnel row rendered when an OLDER cached CLI
204
- // version is picked up by npx — that older CLI succeeds but omits promo, so
205
- // the JSON round-trips clean but without our row. We patch it back here.
206
- function overlayMemoPromo(data) {
207
- if (data && !data.promo) {
208
- const memoPromo = readPromoMemo();
209
- if (memoPromo) data.promo = memoPromo;
210
- }
211
- return data;
212
- }
213
-
214
- function getStatuslineData() {
215
- const cache = readCache();
216
- // Both clocks must be satisfied to skip the CLI call entirely: the general
217
- // 60s TTL (#2337 — don't re-spawn the CLI on every rapid re-render) AND the
218
- // tighter promo-rotation clock (this fix — don't let a still-fresh 60s
219
- // cache silently freeze the promo/insight row across multiple 20s slots).
220
- if (cache.fresh && cache.promoFresh) {
221
- return applyLocalOverlays(overlayMemoPromo(cache.data));
222
- }
223
-
224
- // #2337: prefer an already-installed CLI bin via direct `node` invocation —
225
- // no npx, no registry round-trip, no @latest re-resolve per render. Try
226
- // every candidate that actually EXISTS (not just the first) before falling
227
- // back to `npx --prefer-offline @claude-flow/cli` (no @latest); an existing
228
- // but broken install (e.g. a stale marketplace checkout missing a bundled
229
- // workspace dep) must not block trying the next one.
230
- //
231
- // No `2>/dev/null` here (deliberately) — the execSync call below already
232
- // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the
233
- // Node level regardless of shell. The redirect was redundant on POSIX and
234
- // actively broke every candidate on Windows: cmd.exe (execSync's default
235
- // shell there) doesn't understand /dev/null, so the CLI delegation always
236
- // failed, silently degrading every render to buildLocalFallback() — 0%
237
- // intelligence and an empty promo row (the memo cache that keeps the row
238
- // populated across CLI hiccups is only ever written from a SUCCESSFUL
239
- // delegation, so it could never get seeded on Windows either).
240
- const cmds = resolveCliBinCandidates()
241
- .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')
242
- .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);
243
- for (const cmd of cmds) {
244
- try {
245
- const raw = execSync(
246
- cmd,
247
- { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true }
248
- ).trim();
249
- // The CLI may emit preamble lines before the JSON — find the first '{'.
250
- const jsonStart = raw.indexOf('{');
251
- if (jsonStart === -1) throw new Error('no JSON in CLI output');
252
- const data = JSON.parse(raw.slice(jsonStart));
253
- // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)
254
- // with real local reads, so those segments reflect actual state instead of 0.
255
- applyLocalOverlays(data);
256
- overlayMemoPromo(data);
257
- writeCache(data);
258
- return data;
259
- } catch { /* this candidate unavailable, broken, or timed out — try the next */ }
260
- }
261
-
262
- // Stale-while-revalidate: if we have any cached data, keep serving it so the
263
- // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for
264
- // the segments the CLI JSON doesn't populate; the promo row survives.
265
- if (cache.data) {
266
- applyLocalOverlays(cache.data);
267
- overlayMemoPromo(cache.data);
268
- return cache.data;
269
- }
270
-
271
- // Last resort: local probes + memo. Users still see the funnel row.
272
- return overlayMemoPromo(buildLocalFallback());
273
- }
274
-
275
- // Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed
276
- // v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).
277
- function getLocalADRCount() {
278
- const adrDirs = [
279
- path.join(CWD, 'v3', 'implementation', 'adrs'),
280
- path.join(CWD, 'v3', 'docs', 'adr'),
281
- path.join(CWD, 'docs', 'adrs'),
282
- path.join(CWD, '.claude-flow', 'adrs'),
283
- ];
284
- let total = 0;
285
- for (const dir of adrDirs) {
286
- try {
287
- if (fs.existsSync(dir)) {
288
- const files = fs.readdirSync(dir).filter(function(f) {
289
- return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\d{4}-/.test(f));
290
- });
291
- total += files.length;
292
- }
293
- } catch { /* ignore */ }
294
- }
295
- return { count: total, implemented: total, compliance: 0 };
296
- }
297
-
298
- // ─── Local overlays for segments the CLI JSON omits ──────────────
299
- // 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.
300
- // agentdb/tests/hooks/integration are never populated, so without these overlays
301
- // they render as a permanent 0. Each reader is cheap and degrades to zeros.
302
-
303
- // Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db
304
- // (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.
305
- // One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).
306
- function getLocalAgentDB() {
307
- const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };
308
- try {
309
- let bytes = 0;
310
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
311
- try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }
312
- }
313
- result.dbSizeKB = Math.round(bytes / 1024);
314
-
315
- const memDb = path.join(CWD, '.swarm', 'memory.db');
316
- if (fs.existsSync(memDb)) {
317
- const Q = String.fromCharCode(34);
318
- // Two INDEPENDENT statements -- do NOT combine into one. Coupling the
319
- // vector count with the vector_indexes row count in a single statement
320
- // meant that on a DB missing the vector_indexes table (older/agentdb-
321
- // written DBs), the whole statement failed at PREPARE time (SQLite
322
- // compiles the full SQL before running), so the valid memory_entries
323
- // count was discarded too and the statusline showed Vectors 0 despite
324
- // thousands of real vectors. Split so a missing table can only zero the
325
- // HNSW flag, never the count. The init self-heal provisions the table so
326
- // the flag recovers on the next ruflo init / MCP start.
327
- const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;
328
- const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);
329
- if (vc) result.vectorCount = parseInt(vc, 10) || 0;
330
- // HNSW flag: separate statement. If vector_indexes is absent, sqlite3
331
- // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact
332
- // original semantics: at least one index-config row present).
333
- const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;
334
- const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);
335
- if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;
336
- }
337
- } catch { /* ignore */ }
338
- return result;
339
- }
340
-
341
- // Count test files via a bounded directory walk (no file reads).
342
- function getLocalTests() {
343
- let testFiles = 0;
344
- function countTests(dir, depth) {
345
- if ((depth || 0) > 4) return;
346
- try {
347
- if (!fs.existsSync(dir)) return;
348
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
349
- if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {
350
- countTests(path.join(dir, e.name), (depth || 0) + 1);
351
- } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {
352
- testFiles++;
353
- }
354
- }
355
- } catch { /* ignore */ }
356
- }
357
- for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));
358
- return { testFiles, testCases: testFiles * 4 };
359
- }
360
-
361
- // Count configured hooks from project .claude/settings.json. Claude Code hooks
362
- // have no enabled/disabled flag, so every configured hook counts as enabled.
363
- function getLocalHooks() {
364
- const result = { enabled: 0, total: 0 };
365
- try {
366
- const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));
367
- const hooks = settings && settings.hooks;
368
- if (hooks && typeof hooks === 'object') {
369
- let n = 0;
370
- for (const ev of Object.keys(hooks)) {
371
- const groups = hooks[ev];
372
- if (Array.isArray(groups)) {
373
- for (const g of groups) {
374
- if (g && Array.isArray(g.hooks)) n += g.hooks.length;
375
- }
376
- }
377
- }
378
- result.total = n;
379
- result.enabled = n;
380
- }
381
- } catch { /* ignore */ }
382
- return result;
383
- }
384
-
385
- // Best-effort integration block: DB presence + locally-configured stdio MCP
386
- // servers (project .mcp.json + global ~/.claude.json). Remote connectors are
387
- // account-managed and not present in local config, so they are not counted.
388
- function getLocalIntegration() {
389
- const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };
390
- try {
391
- for (const f of ['.swarm/memory.db', 'ruvector.db']) {
392
- if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }
393
- }
394
- const names = new Set();
395
- const projMcp = readJSON(path.join(CWD, '.mcp.json'));
396
- if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);
397
- const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));
398
- if (claudeJson) {
399
- if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);
400
- const proj = claudeJson.projects && claudeJson.projects[CWD];
401
- if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {
402
- for (const k of Object.keys(proj.mcpServers)) names.add(k);
403
- }
404
- }
405
- integration.mcpServers.total = names.size;
406
- integration.mcpServers.enabled = names.size;
407
- } catch { /* ignore */ }
408
- return integration;
409
- }
410
-
411
- // ─── Security freshness overlay (ruvnet/ruflo#2776) ──────────────
412
- // The shipped CLI producer (dist/src/funnel/local-signals.js getSecurityStatus)
413
- // only ever emits PENDING / CLEAN / ISSUES — it captures `scannedAt` but never
414
- // inspects it, so a year-old scan renders 🛡 ✓ forever and the renderer's
415
- // STALE / IN_PROGRESS branches are unreachable. Worse, when CLI delegation
416
- // fails, the stale-while-revalidate cache (readCache() below) keeps serving
417
- // the pre-scan PENDING pill indefinitely, so a user who runs the advertised
418
- // `ruflo security scan` sees no change — the pill freezes at "scan pending".
419
- //
420
- // This overlay recomputes the security block from disk on EVERY render (same
421
- // pattern as adrs/agentdb/tests/hooks above), which:
422
- // 1) Makes STALE reachable — when the newest scan is older than
423
- // RUFLO_SCAN_STALE_HOURS (default 24h — matches the CVE feed refresh
424
- // cadence), report STALE regardless of what the cached CLI JSON says.
425
- // 2) Makes IN_PROGRESS reachable — when a `scan-in-progress` marker file
426
- // exists and is younger than SECURITY_IN_PROGRESS_MAX_MIN (guards against
427
- // a crashed scan leaving the marker behind).
428
- // 3) Caps the "scan pending" display window — if PENDING has been shown for
429
- // >RUFLO_SCAN_PENDING_CAP_MIN (default 30) without a completion write,
430
- // switch to STALE and stop rendering the yellow indicator. The tracker
431
- // lives in ~/.ruflo/statusline-scan-pending-since.json, keyed by CWD
432
- // hash so multiple project checkouts don't collide.
433
- // 4) Since this runs AFTER readCache() serves stale data, it bypasses the
434
- // "pill freezes at PENDING" freeze in defect 2 — the overlay reads
435
- // fresh disk state even when the CLI delegation is broken.
436
- const SECURITY_STALE_HOURS = Math.max(1, parseInt(process.env.RUFLO_SCAN_STALE_HOURS || '24', 10) || 24);
437
- const SECURITY_PENDING_CAP_MIN = Math.max(1, parseInt(process.env.RUFLO_SCAN_PENDING_CAP_MIN || '30', 10) || 30);
438
- const SECURITY_IN_PROGRESS_MAX_MIN = 30; // marker older than this = crashed scan; treat as absent
439
- const PENDING_TRACK_FILE = path.join(os.homedir(), '.ruflo', 'statusline-scan-pending-since.json');
440
- const CWD_KEY = require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 12);
441
-
442
- function readPendingSince() {
443
- try {
444
- if (!fs.existsSync(PENDING_TRACK_FILE)) return null;
445
- const raw = JSON.parse(fs.readFileSync(PENDING_TRACK_FILE, 'utf-8'));
446
- if (raw && typeof raw === 'object' && typeof raw[CWD_KEY] === 'number') return raw[CWD_KEY];
447
- } catch { /* ignore */ }
448
- return null;
449
- }
450
-
451
- function writePendingSince(ts) {
452
- try {
453
- let obj = {};
454
- if (fs.existsSync(PENDING_TRACK_FILE)) {
455
- try { obj = JSON.parse(fs.readFileSync(PENDING_TRACK_FILE, 'utf-8')) || {}; } catch { obj = {}; }
456
- }
457
- if (ts === null) { delete obj[CWD_KEY]; } else { obj[CWD_KEY] = ts; }
458
- fs.mkdirSync(path.dirname(PENDING_TRACK_FILE), { recursive: true, mode: 0o700 });
459
- fs.writeFileSync(PENDING_TRACK_FILE, JSON.stringify(obj), { encoding: 'utf-8', mode: 0o600 });
460
- } catch { /* ignore */ }
461
- }
462
-
463
- function getLocalSecurity(cliSecurity) {
464
- const base = (cliSecurity && typeof cliSecurity === 'object')
465
- ? Object.assign({}, cliSecurity)
466
- : { status: 'NONE', findings: 0, cvesFixed: 0, totalCves: 0 };
467
- base.findings = Math.max(0, base.findings || 0);
468
-
469
- const scanDir = path.join(CWD, '.claude', 'security-scans');
470
-
471
- // Detect a live in-progress marker (writer opts-in by writing this file).
472
- let inProgress = false;
473
- try {
474
- const marker = path.join(scanDir, 'scan-in-progress');
475
- if (fs.existsSync(marker)) {
476
- const ageMin = (Date.now() - fs.statSync(marker).mtimeMs) / 60000;
477
- if (ageMin < SECURITY_IN_PROGRESS_MAX_MIN) inProgress = true;
478
- }
479
- } catch { /* ignore */ }
480
-
481
- // Find newest scan-*.json by mtime and read its findings/timestamp.
482
- let newestPath = null;
483
- let newestMtime = 0;
484
- try {
485
- if (fs.existsSync(scanDir)) {
486
- for (const name of fs.readdirSync(scanDir)) {
487
- if (!name.startsWith('scan-') || !name.endsWith('.json')) continue;
488
- try {
489
- const st = fs.statSync(path.join(scanDir, name));
490
- if (st.mtimeMs > newestMtime) { newestMtime = st.mtimeMs; newestPath = path.join(scanDir, name); }
491
- } catch { /* ignore */ }
492
- }
493
- }
494
- } catch { /* ignore */ }
495
-
496
- if (newestPath) {
497
- // We have a scan on disk — the never-scanned pending tracker is no longer
498
- // relevant. Clear it so a re-created directory can start a fresh window.
499
- writePendingSince(null);
500
-
501
- let scannedAtMs = newestMtime;
502
- let findings = base.findings;
503
- try {
504
- const j = JSON.parse(fs.readFileSync(newestPath, 'utf-8'));
505
- // scannedAt (CLI producer's field name) OR timestamp (writer's field name).
506
- const isoStr = (j && (j.scannedAt || j.timestamp)) || null;
507
- if (isoStr) {
508
- const t = Date.parse(isoStr);
509
- if (!isNaN(t)) scannedAtMs = t;
510
- }
511
- // findings may be a number, an array, or nested in summary.total.
512
- if (j) {
513
- if (typeof j.findings === 'number') findings = j.findings;
514
- else if (Array.isArray(j.findings)) findings = j.findings.length;
515
- else if (j.summary && typeof j.summary.total === 'number') findings = j.summary.total;
516
- }
517
- } catch { /* ignore parse — fall back to mtime + cached findings */ }
518
-
519
- base.findings = Math.max(0, findings || 0);
520
- base.scannedAt = new Date(scannedAtMs).toISOString();
521
-
522
- const ageHours = (Date.now() - scannedAtMs) / 3600000;
523
- if (ageHours >= SECURITY_STALE_HOURS) {
524
- // Stale but findings still render red (a year-old ISSUES scan is still bad).
525
- base.status = 'STALE';
526
- } else if (inProgress) {
527
- base.status = 'IN_PROGRESS';
528
- } else if (base.findings > 0) {
529
- base.status = 'ISSUES';
530
- } else {
531
- base.status = 'CLEAN';
532
- }
533
- return base;
534
- }
535
-
536
- // No scan file. If a live marker exists, we're mid-scan.
537
- if (inProgress) {
538
- base.status = 'IN_PROGRESS';
539
- // Reset the pending tracker so, if the scan crashes mid-flight, the next
540
- // render starts a fresh N-minute pending window instead of an already-expired one.
541
- writePendingSince(null);
542
- return base;
543
- }
544
-
545
- // Truly never-scanned: track how long we've shown PENDING. After the cap,
546
- // escalate to STALE with the dim/gray glyph so the pill visibly stops
547
- // shouting for attention — the user has either ignored it for 30 min or
548
- // the scan is silently failing to write.
549
- let pendingSince = readPendingSince();
550
- if (pendingSince === null || typeof pendingSince !== 'number') {
551
- pendingSince = Date.now();
552
- writePendingSince(pendingSince);
553
- }
554
- const pendingAgeMin = (Date.now() - pendingSince) / 60000;
555
- base.status = (pendingAgeMin >= SECURITY_PENDING_CAP_MIN) ? 'STALE' : 'PENDING';
556
- return base;
557
- }
558
-
559
- // Cached pattern count. The store is routinely >10MB (14.5MB / 1277 patterns on
560
- // the machine this was diagnosed on, costing 53ms to read+parse), and the
561
- // statusline re-renders on every prompt, so the parse is keyed on the file's
562
- // mtime+size and reused until the store actually changes.
563
- const PATTERN_COUNT_CACHE = path.join(os.tmpdir(), 'ruflo-statusline-patterns-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
564
-
565
- function countPatternsCached(file) {
566
- let stat;
567
- try { stat = fs.statSync(file); } catch { return 0; }
568
- const key = stat.mtimeMs + ':' + stat.size;
569
-
570
- try {
571
- const memo = JSON.parse(fs.readFileSync(PATTERN_COUNT_CACHE, 'utf-8'));
572
- if (memo && memo[file] && memo[file].key === key) return memo[file].count;
573
- } catch { /* no memo yet, or unreadable — fall through and recount */ }
574
-
575
- let count = 0;
576
- try {
577
- const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
578
- if (Array.isArray(raw)) count = raw.length;
579
- else if (raw && Array.isArray(raw.patterns)) count = raw.patterns.length;
580
- else if (raw && typeof raw === 'object') count = Object.keys(raw).length;
581
- } catch { return 0; }
582
-
583
- try {
584
- let memo = {};
585
- try { memo = JSON.parse(fs.readFileSync(PATTERN_COUNT_CACHE, 'utf-8')) || {}; } catch { /* start fresh */ }
586
- memo[file] = { key, count };
587
- fs.writeFileSync(PATTERN_COUNT_CACHE, JSON.stringify(memo));
588
- } catch { /* cache is an optimisation, never a requirement */ }
589
-
590
- return count;
591
- }
592
-
593
- // `system` is nominally CLI-populated, but the pattern store is on disk, so a
594
- // dead CLI must not render as "no learning". Without this, every candidate in
595
- // resolveCliBinCandidates() failing (a source-only marketplace checkout, or an
596
- // npx fetch that dies in a workspace root) silently degraded the brain to a
597
- // hardcoded 0% while the overlaid segments beside it kept showing live data —
598
- // indistinguishable from a genuine zero. Same reasoning as getLocalAgentDB(),
599
- // which had to start reading locally after the statusline reported "Vectors 0"
600
- // on a database holding thousands.
601
- function getLocalIntelligence(current) {
602
- const base = (current && typeof current === 'object') ? current : {};
603
- if (typeof base.intelligencePct === 'number' && base.intelligencePct > 0) return base;
604
-
605
- for (const file of [
606
- path.join(CWD, '.claude-flow', 'neural', 'patterns.json'),
607
- path.join(os.homedir(), '.claude-flow', 'neural', 'patterns.json'),
608
- ]) {
609
- const n = countPatternsCached(file);
610
- if (n > 0) {
611
- base.intelligencePct = Math.min(100, Math.floor(n / 10));
612
- return base;
613
- }
614
- }
615
-
616
- // No CLI value and no local store: unknown, which is not the same as zero.
617
- base.intelligencePct = null;
618
- return base;
619
- }
620
-
621
- // Overlay every locally-derived block onto the CLI data (mutates in place).
622
- function applyLocalOverlays(data) {
623
- data.adrs = getLocalADRCount();
624
- data.agentdb = getLocalAgentDB();
625
- data.tests = getLocalTests();
626
- data.hooks = getLocalHooks();
627
- data.integration = getLocalIntegration();
628
- // Security overlay: recompute freshness from disk on every render so cached
629
- // CLI JSON can never freeze the pill at PENDING. See getLocalSecurity() above.
630
- data.security = getLocalSecurity(data.security);
631
- data.system = getLocalIntelligence(data.system);
632
- return data;
633
- }
634
-
635
- // Minimal local fallback when the CLI is not installed or times out.
636
- // Returns a structure that matches the CLI JSON schema so the renderer works.
637
- function buildLocalFallback() {
638
- const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
639
-
640
- return applyLocalOverlays({
641
- user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },
642
- v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },
643
- security: { status: 'NONE', findings: 0, cvesFixed: 0, totalCves: 0 },
644
- swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },
645
- system: { memoryMB: memMB, contextPct: 0, intelligencePct: null, subAgents: 0 },
646
- lastUpdated: new Date().toISOString(),
647
- });
648
- }
649
-
650
- // ANSI colors
651
- const c = {
652
- reset: '\x1b[0m',
653
- bold: '\x1b[1m',
654
- dim: '\x1b[2m',
655
- red: '\x1b[0;31m',
656
- green: '\x1b[0;32m',
657
- yellow: '\x1b[0;33m',
658
- blue: '\x1b[0;34m',
659
- purple: '\x1b[0;35m',
660
- cyan: '\x1b[0;36m',
661
- brightRed: '\x1b[1;31m',
662
- brightGreen: '\x1b[1;32m',
663
- brightYellow: '\x1b[1;33m',
664
- brightBlue: '\x1b[1;34m',
665
- brightPurple: '\x1b[1;35m',
666
- brightCyan: '\x1b[1;36m',
667
- brightWhite: '\x1b[1;37m',
668
- };
669
-
670
- // Safe execSync with strict timeout (returns empty string on failure)
671
- function safeExec(cmd, timeoutMs) {
672
- try {
673
- return execSync(cmd, {
674
- encoding: 'utf-8',
675
- timeout: timeoutMs || 2000,
676
- stdio: ['pipe', 'pipe', 'pipe'],
677
- // Windows: without this, every execSync spawns cmd.exe /d /s /c which
678
- // flashes a visible console window every render (~1/min via the 60s
679
- // cache TTL). windowsHide runs the child in a hidden window instead.
680
- // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening").
681
- windowsHide: true,
682
- }).trim();
683
- } catch {
684
- return '';
685
- }
686
- }
687
-
688
- // Safe JSON file reader (returns null on failure)
689
- function readJSON(filePath) {
690
- try {
691
- if (fs.existsSync(filePath)) {
692
- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
693
- }
694
- } catch { /* ignore */ }
695
- return null;
696
- }
697
-
698
- // ─── Git info (pure-Node / single exec — needed for branch display) ──────────
699
-
700
- function getGitInfo() {
701
- const result = {
702
- name: path.basename(CWD) || 'project', gitBranch: '', modified: 0, untracked: 0,
703
- staged: 0, ahead: 0, behind: 0,
704
- };
705
-
706
- const script = [
707
- 'git rev-parse --show-toplevel 2>/dev/null || pwd',
708
- 'echo "---SEP---"',
709
- 'git config user.name 2>/dev/null || echo user',
710
- 'echo "---SEP---"',
711
- 'git branch --show-current 2>/dev/null',
712
- 'echo "---SEP---"',
713
- 'git status --porcelain 2>/dev/null',
714
- 'echo "---SEP---"',
715
- 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',
716
- ].join('; ');
717
-
718
- const raw = safeExec("sh -c '" + script + "'", 3000);
719
- if (!raw) return result;
720
-
721
- const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });
722
- if (parts.length >= 5) {
723
- const projectName = path.basename(parts[0] || CWD) || path.basename(CWD) || 'project';
724
- const authorName = parts[1] || 'user';
725
- result.name = CONFIG.identityMode === 'author' ? authorName : projectName;
726
- result.gitBranch = parts[2] || '';
727
-
728
- if (parts[3]) {
729
- for (const line of parts[3].split('\n')) {
730
- if (!line || line.length < 2) continue;
731
- const x = line[0], y = line[1];
732
- if (x === '?' && y === '?') { result.untracked++; continue; }
733
- if (x !== ' ' && x !== '?') result.staged++;
734
- if (y !== ' ' && y !== '?') result.modified++;
735
- }
736
- }
737
-
738
- const ab = (parts[4] || '0 0').split(/\s+/);
739
- result.ahead = parseInt(ab[0]) || 0;
740
- result.behind = parseInt(ab[1]) || 0;
741
- }
742
-
743
- return result;
744
- }
745
-
746
- // Detect model name from Claude config (pure file reads, no exec)
747
- function getModelName() {
748
- try {
749
- const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));
750
- if (claudeConfig && claudeConfig.projects) {
751
- for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
752
- if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {
753
- const usage = projectConfig.lastModelUsage;
754
- if (usage) {
755
- const ids = Object.keys(usage);
756
- if (ids.length > 0) {
757
- let modelId = ids[ids.length - 1];
758
- let latest = 0;
759
- for (const id of ids) {
760
- const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
761
- if (ts > latest) { latest = ts; modelId = id; }
762
- }
763
- if (modelId.includes('opus')) return 'Opus 4.8';
764
- if (modelId.includes('sonnet')) return 'Sonnet 4.6';
765
- if (modelId.includes('haiku')) return 'Haiku 4.5';
766
- return modelId.split('-').slice(1, 3).join(' ');
767
- }
768
- }
769
- break;
770
- }
771
- }
772
- }
773
- } catch { /* ignore */ }
774
-
775
- // Fallback: settings.json model field
776
- const settings = getSettings();
777
- if (settings && settings.model) {
778
- const m = settings.model;
779
- if (m.includes('opus')) return 'Opus 4.8';
780
- if (m.includes('sonnet')) return 'Sonnet 4.6';
781
- if (m.includes('haiku')) return 'Haiku 4.5';
782
- }
783
- return 'Claude Code';
784
- }
785
-
786
- // ─── Stdin reader (Claude Code pipes session JSON) ──────────────
787
- // Claude Code sends session JSON via stdin. Read synchronously so the
788
- // script works both when invoked by Claude Code (stdin has JSON) and
789
- // when run manually from terminal (stdin is empty/tty).
790
- let _stdinData = null;
791
- function getStdinData() {
792
- if (_stdinData !== undefined && _stdinData !== null) return _stdinData;
793
- try {
794
- if (process.stdin.isTTY) { _stdinData = null; return null; }
795
- const chunks = [];
796
- const buf = Buffer.alloc(4096);
797
- let bytesRead;
798
- try {
799
- while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {
800
- chunks.push(buf.slice(0, bytesRead));
801
- }
802
- } catch { /* EOF or read error */ }
803
- const raw = Buffer.concat(chunks).toString('utf-8').trim();
804
- _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;
805
- } catch {
806
- _stdinData = null;
807
- }
808
- return _stdinData;
809
- }
810
-
811
- function getModelFromStdin() {
812
- const data = getStdinData();
813
- return (data && data.model && data.model.display_name) ? data.model.display_name : null;
814
- }
815
-
816
- function getContextFromStdin() {
817
- const data = getStdinData();
818
- if (data && data.context_window) {
819
- return { usedPct: Math.floor(data.context_window.used_percentage || 0) };
820
- }
821
- return null;
822
- }
823
-
824
- function getCostFromStdin() {
825
- const data = getStdinData();
826
- if (data && data.cost) {
827
- const durationMs = data.cost.total_duration_ms || 0;
828
- const mins = Math.floor(durationMs / 60000);
829
- const secs = Math.floor((durationMs % 60000) / 1000);
830
- return {
831
- costUsd: data.cost.total_cost_usd || 0,
832
- duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',
833
- };
834
- }
835
- return null;
836
- }
837
-
838
- // Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").
839
- // Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately
840
- // simple (no prerelease/build-metadata handling) — this only orders local
841
- // package.json versions against each other, never anything untrusted from
842
- // a payload, so a full semver implementation would be dead weight here.
843
- function compareVersions(a, b) {
844
- const pa = String(a).split('.').map((n) => parseInt(n, 10));
845
- const pb = String(b).split('.').map((n) => parseInt(n, 10));
846
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
847
- const na = Number.isFinite(pa[i]) ? pa[i] : 0;
848
- const nb = Number.isFinite(pb[i]) ? pb[i] : 0;
849
- if (na !== nb) return na - nb;
850
- }
851
- return 0;
852
- }
853
-
854
- // #2742: when CWD is a linked git worktree, it has no node_modules of its
855
- // own (worktrees don't get their own `npm install`), so every CWD-relative
856
- // probe in getPkgVersion() misses and the version silently falls back to
857
- // the baked-in default — even though the main repo's install a few
858
- // directories away is perfectly resolvable. A linked worktree's `.git` is
859
- // a plain FILE (not a directory) containing `gitdir: <main>/.git/worktrees/
860
- // <name>`; walk up from CWD to find it, parse the pointer, and strip the
861
- // trailing `.git/worktrees/<name>` segment to recover the main repo root.
862
- // Pure fs — no `git rev-parse` spawn (statusline renders are latency-
863
- // sensitive; this doc comment's neighbors are explicit about avoiding
864
- // spawns in the render path).
865
- function resolveWorktreeMainRoot() {
866
- try {
867
- let dir = CWD;
868
- for (;;) {
869
- const dotGit = path.join(dir, '.git');
870
- if (fs.existsSync(dotGit)) {
871
- if (fs.statSync(dotGit).isFile()) {
872
- const contents = fs.readFileSync(dotGit, 'utf-8');
873
- const m = contents.match(/^gitdir:\s*(.+)$/m);
874
- const wtGitDir = m && m[1].trim();
875
- if (wtGitDir) {
876
- // Git writes this pointer with forward slashes even on Windows
877
- // (a git-for-windows convention for its own internal files) —
878
- // path.sep (backslash on win32) never matches, so normalize
879
- // before searching rather than building an OS-specific marker.
880
- const normalized = wtGitDir.replace(/\\/g, '/');
881
- const marker = '/.git/worktrees/';
882
- const idx = normalized.lastIndexOf(marker);
883
- if (idx > 0) return normalized.slice(0, idx);
884
- }
885
- }
886
- return null; // a real (non-worktree) .git dir — nothing to resolve
887
- }
888
- const parent = path.dirname(dir);
889
- if (parent === dir) return null; // reached filesystem root
890
- dir = parent;
891
- }
892
- } catch {
893
- return null;
894
- }
895
- }
896
-
897
- function getPkgVersion() {
898
- // Baked in at generation time from the real running CLI's own resolved
899
- // version (see generateStatuslineScript()'s doc comment) — correct even
900
- // when this renders via a pure npx invocation with no local install for
901
- // the candidate scan below to find.
902
- let ver = "3.32.8";
903
- try {
904
- const home = os.homedir();
905
- const pkgPaths = [
906
- ...(BAKED_INSTALL_ROOT ? [path.join(BAKED_INSTALL_ROOT, 'package.json')] : []),
907
- path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),
908
- path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),
909
- path.join(CWD, 'node_modules', 'ruflo', 'package.json'),
910
- path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),
911
- ];
912
- // #2742: CWD is a linked git worktree with no node_modules of its own —
913
- // probe the main repo's install too, so a worktree session shows the
914
- // same version a main-repo session would.
915
- const worktreeMainRoot = resolveWorktreeMainRoot();
916
- if (worktreeMainRoot) {
917
- pkgPaths.push(
918
- path.join(worktreeMainRoot, 'node_modules', '@claude-flow', 'cli', 'package.json'),
919
- path.join(worktreeMainRoot, 'node_modules', 'ruflo', 'package.json'),
920
- path.join(worktreeMainRoot, 'v3', '@claude-flow', 'cli', 'package.json'),
921
- );
922
- }
923
- // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the
924
- // probes above all miss and the version falls back to the hard-coded default.
925
- // Derive the global node_modules dir from the running node binary (no npm spawn —
926
- // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows
927
- // (bin/node_modules) layouts.
928
- try {
929
- const binDir = path.dirname(process.execPath);
930
- const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
931
- // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from
932
- // the node binary location, so the binDir-derived probes above all miss. Also
933
- // probe the npm prefix from the environment and the common ~/.npm-global default.
934
- for (const prefix of [
935
- process.env.npm_config_prefix,
936
- process.env.PREFIX,
937
- path.join(home, '.local'),
938
- path.join(home, '.npm-global'),
939
- ]) {
940
- if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
941
- }
942
- for (const gm of globalModuleDirs) {
943
- pkgPaths.push(
944
- path.join(gm, 'ruflo', 'package.json'),
945
- path.join(gm, '@claude-flow', 'cli', 'package.json'),
946
- );
947
- }
948
- } catch { /* ignore */ }
949
- // Pick the HIGHEST version among every candidate that exists, not the
950
- // first one found. The marketplace plugin path is probed first (list
951
- // order above), but Claude Code's own plugin marketplace mechanism
952
- // syncs on its own git-pull cadence, independent of npm publishes — a
953
- // freshly-published npm version can sit alongside a stale marketplace
954
- // checkout for a while (observed live: marketplace one release behind
955
- // right after a publish). Taking the first EXISTING candidate meant the
956
- // header could show a stale version even when a newer install (e.g.
957
- // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.
958
- for (const p of pkgPaths) {
959
- if (!fs.existsSync(p)) continue;
960
- try {
961
- const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
962
- if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
963
- if (compareVersions(pkg.version, ver) > 0) ver = pkg.version;
964
- }
965
- } catch { /* ignore */ }
966
- }
967
- } catch { /* ignore */ }
968
- return ver;
969
- }
970
-
971
- // ─── Rendering ──────────────────────────────────────────────────
972
-
973
- function progressBar(current, total) {
974
- const width = 5;
975
- const filled = Math.round((current / total) * width);
976
- return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
977
- }
978
-
979
- function generateStatusline() {
980
- const d = getStatuslineData();
981
- const git = getGitInfo();
982
- const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
983
- const ctxInfo = getContextFromStdin();
984
- const costInfo = getCostFromStdin();
985
- // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard
986
- // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted
987
- // .cjs artifact — without it the header silently reverts to a hard-coded
988
- // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.
989
- const RUFLO_VERSION = getPkgVersion();
990
-
991
- const progress = d.v3Progress || {};
992
- const security = d.security || {};
993
- const swarm = d.swarm || {};
994
- const system = d.system || {};
995
- const adrs = d.adrs || {};
996
- const hooks = d.hooks || {};
997
- const agentdb = d.agentdb || {};
998
- const tests = d.tests || {};
999
-
1000
- const domainsCompleted = progress.domainsCompleted || 0;
1001
- const totalDomains = progress.totalDomains || 5;
1002
- const dddProgress = progress.dddProgress || 0;
1003
- const patternsLearned = progress.patternsLearned || 0;
1004
- const activeAgents = swarm.activeAgents || 0;
1005
- const maxAgents = swarm.maxAgents || CONFIG.maxAgents;
1006
- const coordinationActive = swarm.coordinationActive || false;
1007
- // null/undefined means "no source answered", which must not collapse to 0 --
1008
- // that is exactly the ambiguity this segment used to present.
1009
- const intelligencePct = (typeof system.intelligencePct === 'number')
1010
- ? system.intelligencePct
1011
- : null;
1012
- const memoryMB = system.memoryMB || 0;
1013
- const subAgents = system.subAgents || 0;
1014
- const findings = Math.max(0, security.findings || 0);
1015
- const secStatus = security.status || 'NONE';
1016
- const adrCount = adrs.count || 0;
1017
- const adrImpl = adrs.implemented || 0;
1018
- const hooksEnabled = hooks.enabled || 0;
1019
- const hooksTotal = hooks.total || 0;
1020
- const vectorCount = agentdb.vectorCount || 0;
1021
- const hasHnsw = agentdb.hasHnsw || false;
1022
- const dbSizeKB = agentdb.dbSizeKB || 0;
1023
- const testFiles = tests.testFiles || 0;
1024
- const testCases = tests.testCases || testFiles * 4;
1025
-
1026
- const lines = [];
1027
-
1028
- // 3-line design (fits Claude Code's visible statusline area — line 4+ gets
1029
- // replaced by the system guidance / input prompt line):
1030
- // Line 1 — Header (RuFlo version · git · model · timing · context · cost)
1031
- // Line 2 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health)
1032
- // Line 3 — Promo / disclosure row (funnel surface, ADR-301)
1033
-
1034
- // ─── Line 1: header ────────────────────────────────────────────
1035
- let header = c.bold + c.brightPurple + '▊ RuFlo V' + RUFLO_VERSION + ' ' + c.reset;
1036
- header += (coordinationActive ? c.brightCyan : c.dim) + '● ' + c.brightCyan + git.name + c.reset;
1037
- if (git.gitBranch) {
1038
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightBlue + '⏇ ' + git.gitBranch + c.reset;
1039
- const changes = git.modified + git.staged + git.untracked;
1040
- if (changes > 0) {
1041
- let ind = '';
1042
- if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;
1043
- if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;
1044
- if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;
1045
- header += ' ' + ind;
1046
- }
1047
- if (git.ahead > 0) header += ' ' + c.brightGreen + '↑' + git.ahead + c.reset;
1048
- if (git.behind > 0) header += ' ' + c.brightRed + '↓' + git.behind + c.reset;
1049
- }
1050
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.purple + modelName + c.reset;
1051
- const duration = costInfo ? costInfo.duration : '';
1052
- if (duration) header += ' ' + c.dim + '│' + c.reset + ' ' + c.cyan + '⏱ ' + duration + c.reset;
1053
- if (ctxInfo && ctxInfo.usedPct > 0) {
1054
- const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;
1055
- header += ' ' + c.dim + '│' + c.reset + ' ' + ctxColor + '● ' + ctxInfo.usedPct + '% ctx' + c.reset;
1056
- }
1057
- if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {
1058
- header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;
1059
- }
1060
- lines.push(header);
1061
-
1062
- // ─── Line 2: compressed ops ────────────────────────────────────
1063
- // Everything actionable in one dense row. Show only what changes what you
1064
- // do next; diagnostic detail moves to `ruflo status --verbose`.
1065
- const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;
1066
- const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;
1067
- const intellColor = intelligencePct === null ? c.dim : intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;
1068
- const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset + ' ' : c.dim + '○' + c.reset + ' ';
1069
- const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && findings === 0;
1070
- const opsParts = [];
1071
- opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);
1072
- if (subAgents > 0) opsParts.push(c.brightPurple + '👥 ' + subAgents + c.reset);
1073
- opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);
1074
- opsParts.push(intellColor + '🧠 ' + (intelligencePct === null ? '—' : intelligencePct + '%') + c.reset);
1075
- opsParts.push(c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset);
1076
- // Health: one glyph when green, terse copy when there's something to act on.
1077
- if (healthAllGreen) {
1078
- opsParts.push(c.brightGreen + '🛡 ✓' + c.reset);
1079
- } else {
1080
- // #2776: STALE gets dim/gray (distinct from the actionable yellow of
1081
- // PENDING/IN_PROGRESS) so a stale pill visibly stops shouting for
1082
- // attention — the user can act on the "run ruflo security scan" prompt or
1083
- // ignore it without a permanently-yellow indicator.
1084
- if (secStatus === 'PENDING') opsParts.push(c.brightYellow + '🛡 scan pending' + c.reset);
1085
- else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + '🛡 scanning…' + c.reset);
1086
- else if (secStatus === 'ISSUES') opsParts.push(c.brightRed + '🛡 findings' + c.reset);
1087
- else if (secStatus === 'STALE') opsParts.push(c.dim + '🛡 scan stale' + c.reset);
1088
- else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + '🛡 ' + secStatus.toLowerCase() + c.reset);
1089
- if (findings > 0) {
1090
- opsParts.push(c.brightRed + '⚠ ' + findings + ' finding' + (findings === 1 ? '' : 's') + c.reset);
1091
- }
1092
- }
1093
- lines.push(opsParts.join(' ' + c.dim + '·' + c.reset + ' '));
1094
-
1095
- // ─── Line 3: promo / disclosure / insight ───────────────────────
1096
- // Colored by content kind so it reads as *what it is*, not as noise:
1097
- // disclosure → brightCyan (announcement / capability link)
1098
- // promotional → brightPurple (Cognitum sponsor spot)
1099
- // educational → yellow (a tip)
1100
- // insight → brightRed (environment/task-aware, local, actionable —
1101
- // distinct from remote content on purpose)
1102
- const promoRow = getPromoRow(d);
1103
- if (promoRow) {
1104
- const kind = (d && d.promo && d.promo.kind) || 'disclosure';
1105
- const promoColor = kind === 'promotional' ? c.brightPurple
1106
- : kind === 'educational' ? c.yellow
1107
- : kind === 'insight' ? c.brightRed
1108
- : c.brightCyan;
1109
- lines.push(promoColor + promoRow + c.reset);
1110
- }
1111
-
1112
- // Trailing blank line so Claude Code's input prompt gets breathing room
1113
- // instead of butting directly against the last statusline row.
1114
- return lines.join('\n') + '\n';
1115
- }
1116
-
1117
- // ─── Funnel promo row (ADR-301) ─────────────────────────────────
1118
- // Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so
1119
- // no message can smuggle a link to an unapproved host.
1120
- //
1121
- // The final destination hosts (cognitum.one / agentics.org) AND the
1122
- // click-redirect host are both allowlisted here: promo.ts routes every
1123
- // clickable message through the server-side click-redirect (ADR-311 §7)
1124
- // so promo_open + geo are captured before the 302 to the real target —
1125
- // so the OSC 8 link the renderer emits points at the redirect host, not
1126
- // the final destination directly.
1127
- const PROMO_LINK_HOSTS = new Set([
1128
- 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
1129
- // agentics.org — OSS foundation, distinct sponsor domain. Kept in sync
1130
- // with messages.ts ALLOWED_URL_HOSTS.
1131
- 'agentics.org', 'www.agentics.org',
1132
- // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw
1133
- // Cloud Run hostname is allowlisted too since event-transport.ts /
1134
- // message-transport.ts / attribution.ts currently point at it as a TEMP
1135
- // fallback while the domain mapping's cert provisions).
1136
- 'funnel.ruv.io',
1137
- 'cognitum-analytics-63rzcdswba-uc.a.run.app',
1138
- ]);
1139
-
1140
- // Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles
1141
- // raw OSC 8 (see anthropics/claude-code#27047) — opt in via env if wrapped.
1142
- function terminalSupportsHyperlinks() {
1143
- if (process.env.CI || process.env.GITHUB_ACTIONS) return false;
1144
- if (process.env.TERM === 'dumb') return false;
1145
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;
1146
- if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;
1147
- return true;
1148
- }
1149
-
1150
- // Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw
1151
- // label whenever the URL is not an allowlisted https target, when the terminal
1152
- // can't render hyperlinks, or when parsing fails — a broken link must never
1153
- // leave a raw URL or stray escape in the statusline output.
1154
- function safeTerminalLink(label, url) {
1155
- if (!terminalSupportsHyperlinks()) return label;
1156
- if (typeof url !== 'string' || url.length === 0) return label;
1157
- let parsed;
1158
- try { parsed = new URL(url); } catch { return label; }
1159
- if (parsed.protocol !== 'https:') return label;
1160
- if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;
1161
- const cleanLabel = String(label).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');
1162
- if (cleanLabel.length === 0) return label;
1163
- const ESC = '\u001b';
1164
- return ESC + ']8;;' + parsed.href + ESC + '\\' + cleanLabel + ESC + ']8;;' + ESC + '\\';
1165
- }
1166
-
1167
- function getPromoRow(d) {
1168
- try {
1169
- if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
1170
- if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
1171
- const promo = d && d.promo;
1172
- if (!promo || typeof promo.text !== 'string') return null;
1173
- // Strip control chars / ANSI / bidi overrides — promo copy is data and
1174
- // must never emit its own terminal sequences. Hard-cap length AFTER the
1175
- // strip; append an ellipsis when the cap fires so the row visibly reads
1176
- // as truncated instead of chopping a word mid-character (was: silent
1177
- // slice(0,100) that could produce output that looked like corrupt data).
1178
- const MAX_LEN = 100;
1179
- const sanitized = promo.text
1180
- .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
1181
- ;
1182
- const text = (sanitized.length > MAX_LEN ? sanitized.slice(0, MAX_LEN - 1).trimEnd() + '…' : sanitized).trim();
1183
- if (text.length === 0) return null;
1184
- // Split the label from the trailing "· manage: ruflo settings" instruction
1185
- // so each part gets styling that matches what it actually IS:
1186
- // 1. label — OSC 8 hyperlink + underline. A real clickable link.
1187
- // 2. "manage:" — dim. Just a connector word, no action implied.
1188
- // 3. "ruflo settings" — bold/bright, NOT underlined. This is a shell
1189
- // command the user TYPES, not a link they CLICK — a terminal can
1190
- // never safely execute a command from a click (that would let any
1191
- // server-served message run arbitrary commands), so we deliberately
1192
- // avoid the underline/OSC8 cues that imply "clickable". Bold+bright
1193
- // instead signals "this is the important bit — copy/type it".
1194
- // Educational tips have no manage tail and no URL — plain text through.
1195
- const manageIdx = text.indexOf(' · manage: ');
1196
- const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;
1197
- const manageWord = manageIdx > 0 ? ' · manage: ' : '';
1198
- const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';
1199
- const UL_ON = '\u001b[4m';
1200
- const UL_OFF = '\u001b[24m';
1201
- const DIM_ON = '\u001b[2m';
1202
- const DIM_OFF = '\u001b[22m';
1203
- const BOLD_ON = '\u001b[1m';
1204
- const BOLD_OFF = '\u001b[22m';
1205
- const FG_BRIGHT_WHITE = '';
1206
- // Reset FG to default so the caller's row-color code resumes coloring the
1207
- // rest of the row after the command portion. Without this the row-color
1208
- // escape wouldn't visibly re-apply because we already emitted an explicit FG.
1209
- const FG_DEFAULT = '';
1210
- // Some hosts (Claude Code's Windows UI, cmd.exe, older mintty) don't
1211
- // render OSC 8 hyperlinks as clickable — the label just underlines and
1212
- // clicks do nothing. Append a "(domain)" suffix so the destination is
1213
- // visible/copyable everywhere. Wrap the suffix in OSC 8 too so terminals
1214
- // that DO support hyperlinks give users TWO click targets (label AND
1215
- // domain hint) instead of one — some Windows hosts render one but not
1216
- // the other depending on how the statusline row is parsed.
1217
- // Only for URLs (not educational tips), and only when the label doesn't
1218
- // already end in the domain to avoid duplication.
1219
- let visibleUrlHint = '';
1220
- if (promo.url) {
1221
- try {
1222
- const host = new URL(promo.url).hostname.replace(/^www\./, '');
1223
- // Strip the click-redirect wrapper so users see the FINAL destination,
1224
- // not funnel.ruv.io. If the URL is /v1/click/<id>?to=<encoded>, pull the target.
1225
- let displayHost = host;
1226
- try {
1227
- const to = new URL(promo.url).searchParams.get('to');
1228
- if (to) displayHost = new URL(to).hostname.replace(/^www\./, '');
1229
- } catch { /* not a click-redirect, keep the raw host */ }
1230
- if (displayHost && !label.toLowerCase().endsWith(displayHost.toLowerCase())) {
1231
- // safeTerminalLink returns the plain string if URL isn't allowlisted
1232
- // or the terminal can't do OSC 8 — either way the domain stays visible.
1233
- const clickableDomain = safeTerminalLink(displayHost, promo.url);
1234
- visibleUrlHint = DIM_ON + ' (' + clickableDomain + ')' + DIM_OFF;
1235
- }
1236
- } catch { /* malformed URL — omit hint, never break the row */ }
1237
- }
1238
- // "Entire row clickable" (user request) — wrap the whole assembled
1239
- // string in ONE OSC 8 hyperlink instead of just the label. The command
1240
- // portion keeps its bold + bright-white treatment (no underline) so it
1241
- // still VISUALLY reads as a shell command the user should type, not a
1242
- // link — but if the user clicks anywhere on the row (label, domain
1243
- // hint, connector, even the command text), the terminal opens the URL.
1244
- // Clicking DOES NOT execute the command; it just opens the target URL,
1245
- // which is safe. Terminals that ignore OSC 8 render the whole row as
1246
- // styled text and no click behavior — the previous fallback (visible
1247
- // domain suffix) still keeps the destination readable.
1248
- const wrapWholeRowInHyperlink = (assembled) => {
1249
- if (!promo.url) return assembled;
1250
- if (!terminalSupportsHyperlinks()) return assembled;
1251
- let parsed;
1252
- try { parsed = new URL(promo.url); } catch { return assembled; }
1253
- if (parsed.protocol !== 'https:') return assembled;
1254
- if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return assembled;
1255
- const ESC = '';
1256
- return ESC + ']8;;' + parsed.href + ESC + '\\' + assembled + ESC + ']8;;' + ESC + '\\';
1257
- };
1258
- // Visual styling stays per-part. We only add the OSC 8 wrap around the
1259
- // combined string, so the whole row is one click target.
1260
- const labelStyled = promo.url ? UL_ON + label + UL_OFF : label;
1261
- if (!command) return wrapWholeRowInHyperlink(labelStyled + visibleUrlHint);
1262
- return wrapWholeRowInHyperlink(
1263
- labelStyled + visibleUrlHint
1264
- + DIM_ON + manageWord + DIM_OFF
1265
- + BOLD_ON + FG_BRIGHT_WHITE + command + FG_DEFAULT + BOLD_OFF
1266
- );
1267
- } catch (e) {
1268
- return null; // the promo row must never break the statusline
1269
- }
1270
- }
1271
-
1272
- // JSON output — delegates to CLI for accuracy; caller can use --json flag
1273
- function generateJSON() {
1274
- const d = getStatuslineData();
1275
- const git = getGitInfo();
1276
- return Object.assign({}, d, {
1277
- user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),
1278
- git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },
1279
- lastUpdated: new Date().toISOString(),
1280
- });
1281
- }
1282
-
1283
- // ─── Main ───────────────────────────────────────────────────────
1284
- if (process.argv.includes('--json')) {
1285
- console.log(JSON.stringify(generateJSON(), null, 2));
1286
- } else if (process.argv.includes('--compact')) {
1287
- console.log(JSON.stringify(generateJSON()));
1288
- } else {
1289
- console.log(generateStatusline());
1290
- }
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
+ // Header identity defaults to project/repository name. Set `author` to
32
+ // retain the previous `git config user.name` display (#2682).
33
+ identityMode: (process.env.RUFLO_STATUSLINE_IDENTITY || 'project').toLowerCase(),
34
+ // Session-cost display. Claude Code's cost.total_cost_usd is a client-side
35
+ // estimate that "may differ from your actual bill" and reads as misleading on
36
+ // subscription plans, where token usage is not billed per dollar. These let
37
+ // each user pick what the segment means to them without changing the default.
38
+ // RUFLO_STATUSLINE_COST_SYMBOL override the leading '$' (e.g. ⚡, €, 🌱);
39
+ // set to an empty string for the number alone.
40
+ // RUFLO_STATUSLINE_HIDE_COST 1/true/yes/on removes the segment entirely.
41
+ costSymbol: process.env.RUFLO_STATUSLINE_COST_SYMBOL ?? '$',
42
+ hideCost: /^(1|true|yes|on)$/i.test(process.env.RUFLO_STATUSLINE_HIDE_COST || ''),
43
+ };
44
+
45
+ const CWD = process.env.CLAUDE_PROJECT_DIR || process.cwd();
46
+ // Replaced by statusline-generator with the package root of the CLI that
47
+ // installed this helper. This survives custom npm prefixes and bundled Node
48
+ // runtimes whose process.execPath belongs to a different tree (#2811).
49
+ const BAKED_INSTALL_ROOT = "";
50
+
51
+ // ─── Delegation cache ───────────────────────────────────────────
52
+ // Cache the CLI JSON result so rapid prompt re-renders (Claude Code
53
+ // refreshes the statusline several times a second while streaming) don't
54
+ // re-invoke the CLI each time.
55
+ // #2337 bumped 10s → 60s.
56
+ // Followup for anthropics/claude-code#70200 (Windows console-flash bug —
57
+ // claude.exe spawns hook/statusline subprocesses without CREATE_NO_WINDOW,
58
+ // producing a visible cmd flash on every render): bumped 60s → 300s to
59
+ // reduce the flash rate 5x on Windows until the upstream fix ships.
60
+ // Tradeoff: stat/git counters update every 5min instead of every 1min;
61
+ // promo/insight row still rotates on its own tighter 20s promoFresh clock.
62
+ const CACHE_FILE = path.join(os.tmpdir(), 'ruflo-statusline-cache-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
63
+ const CACHE_TTL_MS = 300000;
64
+
65
+ // The promo/insight row is designed to rotate on a 20s cadence (funnel/
66
+ // rotation.ts's ROTATION_SLOT_MS / funnel/promo.ts's insight-slot check —
67
+ // duplicated here as a bare number since this generated script has no
68
+ // runtime import of the funnel module; keep in sync if that constant ever
69
+ // changes). The rotation slot is only ever (re)computed SERVER-SIDE inside
70
+ // the CLI subprocess this file shells out to — so a general 60s data cache
71
+ // (correct and necessary for #2337) silently made that 20s design
72
+ // unreachable: cache.fresh stayed true across 2-3 whole rotation slots,
73
+ // so the row visibly "didn't rotate" (user report). Fix: track promo
74
+ // freshness on its OWN, tighter clock — when it lags behind the current
75
+ // slot, fall through to a real CLI call even though the REST of the
76
+ // cached data (security/swarm/system) is still within CACHE_TTL_MS. This
77
+ // does not touch or regress #2337's fix; it only adds a narrower check.
78
+ const PROMO_ROTATION_SLOT_MS = 20000;
79
+
80
+ // Persistent last-known-good promo record. Lives outside the /tmp cache so it
81
+ // survives a full cache wipe / cache write race / CLI failure combo. Written
82
+ // every time we successfully render a promo; read as a last resort so the row
83
+ // never blinks out mid-session (was: 'promo shows then hides' bug report).
84
+ const PROMO_MEMO_FILE = path.join(os.homedir(), '.ruflo', 'statusline-promo.json');
85
+ 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.
86
+
87
+ // #2337: resolve an already-installed @claude-flow/cli (or ruflo) bin so we
88
+ // can invoke it directly via `node`. The previous version called
89
+ // `npx --yes @claude-flow/cli@latest` on every uncached render, which forces
90
+ // a registry resolution + cold-start of the entire CLI per render. With
91
+ // multiple concurrent Claude Code sessions this storms the host (reporter
92
+ // saw load average 40-65 on a 12-core box).
93
+ //
94
+ // Returns EVERY existing bin/cli.js candidate, in preference order (project,
95
+ // monorepo, plugin marketplace, global node_modules including custom-prefix
96
+ // layouts like ~/.npm-global) — mirrors getPkgVersion()'s own path probing.
97
+ //
98
+ // Returns a list, not a single winner: `fs.existsSync` only proves a file is
99
+ // present, not that it actually runs. A marketplace/npx-cached install can
100
+ // exist on disk but be broken (observed in practice: a stale marketplace
101
+ // checkout whose dist/ imports a workspace package, '@claude-flow/cli-core',
102
+ // that isn't bundled there — every invocation throws ERR_MODULE_NOT_FOUND).
103
+ // Picking the first EXISTING path and never falling through meant a single
104
+ // broken install silently killed the promo row for the entire session (the
105
+ // CLI call always failed, so the memo could never refresh and eventually
106
+ // expired). getStatuslineData() now walks this whole list and tries the next
107
+ // candidate on failure, so one broken install can't permanently wedge it.
108
+ function resolveCliBinCandidates() {
109
+ const candidates = [];
110
+ try {
111
+ const home = os.homedir();
112
+ candidates.push(
113
+ path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'bin', 'cli.js'),
114
+ path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'bin', 'cli.js'),
115
+ path.join(CWD, 'node_modules', 'ruflo', 'bin', 'cli.js'),
116
+ path.join(CWD, 'v3', '@claude-flow', 'cli', 'bin', 'cli.js'),
117
+ );
118
+ try {
119
+ const binDir = path.dirname(process.execPath);
120
+ const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
121
+ for (const prefix of [process.env.npm_config_prefix, process.env.PREFIX, path.join(home, '.npm-global')]) {
122
+ if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
123
+ }
124
+ for (const gm of globalModuleDirs) {
125
+ candidates.push(
126
+ path.join(gm, 'ruflo', 'bin', 'cli.js'),
127
+ path.join(gm, '@claude-flow', 'cli', 'bin', 'cli.js'),
128
+ );
129
+ }
130
+ } catch { /* ignore */ }
131
+ } catch { /* ignore */ }
132
+ return candidates.filter((p) => {
133
+ try {
134
+ if (!fs.existsSync(p)) return false;
135
+ // A candidate's bin/cli.js can exist on disk while its compiled
136
+ // dist/ never got built (Claude Code's own plugin marketplace just
137
+ // git-clones the repo — no install/build step — so every marketplace
138
+ // install is a source-only checkout by construction). Importing
139
+ // dist/src/index.js from bin/cli.js then throws MODULE_NOT_FOUND on
140
+ // every real command; only --version happens to survive it. Check
141
+ // for the compiled entrypoint too so a doomed candidate is skipped
142
+ // up front instead of wasting a spawn-and-fail on every render.
143
+ return fs.existsSync(path.join(path.dirname(p), '..', 'dist', 'src', 'index.js'));
144
+ } catch { return false; }
145
+ });
146
+ }
147
+
148
+ // Return { fresh, promoFresh, data }. 'fresh' is true only if within the TTL
149
+ // — but data is returned regardless (stale-while-revalidate). This lets us
150
+ // serve last known state (specifically the promo row) when the CLI is
151
+ // slow/unavailable, so users don't see the funnel row flicker in and out on
152
+ // cache expiry. 'promoFresh' is a SEPARATE, tighter check on the same clock
153
+ // as PROMO_ROTATION_SLOT_MS — see that constant's comment for why the promo
154
+ // row needs its own freshness bound distinct from the general 60s TTL.
155
+ function readCache() {
156
+ try {
157
+ if (fs.existsSync(CACHE_FILE)) {
158
+ const raw = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));
159
+ if (raw && raw._ts && raw.data) {
160
+ const age = Date.now() - raw._ts;
161
+ return { fresh: age < CACHE_TTL_MS, promoFresh: age < PROMO_ROTATION_SLOT_MS, data: raw.data };
162
+ }
163
+ }
164
+ } catch { /* ignore */ }
165
+ return { fresh: false, promoFresh: false, data: null };
166
+ }
167
+
168
+ function writeCache(data) {
169
+ try { fs.writeFileSync(CACHE_FILE, JSON.stringify({ _ts: Date.now(), data }), 'utf-8'); } catch { /* ignore */ }
170
+ // Also memoize any promo we saw so the row can survive future CLI hiccups.
171
+ try {
172
+ if (data && data.promo && typeof data.promo === 'object') {
173
+ fs.mkdirSync(path.dirname(PROMO_MEMO_FILE), { recursive: true, mode: 0o700 });
174
+ fs.writeFileSync(PROMO_MEMO_FILE, JSON.stringify({ _ts: Date.now(), promo: data.promo }), { encoding: 'utf-8', mode: 0o600 });
175
+ }
176
+ } catch { /* ignore */ }
177
+ }
178
+
179
+ // Last resort: read a memoized promo (up to 6h old). Used when no cache and
180
+ // no CLI response is available — the row still renders, so users don't see
181
+ // the disclosure blink out. Returns null when the memo is absent, expired,
182
+ // or malformed. Never throws.
183
+ function readPromoMemo() {
184
+ try {
185
+ if (!fs.existsSync(PROMO_MEMO_FILE)) return null;
186
+ const raw = JSON.parse(fs.readFileSync(PROMO_MEMO_FILE, 'utf-8'));
187
+ if (raw && raw._ts && (Date.now() - raw._ts) < PROMO_MEMO_TTL_MS && raw.promo) {
188
+ return raw.promo;
189
+ }
190
+ } catch { /* ignore */ }
191
+ return null;
192
+ }
193
+
194
+ /**
195
+ * Single source of truth: delegate to the CLI hooks statusline --json command.
196
+ * Falls back to a minimal static object on failure so the statusline still renders.
197
+ *
198
+ * Fix for ruflo#2195: the previous local readers returned 0 for AgentDB patterns
199
+ * (missed the .swarm/memory.db → AgentDB path), computed dddProgress wrong,
200
+ * and only counted ADRs in v3/implementation/adrs/ (missed v3/docs/adr/).
201
+ */
202
+ // Overlay the memoized promo onto any data object that's missing one. This is
203
+ // the safety net that keeps the funnel row rendered when an OLDER cached CLI
204
+ // version is picked up by npx — that older CLI succeeds but omits promo, so
205
+ // the JSON round-trips clean but without our row. We patch it back here.
206
+ function overlayMemoPromo(data) {
207
+ if (data && !data.promo) {
208
+ const memoPromo = readPromoMemo();
209
+ if (memoPromo) data.promo = memoPromo;
210
+ }
211
+ return data;
212
+ }
213
+
214
+ function getStatuslineData() {
215
+ const cache = readCache();
216
+ // Both clocks must be satisfied to skip the CLI call entirely: the general
217
+ // 60s TTL (#2337 — don't re-spawn the CLI on every rapid re-render) AND the
218
+ // tighter promo-rotation clock (this fix — don't let a still-fresh 60s
219
+ // cache silently freeze the promo/insight row across multiple 20s slots).
220
+ if (cache.fresh && cache.promoFresh) {
221
+ return applyLocalOverlays(overlayMemoPromo(cache.data));
222
+ }
223
+
224
+ // #2337: prefer an already-installed CLI bin via direct `node` invocation —
225
+ // no npx, no registry round-trip, no @latest re-resolve per render. Try
226
+ // every candidate that actually EXISTS (not just the first) before falling
227
+ // back to `npx --prefer-offline @claude-flow/cli` (no @latest); an existing
228
+ // but broken install (e.g. a stale marketplace checkout missing a bundled
229
+ // workspace dep) must not block trying the next one.
230
+ //
231
+ // No `2>/dev/null` here (deliberately) — the execSync call below already
232
+ // sets stdio: ['pipe','pipe','pipe'], which captures/discards stderr at the
233
+ // Node level regardless of shell. The redirect was redundant on POSIX and
234
+ // actively broke every candidate on Windows: cmd.exe (execSync's default
235
+ // shell there) doesn't understand /dev/null, so the CLI delegation always
236
+ // failed, silently degrading every render to buildLocalFallback() — 0%
237
+ // intelligence and an empty promo row (the memo cache that keeps the row
238
+ // populated across CLI hiccups is only ever written from a SUCCESSFUL
239
+ // delegation, so it could never get seeded on Windows either).
240
+ const cmds = resolveCliBinCandidates()
241
+ .map((bin) => '"' + process.execPath + '" "' + bin + '" hooks statusline --json')
242
+ .concat(['npx --prefer-offline @claude-flow/cli hooks statusline --json']);
243
+ for (const cmd of cmds) {
244
+ try {
245
+ const raw = execSync(
246
+ cmd,
247
+ { encoding: 'utf-8', timeout: 8000, stdio: ['pipe', 'pipe', 'pipe'], cwd: CWD, windowsHide: true }
248
+ ).trim();
249
+ // The CLI may emit preamble lines before the JSON — find the first '{'.
250
+ const jsonStart = raw.indexOf('{');
251
+ if (jsonStart === -1) throw new Error('no JSON in CLI output');
252
+ const data = JSON.parse(raw.slice(jsonStart));
253
+ // Overlay every block the CLI JSON omits (adrs/agentdb/tests/hooks/integration)
254
+ // with real local reads, so those segments reflect actual state instead of 0.
255
+ applyLocalOverlays(data);
256
+ overlayMemoPromo(data);
257
+ writeCache(data);
258
+ return data;
259
+ } catch { /* this candidate unavailable, broken, or timed out — try the next */ }
260
+ }
261
+
262
+ // Stale-while-revalidate: if we have any cached data, keep serving it so the
263
+ // funnel row doesn't flicker on CLI hiccups. Overlay fresh local reads for
264
+ // the segments the CLI JSON doesn't populate; the promo row survives.
265
+ if (cache.data) {
266
+ applyLocalOverlays(cache.data);
267
+ overlayMemoPromo(cache.data);
268
+ return cache.data;
269
+ }
270
+
271
+ // Last resort: local probes + memo. Users still see the funnel row.
272
+ return overlayMemoPromo(buildLocalFallback());
273
+ }
274
+
275
+ // Count ADRs from BOTH known directories (fix for ruflo#2195: old code missed
276
+ // v3/docs/adr/ which holds ADR-088..ADR-137, i.e. 41 of the 128 total ADRs).
277
+ function getLocalADRCount() {
278
+ const adrDirs = [
279
+ path.join(CWD, 'v3', 'implementation', 'adrs'),
280
+ path.join(CWD, 'v3', 'docs', 'adr'),
281
+ path.join(CWD, 'docs', 'adrs'),
282
+ path.join(CWD, '.claude-flow', 'adrs'),
283
+ ];
284
+ let total = 0;
285
+ for (const dir of adrDirs) {
286
+ try {
287
+ if (fs.existsSync(dir)) {
288
+ const files = fs.readdirSync(dir).filter(function(f) {
289
+ return f.endsWith('.md') && (f.startsWith('ADR-') || f.startsWith('adr-') || /^\d{4}-/.test(f));
290
+ });
291
+ total += files.length;
292
+ }
293
+ } catch { /* ignore */ }
294
+ }
295
+ return { count: total, implemented: total, compliance: 0 };
296
+ }
297
+
298
+ // ─── Local overlays for segments the CLI JSON omits ──────────────
299
+ // 'hooks statusline --json' only returns user/v3Progress/security/swarm/system.
300
+ // agentdb/tests/hooks/integration are never populated, so without these overlays
301
+ // they render as a permanent 0. Each reader is cheap and degrades to zeros.
302
+
303
+ // Real AgentDB stats from the local memory DB. Vectors live in .swarm/memory.db
304
+ // (sql.js + HNSW); ruvector.db is an opaque redb store counted only toward size.
305
+ // One read-only sqlite3 query (mode=ro never takes a write lock the daemon owns).
306
+ function getLocalAgentDB() {
307
+ const result = { vectorCount: 0, dbSizeKB: 0, hasHnsw: false };
308
+ try {
309
+ let bytes = 0;
310
+ for (const f of ['.swarm/memory.db', 'ruvector.db']) {
311
+ try { bytes += fs.statSync(path.join(CWD, f)).size; } catch { /* missing */ }
312
+ }
313
+ result.dbSizeKB = Math.round(bytes / 1024);
314
+
315
+ const memDb = path.join(CWD, '.swarm', 'memory.db');
316
+ if (fs.existsSync(memDb)) {
317
+ const Q = String.fromCharCode(34);
318
+ // Two INDEPENDENT statements -- do NOT combine into one. Coupling the
319
+ // vector count with the vector_indexes row count in a single statement
320
+ // meant that on a DB missing the vector_indexes table (older/agentdb-
321
+ // written DBs), the whole statement failed at PREPARE time (SQLite
322
+ // compiles the full SQL before running), so the valid memory_entries
323
+ // count was discarded too and the statusline showed Vectors 0 despite
324
+ // thousands of real vectors. Split so a missing table can only zero the
325
+ // HNSW flag, never the count. The init self-heal provisions the table so
326
+ // the flag recovers on the next ruflo init / MCP start.
327
+ const countSql = Q + 'SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL;' + Q;
328
+ const vc = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + countSql, 1500);
329
+ if (vc) result.vectorCount = parseInt(vc, 10) || 0;
330
+ // HNSW flag: separate statement. If vector_indexes is absent, sqlite3
331
+ // exits non-zero and safeExec returns empty -- hasHnsw stays false (exact
332
+ // original semantics: at least one index-config row present).
333
+ const hnswSql = Q + 'SELECT COUNT(*) FROM vector_indexes;' + Q;
334
+ const hn = safeExec("sqlite3 'file:" + memDb + "?mode=ro' " + hnswSql, 1500);
335
+ if (hn) result.hasHnsw = (parseInt(hn, 10) || 0) > 0;
336
+ }
337
+ } catch { /* ignore */ }
338
+ return result;
339
+ }
340
+
341
+ // Count test files via a bounded directory walk (no file reads).
342
+ function getLocalTests() {
343
+ let testFiles = 0;
344
+ function countTests(dir, depth) {
345
+ if ((depth || 0) > 4) return;
346
+ try {
347
+ if (!fs.existsSync(dir)) return;
348
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
349
+ if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') {
350
+ countTests(path.join(dir, e.name), (depth || 0) + 1);
351
+ } else if (e.isFile() && (e.name.includes('.test.') || e.name.includes('.spec.') || e.name.startsWith('test_') || e.name.startsWith('spec_'))) {
352
+ testFiles++;
353
+ }
354
+ }
355
+ } catch { /* ignore */ }
356
+ }
357
+ for (const d of ['tests', 'test', '__tests__', 'src', 'v3']) countTests(path.join(CWD, d));
358
+ return { testFiles, testCases: testFiles * 4 };
359
+ }
360
+
361
+ // Count configured hooks from project .claude/settings.json. Claude Code hooks
362
+ // have no enabled/disabled flag, so every configured hook counts as enabled.
363
+ function getLocalHooks() {
364
+ const result = { enabled: 0, total: 0 };
365
+ try {
366
+ const settings = readJSON(path.join(CWD, '.claude', 'settings.json'));
367
+ const hooks = settings && settings.hooks;
368
+ if (hooks && typeof hooks === 'object') {
369
+ let n = 0;
370
+ for (const ev of Object.keys(hooks)) {
371
+ const groups = hooks[ev];
372
+ if (Array.isArray(groups)) {
373
+ for (const g of groups) {
374
+ if (g && Array.isArray(g.hooks)) n += g.hooks.length;
375
+ }
376
+ }
377
+ }
378
+ result.total = n;
379
+ result.enabled = n;
380
+ }
381
+ } catch { /* ignore */ }
382
+ return result;
383
+ }
384
+
385
+ // Best-effort integration block: DB presence + locally-configured stdio MCP
386
+ // servers (project .mcp.json + global ~/.claude.json). Remote connectors are
387
+ // account-managed and not present in local config, so they are not counted.
388
+ function getLocalIntegration() {
389
+ const integration = { mcpServers: { enabled: 0, total: 0 }, hasDatabase: false };
390
+ try {
391
+ for (const f of ['.swarm/memory.db', 'ruvector.db']) {
392
+ if (fs.existsSync(path.join(CWD, f))) { integration.hasDatabase = true; break; }
393
+ }
394
+ const names = new Set();
395
+ const projMcp = readJSON(path.join(CWD, '.mcp.json'));
396
+ if (projMcp && projMcp.mcpServers) for (const k of Object.keys(projMcp.mcpServers)) names.add(k);
397
+ const claudeJson = readJSON(path.join(os.homedir(), '.claude.json'));
398
+ if (claudeJson) {
399
+ if (claudeJson.mcpServers) for (const k of Object.keys(claudeJson.mcpServers)) names.add(k);
400
+ const proj = claudeJson.projects && claudeJson.projects[CWD];
401
+ if (proj && proj.mcpServers && !Array.isArray(proj.mcpServers)) {
402
+ for (const k of Object.keys(proj.mcpServers)) names.add(k);
403
+ }
404
+ }
405
+ integration.mcpServers.total = names.size;
406
+ integration.mcpServers.enabled = names.size;
407
+ } catch { /* ignore */ }
408
+ return integration;
409
+ }
410
+
411
+ // ─── Security freshness overlay (ruvnet/ruflo#2776) ──────────────
412
+ // The shipped CLI producer (dist/src/funnel/local-signals.js getSecurityStatus)
413
+ // only ever emits PENDING / CLEAN / ISSUES — it captures `scannedAt` but never
414
+ // inspects it, so a year-old scan renders 🛡 ✓ forever and the renderer's
415
+ // STALE / IN_PROGRESS branches are unreachable. Worse, when CLI delegation
416
+ // fails, the stale-while-revalidate cache (readCache() below) keeps serving
417
+ // the pre-scan PENDING pill indefinitely, so a user who runs the advertised
418
+ // `ruflo security scan` sees no change — the pill freezes at "scan pending".
419
+ //
420
+ // This overlay recomputes the security block from disk on EVERY render (same
421
+ // pattern as adrs/agentdb/tests/hooks above), which:
422
+ // 1) Makes STALE reachable — when the newest scan is older than
423
+ // RUFLO_SCAN_STALE_HOURS (default 24h — matches the CVE feed refresh
424
+ // cadence), report STALE regardless of what the cached CLI JSON says.
425
+ // 2) Makes IN_PROGRESS reachable — when a `scan-in-progress` marker file
426
+ // exists and is younger than SECURITY_IN_PROGRESS_MAX_MIN (guards against
427
+ // a crashed scan leaving the marker behind).
428
+ // 3) Caps the "scan pending" display window — if PENDING has been shown for
429
+ // >RUFLO_SCAN_PENDING_CAP_MIN (default 30) without a completion write,
430
+ // switch to STALE and stop rendering the yellow indicator. The tracker
431
+ // lives in ~/.ruflo/statusline-scan-pending-since.json, keyed by CWD
432
+ // hash so multiple project checkouts don't collide.
433
+ // 4) Since this runs AFTER readCache() serves stale data, it bypasses the
434
+ // "pill freezes at PENDING" freeze in defect 2 — the overlay reads
435
+ // fresh disk state even when the CLI delegation is broken.
436
+ const SECURITY_STALE_HOURS = Math.max(1, parseInt(process.env.RUFLO_SCAN_STALE_HOURS || '24', 10) || 24);
437
+ const SECURITY_PENDING_CAP_MIN = Math.max(1, parseInt(process.env.RUFLO_SCAN_PENDING_CAP_MIN || '30', 10) || 30);
438
+ const SECURITY_IN_PROGRESS_MAX_MIN = 30; // marker older than this = crashed scan; treat as absent
439
+ const PENDING_TRACK_FILE = path.join(os.homedir(), '.ruflo', 'statusline-scan-pending-since.json');
440
+ const CWD_KEY = require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 12);
441
+
442
+ function readPendingSince() {
443
+ try {
444
+ if (!fs.existsSync(PENDING_TRACK_FILE)) return null;
445
+ const raw = JSON.parse(fs.readFileSync(PENDING_TRACK_FILE, 'utf-8'));
446
+ if (raw && typeof raw === 'object' && typeof raw[CWD_KEY] === 'number') return raw[CWD_KEY];
447
+ } catch { /* ignore */ }
448
+ return null;
449
+ }
450
+
451
+ function writePendingSince(ts) {
452
+ try {
453
+ let obj = {};
454
+ if (fs.existsSync(PENDING_TRACK_FILE)) {
455
+ try { obj = JSON.parse(fs.readFileSync(PENDING_TRACK_FILE, 'utf-8')) || {}; } catch { obj = {}; }
456
+ }
457
+ if (ts === null) { delete obj[CWD_KEY]; } else { obj[CWD_KEY] = ts; }
458
+ fs.mkdirSync(path.dirname(PENDING_TRACK_FILE), { recursive: true, mode: 0o700 });
459
+ fs.writeFileSync(PENDING_TRACK_FILE, JSON.stringify(obj), { encoding: 'utf-8', mode: 0o600 });
460
+ } catch { /* ignore */ }
461
+ }
462
+
463
+ function getLocalSecurity(cliSecurity) {
464
+ const base = (cliSecurity && typeof cliSecurity === 'object')
465
+ ? Object.assign({}, cliSecurity)
466
+ : { status: 'NONE', findings: 0, cvesFixed: 0, totalCves: 0 };
467
+ base.findings = Math.max(0, base.findings || 0);
468
+
469
+ const scanDir = path.join(CWD, '.claude', 'security-scans');
470
+
471
+ // Detect a live in-progress marker (writer opts-in by writing this file).
472
+ let inProgress = false;
473
+ try {
474
+ const marker = path.join(scanDir, 'scan-in-progress');
475
+ if (fs.existsSync(marker)) {
476
+ const ageMin = (Date.now() - fs.statSync(marker).mtimeMs) / 60000;
477
+ if (ageMin < SECURITY_IN_PROGRESS_MAX_MIN) inProgress = true;
478
+ }
479
+ } catch { /* ignore */ }
480
+
481
+ // Find newest scan-*.json by mtime and read its findings/timestamp.
482
+ let newestPath = null;
483
+ let newestMtime = 0;
484
+ try {
485
+ if (fs.existsSync(scanDir)) {
486
+ for (const name of fs.readdirSync(scanDir)) {
487
+ if (!name.startsWith('scan-') || !name.endsWith('.json')) continue;
488
+ try {
489
+ const st = fs.statSync(path.join(scanDir, name));
490
+ if (st.mtimeMs > newestMtime) { newestMtime = st.mtimeMs; newestPath = path.join(scanDir, name); }
491
+ } catch { /* ignore */ }
492
+ }
493
+ }
494
+ } catch { /* ignore */ }
495
+
496
+ if (newestPath) {
497
+ // We have a scan on disk — the never-scanned pending tracker is no longer
498
+ // relevant. Clear it so a re-created directory can start a fresh window.
499
+ writePendingSince(null);
500
+
501
+ let scannedAtMs = newestMtime;
502
+ let findings = base.findings;
503
+ try {
504
+ const j = JSON.parse(fs.readFileSync(newestPath, 'utf-8'));
505
+ // scannedAt (CLI producer's field name) OR timestamp (writer's field name).
506
+ const isoStr = (j && (j.scannedAt || j.timestamp)) || null;
507
+ if (isoStr) {
508
+ const t = Date.parse(isoStr);
509
+ if (!isNaN(t)) scannedAtMs = t;
510
+ }
511
+ // findings may be a number, an array, or nested in summary.total.
512
+ if (j) {
513
+ if (typeof j.findings === 'number') findings = j.findings;
514
+ else if (Array.isArray(j.findings)) findings = j.findings.length;
515
+ else if (j.summary && typeof j.summary.total === 'number') findings = j.summary.total;
516
+ }
517
+ } catch { /* ignore parse — fall back to mtime + cached findings */ }
518
+
519
+ base.findings = Math.max(0, findings || 0);
520
+ base.scannedAt = new Date(scannedAtMs).toISOString();
521
+
522
+ const ageHours = (Date.now() - scannedAtMs) / 3600000;
523
+ if (ageHours >= SECURITY_STALE_HOURS) {
524
+ // Stale but findings still render red (a year-old ISSUES scan is still bad).
525
+ base.status = 'STALE';
526
+ } else if (inProgress) {
527
+ base.status = 'IN_PROGRESS';
528
+ } else if (base.findings > 0) {
529
+ base.status = 'ISSUES';
530
+ } else {
531
+ base.status = 'CLEAN';
532
+ }
533
+ return base;
534
+ }
535
+
536
+ // No scan file. If a live marker exists, we're mid-scan.
537
+ if (inProgress) {
538
+ base.status = 'IN_PROGRESS';
539
+ // Reset the pending tracker so, if the scan crashes mid-flight, the next
540
+ // render starts a fresh N-minute pending window instead of an already-expired one.
541
+ writePendingSince(null);
542
+ return base;
543
+ }
544
+
545
+ // Truly never-scanned: track how long we've shown PENDING. After the cap,
546
+ // escalate to STALE with the dim/gray glyph so the pill visibly stops
547
+ // shouting for attention — the user has either ignored it for 30 min or
548
+ // the scan is silently failing to write.
549
+ let pendingSince = readPendingSince();
550
+ if (pendingSince === null || typeof pendingSince !== 'number') {
551
+ pendingSince = Date.now();
552
+ writePendingSince(pendingSince);
553
+ }
554
+ const pendingAgeMin = (Date.now() - pendingSince) / 60000;
555
+ base.status = (pendingAgeMin >= SECURITY_PENDING_CAP_MIN) ? 'STALE' : 'PENDING';
556
+ return base;
557
+ }
558
+
559
+ // Cached pattern count. The store is routinely >10MB (14.5MB / 1277 patterns on
560
+ // the machine this was diagnosed on, costing 53ms to read+parse), and the
561
+ // statusline re-renders on every prompt, so the parse is keyed on the file's
562
+ // mtime+size and reused until the store actually changes.
563
+ const PATTERN_COUNT_CACHE = path.join(os.tmpdir(), 'ruflo-statusline-patterns-' + require('crypto').createHash('md5').update(CWD).digest('hex').slice(0, 8) + '.json');
564
+
565
+ function countPatternsCached(file) {
566
+ let stat;
567
+ try { stat = fs.statSync(file); } catch { return 0; }
568
+ const key = stat.mtimeMs + ':' + stat.size;
569
+
570
+ try {
571
+ const memo = JSON.parse(fs.readFileSync(PATTERN_COUNT_CACHE, 'utf-8'));
572
+ if (memo && memo[file] && memo[file].key === key) return memo[file].count;
573
+ } catch { /* no memo yet, or unreadable — fall through and recount */ }
574
+
575
+ let count = 0;
576
+ try {
577
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
578
+ if (Array.isArray(raw)) count = raw.length;
579
+ else if (raw && Array.isArray(raw.patterns)) count = raw.patterns.length;
580
+ else if (raw && typeof raw === 'object') count = Object.keys(raw).length;
581
+ } catch { return 0; }
582
+
583
+ try {
584
+ let memo = {};
585
+ try { memo = JSON.parse(fs.readFileSync(PATTERN_COUNT_CACHE, 'utf-8')) || {}; } catch { /* start fresh */ }
586
+ memo[file] = { key, count };
587
+ fs.writeFileSync(PATTERN_COUNT_CACHE, JSON.stringify(memo));
588
+ } catch { /* cache is an optimisation, never a requirement */ }
589
+
590
+ return count;
591
+ }
592
+
593
+ // `system` is nominally CLI-populated, but the pattern store is on disk, so a
594
+ // dead CLI must not render as "no learning". Without this, every candidate in
595
+ // resolveCliBinCandidates() failing (a source-only marketplace checkout, or an
596
+ // npx fetch that dies in a workspace root) silently degraded the brain to a
597
+ // hardcoded 0% while the overlaid segments beside it kept showing live data —
598
+ // indistinguishable from a genuine zero. Same reasoning as getLocalAgentDB(),
599
+ // which had to start reading locally after the statusline reported "Vectors 0"
600
+ // on a database holding thousands.
601
+ function getLocalIntelligence(current) {
602
+ const base = (current && typeof current === 'object') ? current : {};
603
+ if (typeof base.intelligencePct === 'number' && base.intelligencePct > 0) return base;
604
+
605
+ for (const file of [
606
+ path.join(CWD, '.claude-flow', 'neural', 'patterns.json'),
607
+ path.join(os.homedir(), '.claude-flow', 'neural', 'patterns.json'),
608
+ ]) {
609
+ const n = countPatternsCached(file);
610
+ if (n > 0) {
611
+ base.intelligencePct = Math.min(100, Math.floor(n / 10));
612
+ return base;
613
+ }
614
+ }
615
+
616
+ // No CLI value and no local store: unknown, which is not the same as zero.
617
+ base.intelligencePct = null;
618
+ return base;
619
+ }
620
+
621
+ // Overlay every locally-derived block onto the CLI data (mutates in place).
622
+ function applyLocalOverlays(data) {
623
+ data.adrs = getLocalADRCount();
624
+ data.agentdb = getLocalAgentDB();
625
+ data.tests = getLocalTests();
626
+ data.hooks = getLocalHooks();
627
+ data.integration = getLocalIntegration();
628
+ // Security overlay: recompute freshness from disk on every render so cached
629
+ // CLI JSON can never freeze the pill at PENDING. See getLocalSecurity() above.
630
+ data.security = getLocalSecurity(data.security);
631
+ data.system = getLocalIntelligence(data.system);
632
+ return data;
633
+ }
634
+
635
+ // Minimal local fallback when the CLI is not installed or times out.
636
+ // Returns a structure that matches the CLI JSON schema so the renderer works.
637
+ function buildLocalFallback() {
638
+ const memMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024);
639
+
640
+ return applyLocalOverlays({
641
+ user: { name: 'user', gitBranch: '', modelName: 'Claude Code' },
642
+ v3Progress: { domainsCompleted: 0, totalDomains: 5, dddProgress: 0, patternsLearned: 0, sessionsCompleted: 0 },
643
+ security: { status: 'NONE', findings: 0, cvesFixed: 0, totalCves: 0 },
644
+ swarm: { activeAgents: 0, maxAgents: CONFIG.maxAgents, coordinationActive: false },
645
+ system: { memoryMB: memMB, contextPct: 0, intelligencePct: null, subAgents: 0 },
646
+ lastUpdated: new Date().toISOString(),
647
+ });
648
+ }
649
+
650
+ // ANSI colors
651
+ const c = {
652
+ reset: '\x1b[0m',
653
+ bold: '\x1b[1m',
654
+ dim: '\x1b[2m',
655
+ red: '\x1b[0;31m',
656
+ green: '\x1b[0;32m',
657
+ yellow: '\x1b[0;33m',
658
+ blue: '\x1b[0;34m',
659
+ purple: '\x1b[0;35m',
660
+ cyan: '\x1b[0;36m',
661
+ brightRed: '\x1b[1;31m',
662
+ brightGreen: '\x1b[1;32m',
663
+ brightYellow: '\x1b[1;33m',
664
+ brightBlue: '\x1b[1;34m',
665
+ brightPurple: '\x1b[1;35m',
666
+ brightCyan: '\x1b[1;36m',
667
+ brightWhite: '\x1b[1;37m',
668
+ };
669
+
670
+ // Safe execSync with strict timeout (returns empty string on failure)
671
+ function safeExec(cmd, timeoutMs) {
672
+ try {
673
+ return execSync(cmd, {
674
+ encoding: 'utf-8',
675
+ timeout: timeoutMs || 2000,
676
+ stdio: ['pipe', 'pipe', 'pipe'],
677
+ // Windows: without this, every execSync spawns cmd.exe /d /s /c which
678
+ // flashes a visible console window every render (~1/min via the 60s
679
+ // cache TTL). windowsHide runs the child in a hidden window instead.
680
+ // No-op on POSIX. Fix for #2XXX (user report: "cmd prompt keeps opening").
681
+ windowsHide: true,
682
+ }).trim();
683
+ } catch {
684
+ return '';
685
+ }
686
+ }
687
+
688
+ // Safe JSON file reader (returns null on failure)
689
+ function readJSON(filePath) {
690
+ try {
691
+ if (fs.existsSync(filePath)) {
692
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
693
+ }
694
+ } catch { /* ignore */ }
695
+ return null;
696
+ }
697
+
698
+ // ─── Git info (pure-Node / single exec — needed for branch display) ──────────
699
+
700
+ function getGitInfo() {
701
+ const result = {
702
+ name: path.basename(CWD) || 'project', gitBranch: '', modified: 0, untracked: 0,
703
+ staged: 0, ahead: 0, behind: 0,
704
+ };
705
+
706
+ const script = [
707
+ 'git rev-parse --show-toplevel 2>/dev/null || pwd',
708
+ 'echo "---SEP---"',
709
+ 'git config user.name 2>/dev/null || echo user',
710
+ 'echo "---SEP---"',
711
+ 'git branch --show-current 2>/dev/null',
712
+ 'echo "---SEP---"',
713
+ 'git status --porcelain 2>/dev/null',
714
+ 'echo "---SEP---"',
715
+ 'git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null || echo "0 0"',
716
+ ].join('; ');
717
+
718
+ const raw = safeExec("sh -c '" + script + "'", 3000);
719
+ if (!raw) return result;
720
+
721
+ const parts = raw.split('---SEP---').map(function(s) { return s.trim(); });
722
+ if (parts.length >= 5) {
723
+ const projectName = path.basename(parts[0] || CWD) || path.basename(CWD) || 'project';
724
+ const authorName = parts[1] || 'user';
725
+ result.name = CONFIG.identityMode === 'author' ? authorName : projectName;
726
+ result.gitBranch = parts[2] || '';
727
+
728
+ if (parts[3]) {
729
+ for (const line of parts[3].split('\n')) {
730
+ if (!line || line.length < 2) continue;
731
+ const x = line[0], y = line[1];
732
+ if (x === '?' && y === '?') { result.untracked++; continue; }
733
+ if (x !== ' ' && x !== '?') result.staged++;
734
+ if (y !== ' ' && y !== '?') result.modified++;
735
+ }
736
+ }
737
+
738
+ const ab = (parts[4] || '0 0').split(/\s+/);
739
+ result.ahead = parseInt(ab[0]) || 0;
740
+ result.behind = parseInt(ab[1]) || 0;
741
+ }
742
+
743
+ return result;
744
+ }
745
+
746
+ // Detect model name from Claude config (pure file reads, no exec)
747
+ function getModelName() {
748
+ try {
749
+ const claudeConfig = readJSON(path.join(os.homedir(), '.claude.json'));
750
+ if (claudeConfig && claudeConfig.projects) {
751
+ for (const [projectPath, projectConfig] of Object.entries(claudeConfig.projects)) {
752
+ if (CWD === projectPath || CWD.startsWith(projectPath + '/')) {
753
+ const usage = projectConfig.lastModelUsage;
754
+ if (usage) {
755
+ const ids = Object.keys(usage);
756
+ if (ids.length > 0) {
757
+ let modelId = ids[ids.length - 1];
758
+ let latest = 0;
759
+ for (const id of ids) {
760
+ const ts = usage[id] && usage[id].lastUsedAt ? new Date(usage[id].lastUsedAt).getTime() : 0;
761
+ if (ts > latest) { latest = ts; modelId = id; }
762
+ }
763
+ if (modelId.includes('opus')) return 'Opus 4.8';
764
+ if (modelId.includes('sonnet')) return 'Sonnet 4.6';
765
+ if (modelId.includes('haiku')) return 'Haiku 4.5';
766
+ return modelId.split('-').slice(1, 3).join(' ');
767
+ }
768
+ }
769
+ break;
770
+ }
771
+ }
772
+ }
773
+ } catch { /* ignore */ }
774
+
775
+ // Fallback: settings.json model field
776
+ const settings = getSettings();
777
+ if (settings && settings.model) {
778
+ const m = settings.model;
779
+ if (m.includes('opus')) return 'Opus 4.8';
780
+ if (m.includes('sonnet')) return 'Sonnet 4.6';
781
+ if (m.includes('haiku')) return 'Haiku 4.5';
782
+ }
783
+ return 'Claude Code';
784
+ }
785
+
786
+ // ─── Stdin reader (Claude Code pipes session JSON) ──────────────
787
+ // Claude Code sends session JSON via stdin. Read synchronously so the
788
+ // script works both when invoked by Claude Code (stdin has JSON) and
789
+ // when run manually from terminal (stdin is empty/tty).
790
+ let _stdinData = null;
791
+ function getStdinData() {
792
+ if (_stdinData !== undefined && _stdinData !== null) return _stdinData;
793
+ try {
794
+ if (process.stdin.isTTY) { _stdinData = null; return null; }
795
+ const chunks = [];
796
+ const buf = Buffer.alloc(4096);
797
+ let bytesRead;
798
+ try {
799
+ while ((bytesRead = fs.readSync(0, buf, 0, buf.length, null)) > 0) {
800
+ chunks.push(buf.slice(0, bytesRead));
801
+ }
802
+ } catch { /* EOF or read error */ }
803
+ const raw = Buffer.concat(chunks).toString('utf-8').trim();
804
+ _stdinData = (raw && raw.startsWith('{')) ? JSON.parse(raw) : null;
805
+ } catch {
806
+ _stdinData = null;
807
+ }
808
+ return _stdinData;
809
+ }
810
+
811
+ function getModelFromStdin() {
812
+ const data = getStdinData();
813
+ return (data && data.model && data.model.display_name) ? data.model.display_name : null;
814
+ }
815
+
816
+ function getContextFromStdin() {
817
+ const data = getStdinData();
818
+ if (data && data.context_window) {
819
+ return { usedPct: Math.floor(data.context_window.used_percentage || 0) };
820
+ }
821
+ return null;
822
+ }
823
+
824
+ function getCostFromStdin() {
825
+ const data = getStdinData();
826
+ if (data && data.cost) {
827
+ const durationMs = data.cost.total_duration_ms || 0;
828
+ const mins = Math.floor(durationMs / 60000);
829
+ const secs = Math.floor((durationMs % 60000) / 1000);
830
+ return {
831
+ costUsd: data.cost.total_cost_usd || 0,
832
+ duration: mins > 0 ? mins + 'm' + secs + 's' : secs + 's',
833
+ };
834
+ }
835
+ return null;
836
+ }
837
+
838
+ // Compares dotted-numeric version strings (e.g. "3.27.1" vs "3.27.10").
839
+ // Returns >0 if a>b, <0 if a<b, 0 if equal-as-far-as-parseable. Deliberately
840
+ // simple (no prerelease/build-metadata handling) — this only orders local
841
+ // package.json versions against each other, never anything untrusted from
842
+ // a payload, so a full semver implementation would be dead weight here.
843
+ function compareVersions(a, b) {
844
+ const pa = String(a).split('.').map((n) => parseInt(n, 10));
845
+ const pb = String(b).split('.').map((n) => parseInt(n, 10));
846
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
847
+ const na = Number.isFinite(pa[i]) ? pa[i] : 0;
848
+ const nb = Number.isFinite(pb[i]) ? pb[i] : 0;
849
+ if (na !== nb) return na - nb;
850
+ }
851
+ return 0;
852
+ }
853
+
854
+ // #2742: when CWD is a linked git worktree, it has no node_modules of its
855
+ // own (worktrees don't get their own `npm install`), so every CWD-relative
856
+ // probe in getPkgVersion() misses and the version silently falls back to
857
+ // the baked-in default — even though the main repo's install a few
858
+ // directories away is perfectly resolvable. A linked worktree's `.git` is
859
+ // a plain FILE (not a directory) containing `gitdir: <main>/.git/worktrees/
860
+ // <name>`; walk up from CWD to find it, parse the pointer, and strip the
861
+ // trailing `.git/worktrees/<name>` segment to recover the main repo root.
862
+ // Pure fs — no `git rev-parse` spawn (statusline renders are latency-
863
+ // sensitive; this doc comment's neighbors are explicit about avoiding
864
+ // spawns in the render path).
865
+ function resolveWorktreeMainRoot() {
866
+ try {
867
+ let dir = CWD;
868
+ for (;;) {
869
+ const dotGit = path.join(dir, '.git');
870
+ if (fs.existsSync(dotGit)) {
871
+ if (fs.statSync(dotGit).isFile()) {
872
+ const contents = fs.readFileSync(dotGit, 'utf-8');
873
+ const m = contents.match(/^gitdir:\s*(.+)$/m);
874
+ const wtGitDir = m && m[1].trim();
875
+ if (wtGitDir) {
876
+ // Git writes this pointer with forward slashes even on Windows
877
+ // (a git-for-windows convention for its own internal files) —
878
+ // path.sep (backslash on win32) never matches, so normalize
879
+ // before searching rather than building an OS-specific marker.
880
+ const normalized = wtGitDir.replace(/\\/g, '/');
881
+ const marker = '/.git/worktrees/';
882
+ const idx = normalized.lastIndexOf(marker);
883
+ if (idx > 0) return normalized.slice(0, idx);
884
+ }
885
+ }
886
+ return null; // a real (non-worktree) .git dir — nothing to resolve
887
+ }
888
+ const parent = path.dirname(dir);
889
+ if (parent === dir) return null; // reached filesystem root
890
+ dir = parent;
891
+ }
892
+ } catch {
893
+ return null;
894
+ }
895
+ }
896
+
897
+ function getPkgVersion() {
898
+ // Baked in at generation time from the real running CLI's own resolved
899
+ // version (see generateStatuslineScript()'s doc comment) — correct even
900
+ // when this renders via a pure npx invocation with no local install for
901
+ // the candidate scan below to find.
902
+ let ver = "3.32.8";
903
+ try {
904
+ const home = os.homedir();
905
+ const pkgPaths = [
906
+ ...(BAKED_INSTALL_ROOT ? [path.join(BAKED_INSTALL_ROOT, 'package.json')] : []),
907
+ path.join(home, '.claude', 'plugins', 'marketplaces', 'ruflo', 'package.json'),
908
+ path.join(CWD, 'node_modules', '@claude-flow', 'cli', 'package.json'),
909
+ path.join(CWD, 'node_modules', 'ruflo', 'package.json'),
910
+ path.join(CWD, 'v3', '@claude-flow', 'cli', 'package.json'),
911
+ ];
912
+ // #2742: CWD is a linked git worktree with no node_modules of its own —
913
+ // probe the main repo's install too, so a worktree session shows the
914
+ // same version a main-repo session would.
915
+ const worktreeMainRoot = resolveWorktreeMainRoot();
916
+ if (worktreeMainRoot) {
917
+ pkgPaths.push(
918
+ path.join(worktreeMainRoot, 'node_modules', '@claude-flow', 'cli', 'package.json'),
919
+ path.join(worktreeMainRoot, 'node_modules', 'ruflo', 'package.json'),
920
+ path.join(worktreeMainRoot, 'v3', '@claude-flow', 'cli', 'package.json'),
921
+ );
922
+ }
923
+ // #2221: global installs (npm i -g ruflo) live outside CWD/node_modules, so the
924
+ // probes above all miss and the version falls back to the hard-coded default.
925
+ // Derive the global node_modules dir from the running node binary (no npm spawn —
926
+ // statusline renders often). Covers nvm/mise (bin/../lib/node_modules) and Windows
927
+ // (bin/node_modules) layouts.
928
+ try {
929
+ const binDir = path.dirname(process.execPath);
930
+ const globalModuleDirs = [path.join(binDir, '..', 'lib', 'node_modules'), path.join(binDir, 'node_modules')];
931
+ // #2221 follow-up: a custom npm prefix (e.g. ~/.npm-global) is decoupled from
932
+ // the node binary location, so the binDir-derived probes above all miss. Also
933
+ // probe the npm prefix from the environment and the common ~/.npm-global default.
934
+ for (const prefix of [
935
+ process.env.npm_config_prefix,
936
+ process.env.PREFIX,
937
+ path.join(home, '.local'),
938
+ path.join(home, '.npm-global'),
939
+ ]) {
940
+ if (prefix) globalModuleDirs.push(path.join(prefix, 'lib', 'node_modules'));
941
+ }
942
+ for (const gm of globalModuleDirs) {
943
+ pkgPaths.push(
944
+ path.join(gm, 'ruflo', 'package.json'),
945
+ path.join(gm, '@claude-flow', 'cli', 'package.json'),
946
+ );
947
+ }
948
+ } catch { /* ignore */ }
949
+ // Pick the HIGHEST version among every candidate that exists, not the
950
+ // first one found. The marketplace plugin path is probed first (list
951
+ // order above), but Claude Code's own plugin marketplace mechanism
952
+ // syncs on its own git-pull cadence, independent of npm publishes — a
953
+ // freshly-published npm version can sit alongside a stale marketplace
954
+ // checkout for a while (observed live: marketplace one release behind
955
+ // right after a publish). Taking the first EXISTING candidate meant the
956
+ // header could show a stale version even when a newer install (e.g.
957
+ // node_modules/@claude-flow/cli from a plain npm install) was sitting right there.
958
+ for (const p of pkgPaths) {
959
+ if (!fs.existsSync(p)) continue;
960
+ try {
961
+ const pkg = JSON.parse(fs.readFileSync(p, 'utf-8'));
962
+ if (pkg && typeof pkg.version === 'string' && pkg.version.length > 0) {
963
+ if (compareVersions(pkg.version, ver) > 0) ver = pkg.version;
964
+ }
965
+ } catch { /* ignore */ }
966
+ }
967
+ } catch { /* ignore */ }
968
+ return ver;
969
+ }
970
+
971
+ // ─── Rendering ──────────────────────────────────────────────────
972
+
973
+ function progressBar(current, total) {
974
+ const width = 5;
975
+ const filled = Math.round((current / total) * width);
976
+ return '[' + '●'.repeat(filled) + '○'.repeat(width - filled) + ']';
977
+ }
978
+
979
+ function generateStatusline() {
980
+ const d = getStatuslineData();
981
+ const git = getGitInfo();
982
+ const modelName = getModelFromStdin() || (d.user && d.user.modelName) || 'Claude Code';
983
+ const ctxInfo = getContextFromStdin();
984
+ const costInfo = getCostFromStdin();
985
+ // Named RUFLO_VERSION (not pkgVersion) so the #1951 regression guard
986
+ // (scripts/audit-fix-invariants.mjs) can pin its presence in the emitted
987
+ // .cjs artifact — without it the header silently reverts to a hard-coded
988
+ // "RuFlo V3.5" for anyone whose install doesn't match the first probe path.
989
+ const RUFLO_VERSION = getPkgVersion();
990
+
991
+ const progress = d.v3Progress || {};
992
+ const security = d.security || {};
993
+ const swarm = d.swarm || {};
994
+ const system = d.system || {};
995
+ const adrs = d.adrs || {};
996
+ const hooks = d.hooks || {};
997
+ const agentdb = d.agentdb || {};
998
+ const tests = d.tests || {};
999
+
1000
+ const domainsCompleted = progress.domainsCompleted || 0;
1001
+ const totalDomains = progress.totalDomains || 5;
1002
+ const dddProgress = progress.dddProgress || 0;
1003
+ const patternsLearned = progress.patternsLearned || 0;
1004
+ const activeAgents = swarm.activeAgents || 0;
1005
+ const maxAgents = swarm.maxAgents || CONFIG.maxAgents;
1006
+ const coordinationActive = swarm.coordinationActive || false;
1007
+ // null/undefined means "no source answered", which must not collapse to 0 --
1008
+ // that is exactly the ambiguity this segment used to present.
1009
+ const intelligencePct = (typeof system.intelligencePct === 'number')
1010
+ ? system.intelligencePct
1011
+ : null;
1012
+ const memoryMB = system.memoryMB || 0;
1013
+ const subAgents = system.subAgents || 0;
1014
+ const findings = Math.max(0, security.findings || 0);
1015
+ const secStatus = security.status || 'NONE';
1016
+ const adrCount = adrs.count || 0;
1017
+ const adrImpl = adrs.implemented || 0;
1018
+ const hooksEnabled = hooks.enabled || 0;
1019
+ const hooksTotal = hooks.total || 0;
1020
+ const vectorCount = agentdb.vectorCount || 0;
1021
+ const hasHnsw = agentdb.hasHnsw || false;
1022
+ const dbSizeKB = agentdb.dbSizeKB || 0;
1023
+ const testFiles = tests.testFiles || 0;
1024
+ const testCases = tests.testCases || testFiles * 4;
1025
+
1026
+ const lines = [];
1027
+
1028
+ // 3-line design (fits Claude Code's visible statusline area — line 4+ gets
1029
+ // replaced by the system guidance / input prompt line):
1030
+ // Line 1 — Header (RuFlo version · git · model · timing · context · cost)
1031
+ // Line 2 — Compressed ops (Swarm · Hooks · 🧠 · 💾 · Health)
1032
+ // Line 3 — Promo / disclosure row (funnel surface, ADR-301)
1033
+
1034
+ // ─── Line 1: header ────────────────────────────────────────────
1035
+ let header = c.bold + c.brightPurple + '▊ RuFlo V' + RUFLO_VERSION + ' ' + c.reset;
1036
+ header += (coordinationActive ? c.brightCyan : c.dim) + '● ' + c.brightCyan + git.name + c.reset;
1037
+ if (git.gitBranch) {
1038
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightBlue + '⏇ ' + git.gitBranch + c.reset;
1039
+ const changes = git.modified + git.staged + git.untracked;
1040
+ if (changes > 0) {
1041
+ let ind = '';
1042
+ if (git.staged > 0) ind += c.brightGreen + '+' + git.staged + c.reset;
1043
+ if (git.modified > 0) ind += c.brightYellow + '~' + git.modified + c.reset;
1044
+ if (git.untracked > 0) ind += c.dim + '?' + git.untracked + c.reset;
1045
+ header += ' ' + ind;
1046
+ }
1047
+ if (git.ahead > 0) header += ' ' + c.brightGreen + '↑' + git.ahead + c.reset;
1048
+ if (git.behind > 0) header += ' ' + c.brightRed + '↓' + git.behind + c.reset;
1049
+ }
1050
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.purple + modelName + c.reset;
1051
+ const duration = costInfo ? costInfo.duration : '';
1052
+ if (duration) header += ' ' + c.dim + '│' + c.reset + ' ' + c.cyan + '⏱ ' + duration + c.reset;
1053
+ if (ctxInfo && ctxInfo.usedPct > 0) {
1054
+ const ctxColor = ctxInfo.usedPct >= 90 ? c.brightRed : ctxInfo.usedPct >= 70 ? c.brightYellow : c.brightGreen;
1055
+ header += ' ' + c.dim + '│' + c.reset + ' ' + ctxColor + '● ' + ctxInfo.usedPct + '% ctx' + c.reset;
1056
+ }
1057
+ if (!CONFIG.hideCost && costInfo && costInfo.costUsd > 0) {
1058
+ header += ' ' + c.dim + '│' + c.reset + ' ' + c.brightYellow + CONFIG.costSymbol + costInfo.costUsd.toFixed(2) + c.reset;
1059
+ }
1060
+ lines.push(header);
1061
+
1062
+ // ─── Line 2: compressed ops ────────────────────────────────────
1063
+ // Everything actionable in one dense row. Show only what changes what you
1064
+ // do next; diagnostic detail moves to `ruflo status --verbose`.
1065
+ const agentsColor = activeAgents > 0 ? c.brightGreen : c.dim;
1066
+ const hooksColor = hooksEnabled > 0 ? c.brightGreen : c.dim;
1067
+ const intellColor = intelligencePct === null ? c.dim : intelligencePct >= 80 ? c.brightGreen : intelligencePct >= 40 ? c.brightYellow : c.dim;
1068
+ const swarmInd = coordinationActive ? c.brightGreen + '◉' + c.reset + ' ' : c.dim + '○' + c.reset + ' ';
1069
+ const healthAllGreen = (secStatus === 'CLEAN' || secStatus === 'NONE') && findings === 0;
1070
+ const opsParts = [];
1071
+ opsParts.push(c.cyan + 'Swarm ' + swarmInd + agentsColor + activeAgents + c.reset + '/' + c.brightWhite + maxAgents + c.reset);
1072
+ if (subAgents > 0) opsParts.push(c.brightPurple + '👥 ' + subAgents + c.reset);
1073
+ opsParts.push(c.cyan + 'Hooks ' + hooksColor + hooksEnabled + c.reset + '/' + c.brightWhite + hooksTotal + c.reset);
1074
+ opsParts.push(intellColor + '🧠 ' + (intelligencePct === null ? '—' : intelligencePct + '%') + c.reset);
1075
+ opsParts.push(c.brightCyan + '💾 ' + memoryMB + 'MB' + c.reset);
1076
+ // Health: one glyph when green, terse copy when there's something to act on.
1077
+ if (healthAllGreen) {
1078
+ opsParts.push(c.brightGreen + '🛡 ✓' + c.reset);
1079
+ } else {
1080
+ // #2776: STALE gets dim/gray (distinct from the actionable yellow of
1081
+ // PENDING/IN_PROGRESS) so a stale pill visibly stops shouting for
1082
+ // attention — the user can act on the "run ruflo security scan" prompt or
1083
+ // ignore it without a permanently-yellow indicator.
1084
+ if (secStatus === 'PENDING') opsParts.push(c.brightYellow + '🛡 scan pending' + c.reset);
1085
+ else if (secStatus === 'IN_PROGRESS') opsParts.push(c.brightYellow + '🛡 scanning…' + c.reset);
1086
+ else if (secStatus === 'ISSUES') opsParts.push(c.brightRed + '🛡 findings' + c.reset);
1087
+ else if (secStatus === 'STALE') opsParts.push(c.dim + '🛡 scan stale' + c.reset);
1088
+ else if (secStatus !== 'NONE' && secStatus !== 'CLEAN') opsParts.push(c.brightRed + '🛡 ' + secStatus.toLowerCase() + c.reset);
1089
+ if (findings > 0) {
1090
+ opsParts.push(c.brightRed + '⚠ ' + findings + ' finding' + (findings === 1 ? '' : 's') + c.reset);
1091
+ }
1092
+ }
1093
+ lines.push(opsParts.join(' ' + c.dim + '·' + c.reset + ' '));
1094
+
1095
+ // ─── Line 3: promo / disclosure / insight ───────────────────────
1096
+ // Colored by content kind so it reads as *what it is*, not as noise:
1097
+ // disclosure → brightCyan (announcement / capability link)
1098
+ // promotional → brightPurple (Cognitum sponsor spot)
1099
+ // educational → yellow (a tip)
1100
+ // insight → brightRed (environment/task-aware, local, actionable —
1101
+ // distinct from remote content on purpose)
1102
+ const promoRow = getPromoRow(d);
1103
+ if (promoRow) {
1104
+ const kind = (d && d.promo && d.promo.kind) || 'disclosure';
1105
+ const promoColor = kind === 'promotional' ? c.brightPurple
1106
+ : kind === 'educational' ? c.yellow
1107
+ : kind === 'insight' ? c.brightRed
1108
+ : c.brightCyan;
1109
+ lines.push(promoColor + promoRow + c.reset);
1110
+ }
1111
+
1112
+ // Trailing blank line so Claude Code's input prompt gets breathing room
1113
+ // instead of butting directly against the last statusline row.
1114
+ return lines.join('\n') + '\n';
1115
+ }
1116
+
1117
+ // ─── Funnel promo row (ADR-301) ─────────────────────────────────
1118
+ // Allowlist for OSC 8 hyperlink targets. Ships in code (not in payload) so
1119
+ // no message can smuggle a link to an unapproved host.
1120
+ //
1121
+ // The final destination hosts (cognitum.one / agentics.org) AND the
1122
+ // click-redirect host are both allowlisted here: promo.ts routes every
1123
+ // clickable message through the server-side click-redirect (ADR-311 §7)
1124
+ // so promo_open + geo are captured before the 302 to the real target —
1125
+ // so the OSC 8 link the renderer emits points at the redirect host, not
1126
+ // the final destination directly.
1127
+ const PROMO_LINK_HOSTS = new Set([
1128
+ 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
1129
+ // agentics.org — OSS foundation, distinct sponsor domain. Kept in sync
1130
+ // with messages.ts ALLOWED_URL_HOSTS.
1131
+ 'agentics.org', 'www.agentics.org',
1132
+ // Click-redirect host (funnel.ruv.io once its TLS cert is live; the raw
1133
+ // Cloud Run hostname is allowlisted too since event-transport.ts /
1134
+ // message-transport.ts / attribution.ts currently point at it as a TEMP
1135
+ // fallback while the domain mapping's cert provisions).
1136
+ 'funnel.ruv.io',
1137
+ 'cognitum-analytics-63rzcdswba-uc.a.run.app',
1138
+ ]);
1139
+
1140
+ // Emit OSC 8 hyperlinks unless the environment is known-broken. tmux mangles
1141
+ // raw OSC 8 (see anthropics/claude-code#27047) — opt in via env if wrapped.
1142
+ function terminalSupportsHyperlinks() {
1143
+ if (process.env.CI || process.env.GITHUB_ACTIONS) return false;
1144
+ if (process.env.TERM === 'dumb') return false;
1145
+ if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_STATUSLINE_HYPERLINKS || ''))) return false;
1146
+ if (process.env.TMUX && !process.env.RUFLO_STATUSLINE_HYPERLINKS_TMUX) return false;
1147
+ return true;
1148
+ }
1149
+
1150
+ // Wrap a label in an OSC 8 hyperlink escape sequence. Falls back to the raw
1151
+ // label whenever the URL is not an allowlisted https target, when the terminal
1152
+ // can't render hyperlinks, or when parsing fails — a broken link must never
1153
+ // leave a raw URL or stray escape in the statusline output.
1154
+ function safeTerminalLink(label, url) {
1155
+ if (!terminalSupportsHyperlinks()) return label;
1156
+ if (typeof url !== 'string' || url.length === 0) return label;
1157
+ let parsed;
1158
+ try { parsed = new URL(url); } catch { return label; }
1159
+ if (parsed.protocol !== 'https:') return label;
1160
+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return label;
1161
+ const cleanLabel = String(label).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');
1162
+ if (cleanLabel.length === 0) return label;
1163
+ const ESC = '\u001b';
1164
+ return ESC + ']8;;' + parsed.href + ESC + '\\' + cleanLabel + ESC + ']8;;' + ESC + '\\';
1165
+ }
1166
+
1167
+ function getPromoRow(d) {
1168
+ try {
1169
+ if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
1170
+ if (/^(0|false|off|no)$/i.test(String(process.env.RUFLO_FUNNEL || ''))) return null;
1171
+ const promo = d && d.promo;
1172
+ if (!promo || typeof promo.text !== 'string') return null;
1173
+ // Strip control chars / ANSI / bidi overrides — promo copy is data and
1174
+ // must never emit its own terminal sequences. Hard-cap length AFTER the
1175
+ // strip; append an ellipsis when the cap fires so the row visibly reads
1176
+ // as truncated instead of chopping a word mid-character (was: silent
1177
+ // slice(0,100) that could produce output that looked like corrupt data).
1178
+ const MAX_LEN = 100;
1179
+ const sanitized = promo.text
1180
+ .replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '')
1181
+ ;
1182
+ const text = (sanitized.length > MAX_LEN ? sanitized.slice(0, MAX_LEN - 1).trimEnd() + '…' : sanitized).trim();
1183
+ if (text.length === 0) return null;
1184
+ // Split the label from the trailing "· manage: ruflo settings" instruction
1185
+ // so each part gets styling that matches what it actually IS:
1186
+ // 1. label — OSC 8 hyperlink + underline. A real clickable link.
1187
+ // 2. "manage:" — dim. Just a connector word, no action implied.
1188
+ // 3. "ruflo settings" — bold/bright, NOT underlined. This is a shell
1189
+ // command the user TYPES, not a link they CLICK — a terminal can
1190
+ // never safely execute a command from a click (that would let any
1191
+ // server-served message run arbitrary commands), so we deliberately
1192
+ // avoid the underline/OSC8 cues that imply "clickable". Bold+bright
1193
+ // instead signals "this is the important bit — copy/type it".
1194
+ // Educational tips have no manage tail and no URL — plain text through.
1195
+ const manageIdx = text.indexOf(' · manage: ');
1196
+ const label = manageIdx > 0 ? text.slice(0, manageIdx) : text;
1197
+ const manageWord = manageIdx > 0 ? ' · manage: ' : '';
1198
+ const command = manageIdx > 0 ? text.slice(manageIdx + manageWord.length) : '';
1199
+ const UL_ON = '\u001b[4m';
1200
+ const UL_OFF = '\u001b[24m';
1201
+ const DIM_ON = '\u001b[2m';
1202
+ const DIM_OFF = '\u001b[22m';
1203
+ const BOLD_ON = '\u001b[1m';
1204
+ const BOLD_OFF = '\u001b[22m';
1205
+ const FG_BRIGHT_WHITE = '';
1206
+ // Reset FG to default so the caller's row-color code resumes coloring the
1207
+ // rest of the row after the command portion. Without this the row-color
1208
+ // escape wouldn't visibly re-apply because we already emitted an explicit FG.
1209
+ const FG_DEFAULT = '';
1210
+ // Some hosts (Claude Code's Windows UI, cmd.exe, older mintty) don't
1211
+ // render OSC 8 hyperlinks as clickable — the label just underlines and
1212
+ // clicks do nothing. Append a "(domain)" suffix so the destination is
1213
+ // visible/copyable everywhere. Wrap the suffix in OSC 8 too so terminals
1214
+ // that DO support hyperlinks give users TWO click targets (label AND
1215
+ // domain hint) instead of one — some Windows hosts render one but not
1216
+ // the other depending on how the statusline row is parsed.
1217
+ // Only for URLs (not educational tips), and only when the label doesn't
1218
+ // already end in the domain to avoid duplication.
1219
+ let visibleUrlHint = '';
1220
+ if (promo.url) {
1221
+ try {
1222
+ const host = new URL(promo.url).hostname.replace(/^www\./, '');
1223
+ // Strip the click-redirect wrapper so users see the FINAL destination,
1224
+ // not funnel.ruv.io. If the URL is /v1/click/<id>?to=<encoded>, pull the target.
1225
+ let displayHost = host;
1226
+ try {
1227
+ const to = new URL(promo.url).searchParams.get('to');
1228
+ if (to) displayHost = new URL(to).hostname.replace(/^www\./, '');
1229
+ } catch { /* not a click-redirect, keep the raw host */ }
1230
+ if (displayHost && !label.toLowerCase().endsWith(displayHost.toLowerCase())) {
1231
+ // safeTerminalLink returns the plain string if URL isn't allowlisted
1232
+ // or the terminal can't do OSC 8 — either way the domain stays visible.
1233
+ const clickableDomain = safeTerminalLink(displayHost, promo.url);
1234
+ visibleUrlHint = DIM_ON + ' (' + clickableDomain + ')' + DIM_OFF;
1235
+ }
1236
+ } catch { /* malformed URL — omit hint, never break the row */ }
1237
+ }
1238
+ // "Entire row clickable" (user request) — wrap the whole assembled
1239
+ // string in ONE OSC 8 hyperlink instead of just the label. The command
1240
+ // portion keeps its bold + bright-white treatment (no underline) so it
1241
+ // still VISUALLY reads as a shell command the user should type, not a
1242
+ // link — but if the user clicks anywhere on the row (label, domain
1243
+ // hint, connector, even the command text), the terminal opens the URL.
1244
+ // Clicking DOES NOT execute the command; it just opens the target URL,
1245
+ // which is safe. Terminals that ignore OSC 8 render the whole row as
1246
+ // styled text and no click behavior — the previous fallback (visible
1247
+ // domain suffix) still keeps the destination readable.
1248
+ const wrapWholeRowInHyperlink = (assembled) => {
1249
+ if (!promo.url) return assembled;
1250
+ if (!terminalSupportsHyperlinks()) return assembled;
1251
+ let parsed;
1252
+ try { parsed = new URL(promo.url); } catch { return assembled; }
1253
+ if (parsed.protocol !== 'https:') return assembled;
1254
+ if (!PROMO_LINK_HOSTS.has(parsed.hostname)) return assembled;
1255
+ const ESC = '';
1256
+ return ESC + ']8;;' + parsed.href + ESC + '\\' + assembled + ESC + ']8;;' + ESC + '\\';
1257
+ };
1258
+ // Visual styling stays per-part. We only add the OSC 8 wrap around the
1259
+ // combined string, so the whole row is one click target.
1260
+ const labelStyled = promo.url ? UL_ON + label + UL_OFF : label;
1261
+ if (!command) return wrapWholeRowInHyperlink(labelStyled + visibleUrlHint);
1262
+ return wrapWholeRowInHyperlink(
1263
+ labelStyled + visibleUrlHint
1264
+ + DIM_ON + manageWord + DIM_OFF
1265
+ + BOLD_ON + FG_BRIGHT_WHITE + command + FG_DEFAULT + BOLD_OFF
1266
+ );
1267
+ } catch (e) {
1268
+ return null; // the promo row must never break the statusline
1269
+ }
1270
+ }
1271
+
1272
+ // JSON output — delegates to CLI for accuracy; caller can use --json flag
1273
+ function generateJSON() {
1274
+ const d = getStatuslineData();
1275
+ const git = getGitInfo();
1276
+ return Object.assign({}, d, {
1277
+ user: Object.assign({ name: git.name, gitBranch: git.gitBranch }, d.user || {}),
1278
+ git: { modified: git.modified, untracked: git.untracked, staged: git.staged, ahead: git.ahead, behind: git.behind },
1279
+ lastUpdated: new Date().toISOString(),
1280
+ });
1281
+ }
1282
+
1283
+ // ─── Main ───────────────────────────────────────────────────────
1284
+ if (process.argv.includes('--json')) {
1285
+ console.log(JSON.stringify(generateJSON(), null, 2));
1286
+ } else if (process.argv.includes('--compact')) {
1287
+ console.log(JSON.stringify(generateJSON()));
1288
+ } else {
1289
+ console.log(generateStatusline());
1290
+ }