@boyingliu01/xp-gate 0.38.125 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (428) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +45 -1
  3. package/adapters/gate-7.sh +15 -6
  4. package/adapters/python.sh +36 -38
  5. package/bin/xp-gate.js +35 -0
  6. package/build-integrity/gate-10-lines.ts +98 -0
  7. package/build-integrity/gate-10.ts +131 -117
  8. package/build-integrity/quote-masker.ts +17 -3
  9. package/gate-3.sh +45 -1
  10. package/gate-registry.sh +3 -1
  11. package/gates/common-process.ts +116 -34
  12. package/gates/common.ts +51 -15
  13. package/gates/gate-3.ts +166 -61
  14. package/gates/gate-8.ts +76 -24
  15. package/gates/gate-9.ts +276 -82
  16. package/gates/pbt-detect.ts +70 -39
  17. package/gates/python-health.ts +236 -98
  18. package/gates/test-layers.ts +103 -30
  19. package/hooks/deploy-manifest.sh +1 -0
  20. package/hooks/gate-3.sh +45 -1
  21. package/hooks/gate-entries/gate-1-entry.sh +44 -24
  22. package/hooks/gate-entries/gate-5-entry.sh +60 -20
  23. package/hooks/gate-entries/gate-6-entry.sh +15 -6
  24. package/hooks/gate-registry.sh +3 -1
  25. package/hooks/lib/gate-status.sh +164 -0
  26. package/hooks/lib/jscpd-run.sh +9 -1
  27. package/hooks/lib/native-path.sh +54 -0
  28. package/hooks/lib/toolchain-path.sh +38 -0
  29. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  30. package/hooks/pre-commit +52 -0
  31. package/hooks/pre-push +67 -7
  32. package/lib/agent-runtime-journal.js +104 -37
  33. package/lib/arch.js +6 -0
  34. package/lib/baseline.js +329 -201
  35. package/lib/check.js +38 -2
  36. package/lib/deploy-manifest.js +1 -0
  37. package/lib/doctor-constants.js +43 -0
  38. package/lib/doctor-tool-checks.js +129 -0
  39. package/lib/doctor.js +2014 -1038
  40. package/lib/flaky.js +178 -79
  41. package/lib/gate-audit.ts +80 -0
  42. package/lib/gate-runner.js +115 -63
  43. package/lib/init.js +6 -0
  44. package/lib/language-capability-surfaces.js +75 -8
  45. package/lib/language-capability.js +3 -0
  46. package/lib/language-registry.js +608 -0
  47. package/lib/language-tools.js +679 -894
  48. package/lib/phase-transition.js +646 -446
  49. package/lib/prepush-evidence.js +174 -0
  50. package/lib/sprint-audit.js +52 -22
  51. package/lib/sprint-discovery.js +66 -35
  52. package/lib/sprint-format.js +114 -0
  53. package/lib/sprint-init.js +372 -118
  54. package/lib/sprint-status.js +134 -90
  55. package/lib/star-notice.js +346 -0
  56. package/lib/tool-audit.js +729 -0
  57. package/lib/tool-display.js +52 -0
  58. package/lib/tool-install.js +179 -0
  59. package/lib/uninstall.js +331 -188
  60. package/mock-policy/gate-m3.ts +74 -23
  61. package/mock-policy/mock-decision-engine.ts +21 -7
  62. package/mock-policy/scope-scanner.ts +128 -69
  63. package/mutation/detect-ai-test.ts +20 -12
  64. package/mutation/gate-m.ts +6 -2
  65. package/mutation/init-baseline.ts +49 -13
  66. package/mutation/runners/go-mutant-runner.ts +7 -49
  67. package/mutation/runners/gremlins-runner.ts +53 -18
  68. package/mutation/runners/mutmut-runner.ts +455 -163
  69. package/mutation/runners/pitest-runner.ts +85 -131
  70. package/mutation/runners/spawn-with-capture.ts +304 -0
  71. package/mutation/runners/stryker-runner.ts +14 -55
  72. package/mutation/update-baseline.ts +25 -18
  73. package/package.json +20 -8
  74. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  75. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  76. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/claude-code/skills/reinstall-xp-gate/.architecture-skip +8 -0
  79. package/plugins/claude-code/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  80. package/plugins/claude-code/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  81. package/plugins/claude-code/skills/reinstall-xp-gate/LICENSE +21 -0
  82. package/plugins/claude-code/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  83. package/plugins/claude-code/skills/reinstall-xp-gate/README.md +167 -0
  84. package/plugins/claude-code/skills/reinstall-xp-gate/SKILL.md +271 -0
  85. package/plugins/claude-code/skills/reinstall-xp-gate/TODO.md +253 -0
  86. package/plugins/claude-code/skills/reinstall-xp-gate/VERSION +1 -0
  87. package/plugins/claude-code/skills/reinstall-xp-gate/package.json +28 -0
  88. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  89. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  90. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  91. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  92. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  93. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  94. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  95. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  96. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  97. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  98. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  99. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  100. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  101. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  102. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  103. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  104. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  105. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  106. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  107. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  108. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  109. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  110. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  111. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  112. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  113. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  114. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  115. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  116. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  117. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  118. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  119. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  120. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  121. package/plugins/claude-code/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  122. package/plugins/claude-code/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  123. package/plugins/claude-code/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  124. package/plugins/claude-code/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  125. package/plugins/claude-code/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  126. package/plugins/claude-code/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  127. package/plugins/claude-code/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  128. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  129. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  130. package/plugins/claude-code/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  131. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  132. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  133. package/plugins/claude-code/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  134. package/plugins/claude-code/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  135. package/plugins/claude-code/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  136. package/plugins/claude-code/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  137. package/plugins/claude-code/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  138. package/plugins/claude-code/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  139. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  140. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  141. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  142. package/plugins/claude-code/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  143. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  144. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  145. package/plugins/dsh/package.json +1 -1
  146. package/plugins/dsh/scripts/prepack.cjs +43 -18
  147. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  148. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  149. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  150. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  151. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  152. package/plugins/dsh/src/skills.test.ts +9 -0
  153. package/plugins/opencode/index.ts +337 -123
  154. package/plugins/opencode/package.json +1 -1
  155. package/plugins/opencode/scripts/prepack.cjs +41 -16
  156. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  157. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  158. package/plugins/opencode/skills/reinstall-xp-gate/.architecture-skip +8 -0
  159. package/plugins/opencode/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  160. package/plugins/opencode/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  161. package/plugins/opencode/skills/reinstall-xp-gate/LICENSE +21 -0
  162. package/plugins/opencode/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  163. package/plugins/opencode/skills/reinstall-xp-gate/README.md +167 -0
  164. package/plugins/opencode/skills/reinstall-xp-gate/SKILL.md +271 -0
  165. package/plugins/opencode/skills/reinstall-xp-gate/TODO.md +253 -0
  166. package/plugins/opencode/skills/reinstall-xp-gate/VERSION +1 -0
  167. package/plugins/opencode/skills/reinstall-xp-gate/package.json +28 -0
  168. package/plugins/opencode/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  169. package/plugins/opencode/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  170. package/plugins/opencode/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  171. package/plugins/opencode/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  172. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  173. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  174. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  175. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  176. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  177. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  178. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  179. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  180. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  181. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  182. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  183. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  184. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  185. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  186. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  187. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  188. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  189. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  190. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  191. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  192. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  193. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  194. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  195. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  196. package/plugins/opencode/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  197. package/plugins/opencode/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  198. package/plugins/opencode/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  199. package/plugins/opencode/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  200. package/plugins/opencode/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  201. package/plugins/opencode/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  202. package/plugins/opencode/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  203. package/plugins/opencode/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  204. package/plugins/opencode/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  205. package/plugins/opencode/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  206. package/plugins/opencode/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  207. package/plugins/opencode/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  208. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  209. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  210. package/plugins/opencode/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  211. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  212. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  213. package/plugins/opencode/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  214. package/plugins/opencode/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  215. package/plugins/opencode/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  216. package/plugins/opencode/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  217. package/plugins/opencode/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  218. package/plugins/opencode/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  219. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  220. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  221. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  222. package/plugins/opencode/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  223. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  224. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  225. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  226. package/plugins/qoder/plugin.json +1 -1
  227. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  228. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  229. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  230. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  231. package/plugins/shared/README.md +3 -0
  232. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  233. package/principles/adapters/control-nesting.ts +481 -168
  234. package/principles/adapters/cpp.ts +61 -22
  235. package/principles/adapters/csharp.ts +183 -66
  236. package/principles/adapters/dart.ts +11 -1
  237. package/principles/adapters/duplication.ts +49 -16
  238. package/principles/adapters/import-clause.ts +62 -15
  239. package/principles/adapters/java.ts +199 -70
  240. package/principles/adapters/line-comment.ts +18 -0
  241. package/principles/adapters/member-scan.ts +50 -8
  242. package/principles/adapters/php.ts +232 -103
  243. package/principles/adapters/python.ts +25 -18
  244. package/principles/adapters/quote-state.ts +21 -8
  245. package/principles/adapters/typescript-mask.ts +276 -0
  246. package/principles/adapters/typescript.ts +206 -200
  247. package/principles/analyzer.ts +16 -6
  248. package/principles/baseline-prune.ts +18 -8
  249. package/principles/baseline.ts +28 -11
  250. package/principles/boy-scout-usage.ts +26 -0
  251. package/principles/boy-scout.ts +261 -180
  252. package/principles/config.ts +183 -57
  253. package/principles/direct-execution.ts +24 -12
  254. package/principles/lint-baseline.ts +235 -122
  255. package/principles/rules/arch/dependency.ts +34 -25
  256. package/principles/rules/arch/shared.ts +24 -20
  257. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  258. package/principles/rules/clean-code/god-class.ts +67 -41
  259. package/principles/rules/clean-code/large-file.ts +30 -23
  260. package/principles/rules/clean-code/long-function.ts +51 -37
  261. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  262. package/principles/rules/clean-code/many-exports.ts +46 -29
  263. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  264. package/principles/rules/clean-code/too-many-params.ts +41 -22
  265. package/principles/rules/function-source.ts +62 -0
  266. package/principles/rules/solid/dip.ts +10 -6
  267. package/principles/rules/solid/isp.ts +64 -24
  268. package/principles/rules/solid/lsp.ts +66 -18
  269. package/principles/rules/solid/ocp.ts +29 -13
  270. package/principles/rules/solid/srp.ts +34 -18
  271. package/principles/warnings-count.ts +43 -0
  272. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  273. package/scripts/delphi-config-read.cjs +245 -0
  274. package/scripts/delphi-external-review.cjs +410 -585
  275. package/scripts/delphi-json-extract.cjs +108 -0
  276. package/scripts/delphi-model-validation.cjs +297 -0
  277. package/scripts/delphi-prompts.cjs +55 -0
  278. package/scripts/delphi-repo-tools.cjs +273 -0
  279. package/scripts/delphi-seat-calibration.cjs +204 -0
  280. package/scripts/run-bats-ci.cjs +240 -97
  281. package/scripts/sync-package-content.js +18 -2
  282. package/skills/delphi-review/.delphi-config.json.example +6 -11
  283. package/skills/delphi-review/AGENTS.md +1 -1
  284. package/skills/sprint-flow/AGENTS.md +1 -1
  285. package/skills/test-specification-alignment/AGENTS.md +1 -1
  286. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  287. package/lib/__tests__/arch-config-template.test.js +0 -190
  288. package/lib/__tests__/arch.test.js +0 -424
  289. package/lib/__tests__/assertion-debt.test.js +0 -99
  290. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  291. package/lib/__tests__/audit-log.test.ts +0 -107
  292. package/lib/__tests__/baseline-completeness.test.js +0 -264
  293. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  294. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  295. package/lib/__tests__/baseline.test.js +0 -212
  296. package/lib/__tests__/bootstrap.test.js +0 -60
  297. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  298. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  299. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  300. package/lib/__tests__/check-changed-brief.test.js +0 -63
  301. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  302. package/lib/__tests__/check-single-file.test.js +0 -114
  303. package/lib/__tests__/check-version.test.js +0 -463
  304. package/lib/__tests__/coverage-scope.test.js +0 -140
  305. package/lib/__tests__/coverage-threshold.test.js +0 -80
  306. package/lib/__tests__/crap-cli.test.js +0 -87
  307. package/lib/__tests__/crap.test.js +0 -494
  308. package/lib/__tests__/debt-classify.test.js +0 -78
  309. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  310. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  311. package/lib/__tests__/delphi-channel.test.js +0 -109
  312. package/lib/__tests__/delphi-setup.test.js +0 -203
  313. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  314. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  315. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  316. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  317. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  318. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  319. package/lib/__tests__/deploy-manifest.test.js +0 -97
  320. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  321. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  322. package/lib/__tests__/detect-deps.test.js +0 -655
  323. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  324. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  325. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  326. package/lib/__tests__/doctor-brief.test.js +0 -59
  327. package/lib/__tests__/doctor-delphi.test.js +0 -628
  328. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  329. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  330. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  331. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  332. package/lib/__tests__/doctor-helpers.test.js +0 -139
  333. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  334. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  335. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  336. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  337. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  338. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  339. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  340. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  341. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  342. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  343. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  344. package/lib/__tests__/doctor.test.js +0 -1320
  345. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  346. package/lib/__tests__/flaky.test.js +0 -128
  347. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  348. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  349. package/lib/__tests__/gate-audit.test.ts +0 -440
  350. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  351. package/lib/__tests__/gate-coverage.test.js +0 -204
  352. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  353. package/lib/__tests__/gate-numbering.test.js +0 -79
  354. package/lib/__tests__/gate-rules.test.js +0 -58
  355. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  356. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  357. package/lib/__tests__/gate-runner.test.js +0 -371
  358. package/lib/__tests__/gate2-verdict.test.js +0 -183
  359. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  360. package/lib/__tests__/hook-health-path.test.js +0 -109
  361. package/lib/__tests__/hook-health.test.js +0 -85
  362. package/lib/__tests__/init-gitignore.test.js +0 -204
  363. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  364. package/lib/__tests__/init.test.js +0 -530
  365. package/lib/__tests__/install-cmd.test.js +0 -6
  366. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  367. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  368. package/lib/__tests__/install-skill.test.js +0 -416
  369. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  370. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  371. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  372. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  373. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  374. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  375. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  376. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  377. package/lib/__tests__/language-capability.test.js +0 -291
  378. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  379. package/lib/__tests__/language-tools-detect.test.js +0 -301
  380. package/lib/__tests__/migrate.test.js +0 -232
  381. package/lib/__tests__/mirror-manifest.test.js +0 -64
  382. package/lib/__tests__/mirror-sync.test.js +0 -803
  383. package/lib/__tests__/next-sprint.test.js +0 -231
  384. package/lib/__tests__/npm-package.test.js +0 -140
  385. package/lib/__tests__/phase-transition.test.js +0 -1136
  386. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  387. package/lib/__tests__/principles-directory.test.js +0 -87
  388. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  389. package/lib/__tests__/retro-gate-m.test.js +0 -144
  390. package/lib/__tests__/retro.test.js +0 -131
  391. package/lib/__tests__/rework.test.js +0 -127
  392. package/lib/__tests__/rollback.test.js +0 -183
  393. package/lib/__tests__/runtime-journal.test.js +0 -164
  394. package/lib/__tests__/sastd-client.test.js +0 -514
  395. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  396. package/lib/__tests__/shared-paths.test.js +0 -130
  397. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  398. package/lib/__tests__/shared-utils.test.js +0 -180
  399. package/lib/__tests__/skill-flags.test.js +0 -48
  400. package/lib/__tests__/slo.test.js +0 -89
  401. package/lib/__tests__/sprint-audit.test.js +0 -207
  402. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  403. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  404. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  405. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  406. package/lib/__tests__/sprint-status.test.js +0 -193
  407. package/lib/__tests__/sprint-status.test.ts +0 -213
  408. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  409. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  410. package/lib/__tests__/test-alignment.test.ts +0 -853
  411. package/lib/__tests__/tsconfig.json +0 -8
  412. package/lib/__tests__/tsx-resolution.test.js +0 -89
  413. package/lib/__tests__/ui-detector.test.ts +0 -459
  414. package/lib/__tests__/ui-review.test.ts +0 -132
  415. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  416. package/lib/__tests__/uninstall-skill.test.js +0 -189
  417. package/lib/__tests__/uninstall.test.js +0 -717
  418. package/lib/__tests__/update-hooks.test.js +0 -737
  419. package/lib/__tests__/update-skill-flags.test.js +0 -78
  420. package/lib/__tests__/update-skill.test.js +0 -644
  421. package/lib/__tests__/upgrade-exec.test.js +0 -273
  422. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  423. package/lib/__tests__/upgrade.test.js +0 -78
  424. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  425. package/lib/check-alignment-runner.cjs +0 -97
  426. package/lib/coverage-total.sh +0 -92
  427. package/lib/layer-baseline.cjs +0 -94
  428. package/lib/mattpocock-license-verdict.json +0 -7
@@ -10,6 +10,18 @@ const { execSync } = require('child_process');
10
10
  const fs = require('fs');
11
11
  const path = require('path');
12
12
  const os = require('os');
13
+ // The audit lives in its own module: check-tools and doctor both need the same
14
+ // completeness/validity/uniqueness rules, and a rule kept in two files drifts.
15
+ const {
16
+ collectGateTools,
17
+ auditAllTools,
18
+ summarizeAudit,
19
+ resolveLatestVersion,
20
+ resolveToolViaShell,
21
+ } = require('./tool-audit.js');
22
+ // Reuse doctor's own cross-language list so the two commands cannot disagree
23
+ // about what "the gate CLI tools" are.
24
+ const { GATE_CLI_TOOLS } = require('./detect-deps.js');
13
25
 
14
26
  /**
15
27
  * Tool definition for quality gate language tools.
@@ -33,592 +45,7 @@ const os = require('os');
33
45
  /**
34
46
  * Registry of all supported languages and their tools.
35
47
  */
36
- const LANGUAGE_REGISTRY = {
37
- typescript: {
38
- name: 'TypeScript/JavaScript',
39
- extensions: ['ts', 'tsx', 'js', 'jsx', 'mjs'],
40
- configFiles: ['package.json', 'tsconfig.json'],
41
- tools: [
42
- {
43
- name: 'eslint',
44
- checkCmd: 'eslint --version',
45
- install: {
46
- darwin: 'npm install -g eslint',
47
- linux: 'npm install -g eslint',
48
- win32: 'npm install -g eslint',
49
- },
50
- optional: false,
51
- gates: ['Gate 1 (Code Quality)'],
52
- },
53
- {
54
- name: '@archlinter/cli',
55
- checkCmd: 'npx --no-install archlint --version',
56
- install: {
57
- darwin: 'npm install --save-dev @archlinter/cli',
58
- linux: 'npm install --save-dev @archlinter/cli',
59
- win32: 'npm install --save-dev @archlinter/cli',
60
- },
61
- optional: true,
62
- gates: ['Gate 4 (Architecture)'],
63
- },
64
- {
65
- name: 'dependency-cruiser',
66
- checkCmd: 'npx --no-install depcruise --version',
67
- install: {
68
- darwin: 'npm install --save-dev dependency-cruiser',
69
- linux: 'npm install --save-dev dependency-cruiser',
70
- win32: 'npm install --save-dev dependency-cruiser',
71
- },
72
- optional: true,
73
- gates: ['Gate 4 (Architecture)'],
74
- },
75
- ],
76
- },
77
-
78
- python: {
79
- name: 'Python',
80
- extensions: ['py'],
81
- configFiles: ['pyproject.toml', 'setup.py', 'requirements.txt', 'Pipfile'],
82
- tools: [
83
- {
84
- name: 'mypy',
85
- checkCmd: 'mypy --version',
86
- install: {
87
- darwin: 'pip install mypy',
88
- linux: 'pip install mypy',
89
- win32: 'pip install mypy',
90
- },
91
- optional: false,
92
- gates: ['Gate 1 (Code Quality)'],
93
- },
94
- {
95
- name: 'ruff',
96
- checkCmd: 'ruff --version',
97
- install: {
98
- darwin: 'pip install ruff',
99
- linux: 'pip install ruff',
100
- win32: 'pip install ruff',
101
- },
102
- optional: true, // fallback to flake8
103
- gates: ['Gate 1 (Code Quality)'],
104
- },
105
- {
106
- name: 'flake8',
107
- checkCmd: 'flake8 --version',
108
- install: {
109
- darwin: 'pip install flake8',
110
- linux: 'pip install flake8',
111
- win32: 'pip install flake8',
112
- },
113
- optional: true, // fallback if no ruff
114
- gates: ['Gate 1 (Code Quality)'],
115
- },
116
- {
117
- name: 'pytest',
118
- checkCmd: 'pytest --version',
119
- install: {
120
- darwin: 'pip install pytest',
121
- linux: 'pip install pytest',
122
- win32: 'pip install pytest',
123
- },
124
- optional: false,
125
- gates: ['Gate 5 (Tests + Coverage)'],
126
- },
127
- {
128
- name: 'black',
129
- checkCmd: 'black --version',
130
- install: {
131
- darwin: 'pip install black',
132
- linux: 'pip install black',
133
- win32: 'pip install black',
134
- },
135
- optional: true,
136
- gates: ['Gate 1 (Code Formatting)'],
137
- },
138
- {
139
- name: 'import-linter',
140
- checkCmd: 'lint-imports --version',
141
- install: {
142
- darwin: 'pip install import-linter',
143
- linux: 'pip install import-linter',
144
- win32: 'pip install import-linter',
145
- },
146
- optional: true,
147
- gates: ['Gate 4 (Architecture)'],
148
- },
149
- ],
150
- },
151
-
152
- java: {
153
- name: 'Java',
154
- extensions: ['java'],
155
- configFiles: ['pom.xml', 'build.gradle', 'build.gradle.kts'],
156
- tools: [
157
- {
158
- name: 'mvn',
159
- checkCmd: 'mvn --version',
160
- install: {
161
- darwin: 'brew install maven',
162
- linux: 'apt-get install maven || yum install maven',
163
- win32: 'winget install Apache.Maven',
164
- },
165
- optional: true, // only if Maven project
166
- gates: ['Gate 1 (Build)'],
167
- },
168
- {
169
- name: 'gradle',
170
- checkCmd: 'gradle --version',
171
- install: {
172
- darwin: 'brew install gradle',
173
- linux: 'apt-get install gradle || yum install gradle',
174
- win32: 'winget install Gradle.Gradle',
175
- },
176
- optional: true, // only if Gradle project
177
- gates: ['Gate 1 (Build)'],
178
- },
179
- {
180
- name: 'checkstyle',
181
- checkCmd: 'checkstyle --version',
182
- install: {
183
- darwin: 'brew install checkstyle',
184
- linux: 'apt-get install checkstyle',
185
- win32: 'choco install checkstyle',
186
- },
187
- optional: true,
188
- gates: ['Gate 1 (Code Quality)'],
189
- },
190
- {
191
- name: 'pmd',
192
- checkCmd: 'pmd --version',
193
- install: {
194
- darwin: 'brew install pmd',
195
- linux: 'apt-get install pmd',
196
- win32: 'choco install pmd',
197
- },
198
- optional: true,
199
- gates: ['Gate 1 (Code Quality)'],
200
- },
201
- {
202
- // A BUILD dependency, not a CLI: there is no `archunit` binary to probe,
203
- // so checkCmd cannot work here. Detected by scanning the build files.
204
- name: 'archunit',
205
- detectBy: 'build-file',
206
- install: {
207
- darwin: 'add "com.tngtech.archunit:archunit-junit5" to pom.xml / build.gradle',
208
- linux: 'add "com.tngtech.archunit:archunit-junit5" to pom.xml / build.gradle',
209
- win32: 'add "com.tngtech.archunit:archunit-junit5" to pom.xml / build.gradle',
210
- },
211
- optional: true,
212
- gates: ['Gate 4 (Architecture)'],
213
- },
214
- ],
215
- },
216
-
217
- go: {
218
- name: 'Go',
219
- extensions: ['go'],
220
- configFiles: ['go.mod', 'go.sum'],
221
- tools: [
222
- {
223
- name: 'go',
224
- checkCmd: 'go version',
225
- install: {
226
- darwin: 'brew install go',
227
- linux: 'apt-get install golang || yum install golang',
228
- win32: 'winget install GoLang.Go',
229
- },
230
- optional: false,
231
- gates: ['Gate 1 (Build + Quality)'],
232
- },
233
- {
234
- name: 'golangci-lint',
235
- checkCmd: 'golangci-lint --version',
236
- install: {
237
- darwin: 'brew install golangci-lint',
238
- linux: 'go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest',
239
- win32: 'go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest',
240
- },
241
- optional: true,
242
- gates: ['Gate 1 (Code Quality)'],
243
- },
244
- {
245
- name: 'arch-go',
246
- checkCmd: 'arch-go --version',
247
- install: {
248
- darwin: 'go install github.com/fdaines/arch-go@latest',
249
- linux: 'go install github.com/fdaines/arch-go@latest',
250
- win32: 'go install github.com/fdaines/arch-go@latest',
251
- },
252
- optional: true,
253
- gates: ['Gate 4 (Architecture)'],
254
- },
255
- ],
256
- },
257
-
258
- kotlin: {
259
- name: 'Kotlin',
260
- extensions: ['kt', 'kts'],
261
- configFiles: ['build.gradle', 'build.gradle.kts', 'pom.xml'],
262
- tools: [
263
- {
264
- name: 'gradle',
265
- checkCmd: 'gradle --version',
266
- install: {
267
- darwin: 'brew install gradle',
268
- linux: 'apt-get install gradle',
269
- win32: 'winget install Gradle.Gradle',
270
- },
271
- optional: true,
272
- gates: ['Gate 1 (Build)'],
273
- },
274
- {
275
- name: 'ktlint',
276
- checkCmd: 'ktlint --version',
277
- install: {
278
- darwin: 'brew install ktlint',
279
- linux: 'curl -sSLO https://github.com/pinterest/ktlint/releases/latest/download/ktlint && chmod +x ktlint',
280
- win32: 'choco install ktlint',
281
- },
282
- optional: true,
283
- gates: ['Gate 1 (Code Quality)'],
284
- },
285
- {
286
- // Konsist is a build dependency too -- see the Java ArchUnit note above.
287
- name: 'konsist',
288
- detectBy: 'build-file',
289
- install: {
290
- darwin: 'add "com.lemonappdev:konsist" to build.gradle(.kts)',
291
- linux: 'add "com.lemonappdev:konsist" to build.gradle(.kts)',
292
- win32: 'add "com.lemonappdev:konsist" to build.gradle(.kts)',
293
- },
294
- optional: true,
295
- gates: ['Gate 4 (Architecture)'],
296
- },
297
- ],
298
- },
299
-
300
- // #730: C# was supported by every gate (adapter, principles engine, Gate 4/5/6/10/13
301
- // arms) but absent here, so `detect-languages` produced a config WITHOUT csharp.
302
- // A hook that reads the generated config trusts it and does not fall back to
303
- // extension sniffing, so C# was never routed — the whole feature was invisible in
304
- // exactly the mixed .NET+JS repos it targets (the dsh-aot-runner shape: .csproj plus
305
- // ~900 lines of JS). Registry membership is what makes detection emit the entry.
306
- csharp: {
307
- name: 'C#/.NET',
308
- extensions: ['cs', 'csx'],
309
- // `.csproj`/`.sln` are SUFFIXES of project-specific filenames (Foo.csproj), so
310
- // they must be written as globs — the matcher only globs entries containing '*'
311
- // and otherwise stats the exact name, which would never find DshAotRunner.csproj.
312
- // Directory.Build.props carries repo-wide MSBuild settings; global.json pins the
313
- // SDK, so a repo with only that plus sources still deserves the C# arm.
314
- configFiles: ['*.csproj', '*.sln', '*.csproj.user', 'Directory.Build.props', 'global.json'],
315
- tools: [
316
- {
317
- // The adapter drives everything through the SDK: `dotnet format` for Gate 1,
318
- // `dotnet build -warnaserror` for Gate 13, `dotnet test` for Gate 5.
319
- name: 'dotnet',
320
- checkCmd: 'dotnet --version',
321
- install: {
322
- darwin: 'brew install --cask dotnet-sdk',
323
- linux: 'See https://learn.microsoft.com/dotnet/core/install/linux',
324
- win32: 'winget install Microsoft.DotNet.SDK.8',
325
- },
326
- optional: false,
327
- gates: ['Gate 1 (Code Quality)', 'Gate 5 (Tests + Coverage)', 'Gate 13 (Compiler Strictness)'],
328
- },
329
- // No second C# entry for coverage. `dotnet test --collect` supplies it, and
330
- // the only project-provided detector this module implements is
331
- // `detectBy: 'build-file'`, which reads ARCH_DEPENDENCY_COORDINATES — a table
332
- // with no C# entry. Listing coverlet under a detectBy value nothing consumes
333
- // would make check-tools probe a tool with no checkCmd and report a
334
- // permanently-missing entry for a dependency that is already satisfied.
335
- ],
336
- },
337
-
338
- swift: {
339
- name: 'Swift',
340
- extensions: ['swift'],
341
- configFiles: ['Package.swift', 'project.xcodeproj', 'project.pbxproj'],
342
- tools: [
343
- {
344
- name: 'swift',
345
- checkCmd: 'swift --version',
346
- install: {
347
- darwin: 'xcode-select --install',
348
- linux: 'See https://swift.org/download/',
349
- win32: 'See https://swift.org/download/',
350
- },
351
- optional: false,
352
- gates: ['Gate 1 (Build + Quality)'],
353
- },
354
- {
355
- name: 'swiftlint',
356
- checkCmd: 'swiftlint --version',
357
- install: {
358
- darwin: 'brew install swiftlint',
359
- linux: 'See https://github.com/realm/SwiftLint',
360
- win32: 'See https://github.com/realm/SwiftLint',
361
- },
362
- optional: true,
363
- gates: ['Gate 1 (Code Quality)'],
364
- },
365
- ],
366
- },
367
-
368
- // #846: Objective-C had a full runtime (githooks/adapters/objectivec.sh) and
369
- // was recognised by every GATE-layer list -- Gate 1's short-circuit, Gate 3's
370
- // lizard population, Gate 4's PRINCIPLES_FILES, Gate 5's CODE_EXTENSIONS,
371
- // Gate 10's SEMGREP_FILES, lib/docs-only.sh -- yet was absent HERE. That is
372
- // #730's shape exactly: `detect-languages` writes a config without it, the
373
- // hook trusts that config and does NOT fall back to extension sniffing, so an
374
- // Objective-C repo was never routed. Registry membership, not gate support, is
375
- // what makes a language reachable.
376
- //
377
- // Detection keys off Xcode manifests and NOT off the `.m`/`.mm` extension.
378
- // `.m` is also MATLAB's, and `configFiles` is non-empty here on purpose:
379
- // detectProjectLanguages only consults the extension fallback when
380
- // `configFiles.length === 0`, so listing a manifest both enables detection and
381
- // structurally prevents a MATLAB checkout from being reported as Objective-C.
382
- // `*.pbxproj` is globbed because the project file lives inside
383
- // `<name>.xcodeproj/`, not at the repo root.
384
- objectivec: {
385
- name: 'Objective-C',
386
- extensions: ['m', 'mm'],
387
- configFiles: ['Podfile', 'Package.swift', '*.xcodeproj', '*.pbxproj'],
388
- tools: [
389
- {
390
- name: 'clang',
391
- checkCmd: 'clang --version',
392
- install: {
393
- darwin: 'xcode-select --install',
394
- linux: 'apt install clang',
395
- win32: 'See https://clang.llvm.org/get_started.html',
396
- },
397
- optional: false,
398
- gates: ['Gate 1 (Build + Quality)'],
399
- },
400
- ],
401
- },
402
-
403
- // #731: PHP. `configFiles` is non-empty on purpose, for the same structural
404
- // reason as objectivec below -- detectProjectLanguages only consults the
405
- // extension fallback when `configFiles.length === 0`, so a manifest keeps the
406
- // signal anchored to a real project rather than to a stray .php file.
407
- // composer.json is listed first but is NOT treated as exclusive: unlike a
408
- // .csproj, it coexists happily with package.json in JS repos that shell out for
409
- // one build step. The Gate 0 detection arm keys off `.php` extensions instead.
410
- php: {
411
- name: 'PHP',
412
- extensions: ['php', 'phtml'],
413
- configFiles: ['composer.json', 'phpunit.xml', 'phpunit.xml.dist', 'phpstan.neon'],
414
- tools: [
415
- {
416
- name: 'php',
417
- checkCmd: 'php --version',
418
- install: {
419
- darwin: 'brew install php',
420
- linux: 'sudo apt install php-cli composer',
421
- win32: 'scoop install php composer',
422
- },
423
- optional: false,
424
- gates: ['Gate 1 (Build + Quality)', 'Gate 5 (Coverage)'],
425
- },
426
- {
427
- name: 'composer',
428
- checkCmd: 'composer --version',
429
- install: {
430
- darwin: 'brew install composer',
431
- linux: 'See https://getcomposer.org/download/',
432
- win32: 'scoop install composer',
433
- },
434
- optional: false,
435
- gates: ['Gate 1 (Build + Quality)'],
436
- },
437
- {
438
- name: 'phpstan',
439
- checkCmd: 'php vendor/bin/phpstan --version',
440
- install: {
441
- darwin: 'composer require --dev phpstan/phpstan',
442
- linux: 'composer require --dev phpstan/phpstan',
443
- win32: 'composer require --dev phpstan/phpstan',
444
- },
445
- optional: false,
446
- gates: ['Gate 1 (Build + Quality)'],
447
- },
448
- {
449
- name: 'phpcs',
450
- checkCmd: 'php vendor/bin/phpcs --version',
451
- install: {
452
- darwin: 'composer require --dev squizlabs/php_codesniffer',
453
- linux: 'composer require --dev squizlabs/php_codesniffer',
454
- win32: 'composer require --dev squizlabs/php_codesniffer',
455
- },
456
- optional: false,
457
- gates: ['Gate 1 (Build + Quality)'],
458
- },
459
- {
460
- name: 'pcov',
461
- checkCmd: 'php -r "exit(extension_loaded(\'pcov\')?0:1);"',
462
- install: {
463
- darwin: 'pecl install pcov',
464
- linux: 'pecl install pcov',
465
- win32: 'php_pcov.dll from https://windows.php.net/downloads/pecl/releases/pcov/ (must match the PHP build: ts vs nts)',
466
- },
467
- // Coverage is Gate 5's business; a missing driver makes coverage
468
- // unmeasurable, which the adapter reports as BLOCK rather than 0%.
469
- optional: true,
470
- gates: ['Gate 5 (Coverage)'],
471
- },
472
- ],
473
- },
474
-
475
- dart: {
476
- name: 'Dart',
477
- extensions: ['dart'],
478
- configFiles: ['pubspec.yaml'],
479
- tools: [
480
- {
481
- name: 'dart',
482
- checkCmd: 'dart --version',
483
- install: {
484
- darwin: 'brew tap dart-lang/dart && brew install dart',
485
- linux: 'See https://dart.dev/get-dart',
486
- win32: 'winget install Dart-Dart.dart',
487
- },
488
- optional: false,
489
- gates: ['Gate 1 (Build + Quality)'],
490
- },
491
- ],
492
- },
493
-
494
- flutter: {
495
- name: 'Flutter',
496
- extensions: ['dart'],
497
- configFiles: ['pubspec.yaml'],
498
- tools: [
499
- {
500
- name: 'flutter',
501
- checkCmd: 'flutter --version',
502
- install: {
503
- darwin: 'brew install --cask flutter',
504
- linux: 'See https://flutter.dev/docs/get-started/install',
505
- win32: 'winget install Flutter.Flutter',
506
- },
507
- optional: false,
508
- gates: ['Gate 1 (Build + Quality)'],
509
- },
510
- ],
511
- },
512
-
513
- cpp: {
514
- name: 'C/C++',
515
- extensions: ['cpp', 'cxx', 'cc', 'c', 'hpp', 'h'],
516
- configFiles: ['CMakeLists.txt', 'Makefile', 'conanfile.txt', 'vcpkg.json'],
517
- tools: [
518
- {
519
- name: 'cmake',
520
- checkCmd: 'cmake --version',
521
- install: {
522
- darwin: 'brew install cmake',
523
- linux: 'apt-get install cmake || yum install cmake',
524
- win32: 'winget install Kitware.CMake',
525
- },
526
- optional: true,
527
- gates: ['Gate 1 (Build)'],
528
- },
529
- {
530
- name: 'clang-tidy',
531
- checkCmd: 'clang-tidy --version',
532
- install: {
533
- darwin: 'brew install llvm',
534
- linux: 'apt-get install clang-tidy',
535
- win32: 'See LLVM installer',
536
- },
537
- optional: true,
538
- gates: ['Gate 1 (Code Quality)'],
539
- },
540
- ],
541
- },
542
-
543
- shell: {
544
- name: 'Shell',
545
- extensions: ['sh', 'bash'],
546
- configFiles: [],
547
- tools: [
548
- {
549
- name: 'shellcheck',
550
- checkCmd: 'shellcheck --version',
551
- install: {
552
- darwin: 'brew install shellcheck',
553
- linux: 'apt-get install shellcheck || yum install shellcheck',
554
- win32: 'winget install ShellCheck.ShellCheck',
555
- },
556
- optional: true,
557
- gates: ['Gate 1 (Code Quality)'],
558
- },
559
- ],
560
- },
561
-
562
- powershell: {
563
- name: 'PowerShell',
564
- extensions: ['ps1', 'psm1', 'psd1'],
565
- configFiles: [],
566
- tools: [
567
- {
568
- name: 'pwsh',
569
- checkCmd: 'pwsh --version',
570
- install: {
571
- darwin: 'brew install --cask powershell',
572
- linux: 'apt-get install powershell || yum install powershell',
573
- win32: 'winget install Microsoft.PowerShell',
574
- },
575
- optional: false,
576
- gates: ['Gate 1 (Build + Quality)'],
577
- },
578
- {
579
- name: 'psscriptanalyzer',
580
- checkCmd: 'pwsh -Command "Get-Module -List PSScriptAnalyzer"',
581
- install: {
582
- darwin: 'pwsh -Command "Install-Module -Name PSScriptAnalyzer -Force"',
583
- linux: 'pwsh -Command "Install-Module -Name PSScriptAnalyzer -Force"',
584
- win32: 'pwsh -Command "Install-Module -Name PSScriptAnalyzer -Force"',
585
- },
586
- optional: true,
587
- gates: ['Gate 1 (Code Quality)'],
588
- },
589
- ],
590
- },
591
-
592
- iac: {
593
- name: 'Infrastructure as Code',
594
- extensions: ['tf', 'tfvars', 'yaml', 'yml'],
595
- configFiles: ['*.tf', 'docker-compose*.yaml', 'k8s/*.yaml'],
596
- tools: [
597
- {
598
- name: 'terraform',
599
- checkCmd: 'terraform --version',
600
- install: {
601
- darwin: 'brew install terraform',
602
- linux: 'See https://developer.hashicorp.com/terraform/downloads',
603
- win32: 'winget install Hashicorp.Terraform',
604
- },
605
- optional: true,
606
- gates: ['Gate 7 (IaC Security)'],
607
- },
608
- {
609
- name: 'tflint',
610
- checkCmd: 'tflint --version',
611
- install: {
612
- darwin: 'brew install tflint',
613
- linux: 'See https://github.com/terraform-linters/tflint',
614
- win32: 'See https://github.com/terraform-linters/tflint',
615
- },
616
- optional: true,
617
- gates: ['Gate 7 (IaC Security)'],
618
- },
619
- ],
620
- },
621
- };
48
+ const { LANGUAGE_REGISTRY } = require('./language-registry.js');
622
49
 
623
50
  /**
624
51
  * Directories that must never drive language detection: dependency trees ship
@@ -691,213 +118,135 @@ function parseLanguageFlag(args) {
691
118
  * @param {string} projectRoot - Project root directory
692
119
  * @returns {{detected: string[], configFiles: Object.<string, string[]>}}
693
120
  */
694
- function detectProjectLanguages(projectRoot) {
695
- const detected = new Set();
696
- const configFiles = {};
697
-
698
- // Scanned lazily: the extension fallback is only consulted for languages that
699
- // have no config file to look for, and the scan is bounded, not a full walk.
700
- let scannedExtensions = null;
701
- const extensionSeen = (ext) => {
702
- if (scannedExtensions === null) scannedExtensions = extensionsPresentIn(projectRoot);
703
- return scannedExtensions.has(ext);
704
- };
705
-
706
- for (const [lang, def] of Object.entries(LANGUAGE_REGISTRY)) {
707
- const foundConfigs = [];
708
-
709
- for (const configFile of def.configFiles) {
710
- // Handle glob patterns
711
- if (configFile.includes('*')) {
712
- // Simple glob matching
713
- const pattern = configFile.replace(/\*/g, '.*');
714
- const regex = new RegExp(pattern);
715
- try {
716
- const files = fs.readdirSync(projectRoot);
717
- for (const file of files) {
718
- if (regex.test(file)) {
719
- foundConfigs.push(file);
720
- }
721
- }
722
- } catch { /* ignore */ }
723
- } else {
724
- const configPath = path.join(projectRoot, configFile);
725
- if (fs.existsSync(configPath)) {
726
- foundConfigs.push(configFile);
727
- }
728
- }
729
- }
730
-
731
- if (foundConfigs.length > 0) {
732
- detected.add(lang);
733
- configFiles[lang] = foundConfigs;
734
- } else if (def.configFiles.length === 0 && def.extensions.some(extensionSeen)) {
735
- // Shell and PowerShell have no package-manager manifest to key off, so file
736
- // extensions are their only possible signal (#468). Languages that do have
737
- // config files keep using them: their extension lists are broad (IaC lists
738
- // yaml/yml), and matching on those would make every repo with a CI YAML an
739
- // Infrastructure-as-Code project.
740
- detected.add(lang);
741
- }
742
- }
743
-
744
- // Special case: Flutter vs Dart
745
- if (detected.has('flutter') && detected.has('dart')) {
746
- detected.delete('dart'); // Flutter implies Dart
747
- }
121
+ /**
122
+ * Decide between Flutter and Dart, which are not independent answers.
123
+ *
124
+ * Flutter IMPLIES Dart: reporting both makes a Flutter app look like a Dart project
125
+ * that happens to use Flutter. A `pubspec.yaml` mentioning flutter is the
126
+ * authoritative signal, so it overrides the extension-based guess rather than
127
+ * adding to it.
128
+ *
129
+ * @param {Set<string>} detected mutated in place
130
+ * @param {string} projectRoot
131
+ */
132
+ function resolveFlutterVersusDart(detected, projectRoot) {
133
+ if (detected.has('flutter') && detected.has('dart')) detected.delete('dart');
748
134
 
749
- // Check for Flutter specifically
750
135
  const pubspecPath = path.join(projectRoot, 'pubspec.yaml');
751
- if (fs.existsSync(pubspecPath)) {
752
- try {
753
- const content = fs.readFileSync(pubspecPath, 'utf8');
754
- if (content.includes('flutter:')) {
755
- detected.delete('dart');
756
- detected.add('flutter');
757
- }
758
- } catch { /* ignore */ }
136
+ if (!fs.existsSync(pubspecPath)) return;
137
+ try {
138
+ if (fs.readFileSync(pubspecPath, 'utf8').includes('flutter:')) {
139
+ detected.delete('dart');
140
+ detected.add('flutter');
141
+ }
142
+ } catch {
143
+ // An unreadable pubspec leaves the extension-based detection as it stands.
759
144
  }
760
-
761
- return {
762
- detected: Array.from(detected),
763
- configFiles,
764
- };
765
145
  }
766
146
 
767
147
  /**
768
- * Check if a CLI tool is available.
769
- * @param {string} toolName - Tool name
770
- * @param {string} checkCmd - Command to check version
771
- * @returns {{available: boolean, version?: string}}
148
+ * A predicate over the file extensions present in a project, scanned on first use.
149
+ *
150
+ * Lazy on purpose: the extension fallback is only consulted for languages that have
151
+ * no config file to look for, and the scan is bounded rather than a full walk. On a
152
+ * config-heavy project it never runs at all; on an extension-only one it runs once,
153
+ * not once per language.
154
+ *
155
+ * @param {string} projectRoot
156
+ * @returns {(ext: string) => boolean}
772
157
  */
773
- function checkTool(toolName, checkCmd) {
774
- const isWindows = process.platform === 'win32';
775
- const shell = isWindows ? 'cmd.exe' : '/bin/sh';
776
- const nullRedir = isWindows ? '2>nul' : '2>/dev/null';
777
- const execOpts = {
778
- encoding: 'utf8',
779
- stdio: ['ignore', 'pipe', 'pipe'],
780
- shell,
781
- timeout: 10000
158
+ function makeLazyExtensionScanner(projectRoot) {
159
+ let scanned = null;
160
+ return (ext) => {
161
+ if (scanned === null) scanned = extensionsPresentIn(projectRoot);
162
+ return scanned.has(ext);
782
163
  };
164
+ }
783
165
 
166
+ /**
167
+ * Walk the registry and record every language the project shows evidence of.
168
+ *
169
+ * A language is detected by a config file OR, when it has none to look for, by its
170
+ * extension. Config files take precedence because extension lists are broad -- IaC
171
+ * lists yaml/yml, and matching on those would make every repo with a CI YAML an
172
+ * Infrastructure-as-Code project (#468).
173
+ */
174
+ /**
175
+ * The config files this entry matches: the literal name, or every file a `*` glob hits.
176
+ *
177
+ * A glob's directory listing is read once per pattern, and an unreadable project root
178
+ * yields no matches rather than throwing -- detection is a report about what was
179
+ * SEEN, and a directory we cannot list was not seen.
180
+ *
181
+ * @param {string} projectRoot
182
+ * @param {string} configFile a literal name or a pattern containing `*`
183
+ * @returns {string[]} matched names, relative to the project root
184
+ */
185
+ function matchConfigFile(projectRoot, configFile) {
186
+ if (!configFile.includes('*')) {
187
+ return fs.existsSync(path.join(projectRoot, configFile)) ? [configFile] : [];
188
+ }
189
+ const regex = new RegExp(configFile.replace(/\*/g, '.*'));
784
190
  try {
785
- const result = execSync(`${checkCmd} ${nullRedir}`, execOpts);
786
- return { available: true, version: result.trim().split('\n')[0] };
191
+ return fs.readdirSync(projectRoot).filter((file) => regex.test(file));
787
192
  } catch {
788
- return { available: false };
193
+ return [];
789
194
  }
790
195
  }
791
196
 
792
- /**
793
- * Get required tools for detected languages.
794
- * @param {string[]} languages - Detected languages
795
- * @returns {Object.<string, Array<{tool: ToolDef, status: string}>>}
796
- */
797
- function getToolsForLanguages(languages) {
798
- const result = {};
799
-
800
- for (const lang of languages) {
801
- const langDef = LANGUAGE_REGISTRY[lang];
802
- if (!langDef) continue;
803
-
804
- result[lang] = [];
805
-
806
- for (const tool of langDef.tools) {
807
- // Build-file tools have no binary to probe; running checkCmd on them
808
- // would report "missing" permanently (#689 AC-3).
809
- const status = tool.detectBy === 'build-file'
810
- ? detectBuildFileDependency(lang)
811
- : checkTool(tool.name, tool.checkCmd);
812
- result[lang].push({
813
- tool,
814
- status: status.available ? 'available' : 'missing',
815
- version: status.version,
816
- });
817
- }
197
+ function scanRegistryForLanguages(projectRoot, detected, configFiles, extensionSeen) {
198
+ for (const [lang, def] of Object.entries(LANGUAGE_REGISTRY)) {
199
+ const foundConfigs = [];
200
+
201
+ for (const configFile of def.configFiles) {
202
+ foundConfigs.push(...matchConfigFile(projectRoot, configFile));
818
203
  }
819
204
 
820
- return result;
205
+ if (foundConfigs.length > 0) {
206
+ detected.add(lang);
207
+ configFiles[lang] = foundConfigs;
208
+ } else if (def.configFiles.length === 0 && def.extensions.some(extensionSeen)) {
209
+ // Shell and PowerShell have no package-manager manifest to key off, so file
210
+ // extensions are their only possible signal (#468). Languages that do have
211
+ // config files keep using them: their extension lists are broad (IaC lists
212
+ // yaml/yml), and matching on those would make every repo with a CI YAML an
213
+ // Infrastructure-as-Code project.
214
+ detected.add(lang);
215
+ }
216
+ }
821
217
  }
822
218
 
823
- /**
824
- * Install a tool using the appropriate command for the current platform.
825
- * @param {ToolDef} toolDef - Tool definition
826
- * @returns {{success: boolean, message: string}}
827
- */
828
- function installTool(toolDef) {
829
- // A build-file tool has no installer to run: `detectBy: 'build-file'` exists
830
- // because ArchUnit and Konsist are libraries with no CLI to probe, and their
831
- // `install` field holds an instruction written for a human. Handing that
832
- // prose to execSync made `doctor --fix --install-tools` print
833
- // `'add' is not recognized as an internal or external command` on every Java
834
- // machine, and on POSIX actually shell it. Report the guidance and start no
835
- // process (#689 review, found by Delphi Round 1).
836
- if (toolDef.detectBy === 'build-file') {
837
- const guidance = toolDef.install[process.platform] || toolDef.install.linux || '';
838
- return {
839
- success: false,
840
- message:
841
- `${toolDef.name} is a build-file library, not a CLI: no install command is runnable. ` +
842
- `Add it manually -- ${guidance}`,
843
- };
844
- }
219
+ function detectProjectLanguages(projectRoot) {
220
+ const detected = new Set();
221
+ const configFiles = {};
845
222
 
846
- const platform = process.platform;
847
- const installCmd = toolDef.install[platform] || toolDef.install.linux;
223
+ const extensionSeen = makeLazyExtensionScanner(projectRoot);
848
224
 
849
- if (!installCmd) {
850
- return { success: false, message: `No install command for platform ${platform}` };
851
- }
225
+ scanRegistryForLanguages(projectRoot, detected, configFiles, extensionSeen);
852
226
 
853
- const isWindows = platform === 'win32';
854
- const shell = isWindows ? 'cmd.exe' : '/bin/sh';
855
- const execOpts = {
856
- encoding: 'utf8',
857
- stdio: 'inherit',
858
- shell,
859
- timeout: 120000
860
- };
227
+ resolveFlutterVersusDart(detected, projectRoot);
861
228
 
862
- try {
863
- console.log(`Installing ${toolDef.name}: ${installCmd}`);
864
- execSync(installCmd, execOpts);
865
- return { success: true, message: `${toolDef.name} installed successfully` };
866
- } catch (error) {
867
- return { success: false, message: `Failed to install ${toolDef.name}: ${error.message}` };
868
- }
229
+ return {
230
+ detected: Array.from(detected),
231
+ configFiles,
232
+ };
869
233
  }
870
234
 
871
235
  /**
872
- * Generate project language config file.
873
- * @param {string} projectRoot - Project root
874
- * @param {string[]} languages - Detected languages
875
- * @param {Object} toolStatus - Tool status per language
236
+ * Check if a CLI tool is available.
237
+ * @param {string} toolName - Tool name
238
+ * @param {string} checkCmd - Command to check version
239
+ * @returns {{available: boolean, version?: string}}
876
240
  */
877
- function generateProjectConfig(projectRoot, languages, toolStatus) {
878
- const config = {
879
- version: 1,
880
- languages: languages.reduce((acc, lang) => {
881
- const langDef = LANGUAGE_REGISTRY[lang];
882
- acc[lang] = {
883
- name: langDef?.name || lang,
884
- tools: (toolStatus[lang] || []).map(t => ({
885
- name: t.tool.name,
886
- status: t.status,
887
- optional: t.tool.optional,
888
- gates: t.tool.gates,
889
- })),
890
- };
891
- return acc;
892
- }, {}),
893
- lastDetected: new Date().toISOString(),
894
- };
895
-
896
- const configPath = path.join(projectRoot, '.xp-gate-config.json');
897
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
898
-
899
- return configPath;
900
- }
241
+ const {
242
+ checkTool,
243
+ getToolsForLanguages,
244
+ installTool,
245
+ generateProjectConfig,
246
+ TOOL_PROBE_TIMEOUT_MS,
247
+ INSTALL_EXEC_TIMEOUT_MS,
248
+ } = require('./tool-install.js');
249
+ const { statusOfRow, iconOfRow, qualifiersOfRow } = require('./tool-display.js');
901
250
 
902
251
  /**
903
252
  * Read existing project config if present.
@@ -1005,6 +354,8 @@ function getArchitectureTools() {
1005
354
 
1006
355
  module.exports = {
1007
356
  LANGUAGE_REGISTRY,
357
+ extensionsPresentIn,
358
+ makeLazyExtensionScanner,
1008
359
  detectProjectLanguages,
1009
360
  checkTool,
1010
361
  getToolsForLanguages,
@@ -1014,6 +365,18 @@ module.exports = {
1014
365
  handleDetectLanguages,
1015
366
  handleCheckTools,
1016
367
  handleInstallTools,
368
+ planToolRepairs,
369
+ describeAction,
370
+ statusOfRow,
371
+ iconOfRow,
372
+ qualifiersOfRow,
373
+ printAuditReport,
374
+ toolEntry,
375
+ buildDetectionResult,
376
+ printAuditJson,
377
+ reportSelfCancellingPlan,
378
+ applyPlanActions,
379
+ buildInstallPlan,
1017
380
  getArchitectureTools,
1018
381
  detectBuildFileDependency,
1019
382
  };
@@ -1023,42 +386,81 @@ module.exports = {
1023
386
  * @param {string[]} args - Command arguments
1024
387
  * @returns {Promise<number>} Exit code
1025
388
  */
1026
- async function handleDetectLanguages(args) {
1027
- const projectRoot = process.cwd();
389
+ /**
390
+ * The JSON shape of a detection result: languages, where they were found, tools.
391
+ *
392
+ * `tools` is keyed by language, so a consumer can answer "what is missing for Rust"
393
+ * without re-deriving the language list.
394
+ */
395
+ function buildDetectionResult(detected, configFiles, toolStatus) {
396
+ const tools = {};
397
+ for (const [lang, list] of Object.entries(toolStatus)) {
398
+ tools[lang] = list.map((t) => ({
399
+ name: t.tool.name,
400
+ status: t.status,
401
+ optional: t.tool.optional,
402
+ version: t.version,
403
+ }));
404
+ }
405
+ return { languages: detected, configFiles, tools };
406
+ }
407
+
408
+ /**
409
+ * Report that nothing was detected, in whichever shape the caller asked for.
410
+ *
411
+ * An empty result is a valid answer, not a failure: a directory with no recognisable
412
+ * project has no languages, and exiting non-zero would make a legitimate "nothing
413
+ * here" look like an error.
414
+ *
415
+ * @param {boolean} jsonOutput
416
+ * @returns {number} exit code
417
+ */
418
+ function reportNoLanguages(jsonOutput) {
419
+ if (jsonOutput) {
420
+ console.log(JSON.stringify({ languages: [], configFiles: {} }, null, 2));
421
+ } else {
422
+ console.log('No languages detected.');
423
+ }
424
+ return 0;
425
+ }
426
+
427
+ /**
428
+ * Write the project language config and say WHERE it landed.
429
+ *
430
+ * The path is printed because the file is gitignored-by-convention in some projects
431
+ * and tracked in others; without it a reader cannot tell whether the write is
432
+ * something they need to commit.
433
+ */
434
+ function writeProjectConfig(projectRoot, detected, toolStatus) {
435
+ const configPath = generateProjectConfig(projectRoot, detected, toolStatus);
436
+ console.log(`\nGenerated config: ${configPath}`);
437
+ }
438
+
439
+ async function handleDetectLanguages(args, options = {}) {
440
+ // Injectable like the other handle* functions in this file. It defaulted to
441
+ // `process.cwd()` with no seam, so the only way to test it was to chdir --
442
+ // which vitest workers do not allow, and which made the whole command
443
+ // untestable rather than merely untested.
444
+ const projectRoot = options.projectRoot || process.cwd();
1028
445
  const jsonOutput = args.includes('--json');
1029
446
  const writeConfig = args.includes('--write') || !jsonOutput;
1030
447
 
1031
- console.log('Detecting project languages...');
1032
- console.log(`Project root: ${projectRoot}\n`);
448
+ // Human progress lines ONLY in human mode. Under `--json` stdout must hold exactly
449
+ // one document, and a leading "Detecting project languages..." makes it unparseable
450
+ // -- `jq` reports a syntax error pointing at the word, not at this line.
451
+ if (!jsonOutput) {
452
+ console.log('Detecting project languages...');
453
+ console.log(`Project root: ${projectRoot}\n`);
454
+ }
1033
455
 
1034
456
  const { detected, configFiles } = detectProjectLanguages(projectRoot);
1035
457
 
1036
- if (detected.length === 0) {
1037
- if (jsonOutput) {
1038
- console.log(JSON.stringify({ languages: [], configFiles: {} }, null, 2));
1039
- } else {
1040
- console.log('No languages detected.');
1041
- }
1042
- return 0;
1043
- }
458
+ if (detected.length === 0) return reportNoLanguages(jsonOutput);
1044
459
 
1045
460
  const toolStatus = getToolsForLanguages(detected);
1046
461
 
1047
462
  if (jsonOutput) {
1048
- const result = {
1049
- languages: detected,
1050
- configFiles,
1051
- tools: {},
1052
- };
1053
- for (const [lang, tools] of Object.entries(toolStatus)) {
1054
- result.tools[lang] = tools.map(t => ({
1055
- name: t.tool.name,
1056
- status: t.status,
1057
- optional: t.tool.optional,
1058
- version: t.version,
1059
- }));
1060
- }
1061
- console.log(JSON.stringify(result, null, 2));
463
+ console.log(JSON.stringify(buildDetectionResult(detected, configFiles, toolStatus), null, 2));
1062
464
  } else {
1063
465
  console.log('Detected languages:');
1064
466
  for (const lang of detected) {
@@ -1080,156 +482,539 @@ async function handleDetectLanguages(args) {
1080
482
  }
1081
483
  }
1082
484
 
1083
- if (writeConfig) {
1084
- const configPath = generateProjectConfig(projectRoot, detected, toolStatus);
1085
- console.log(`\nGenerated config: ${configPath}`);
1086
- }
1087
-
485
+ if (writeConfig) writeProjectConfig(projectRoot, detected, toolStatus);
1088
486
  return 0;
1089
487
  }
1090
488
 
489
+
490
+ /**
491
+ * Print the audit as a human-readable list.
492
+ *
493
+ * One list, not one section per language: the question "is my toolchain
494
+ * complete" is about the whole set. Language attribution is kept as a column so
495
+ * nothing is lost.
496
+ */
497
+ function printAuditReport(rows, summary) {
498
+ console.log('Quality Gate Tool Audit\n');
499
+ const width = Math.max(...rows.map((r) => r.name.length), 10);
500
+ for (const row of rows) {
501
+ const opt = row.optional ? ' (optional)' : '';
502
+ const version = row.installedVersion || 'N/A';
503
+ const shown = row.npxInvoked ? `${version} (via npx)` : version;
504
+ const q = qualifiersOfRow(row);
505
+ console.log(` ${iconOfRow(row)} ${row.name.padEnd(width)}${opt} — ${shown}${q ? ` [${q}]` : ''}`);
506
+ }
507
+ console.log('');
508
+ console.log(
509
+ `Summary: ${summary.total} tools — ${summary.missing} missing, ${summary.duplicated} duplicated, `
510
+ + `${summary.outdated} outdated, ${summary.unknown} unknown`,
511
+ );
512
+ if (!summary.complete) {
513
+ console.log('Run `xp-gate install-tools` to install, upgrade and de-duplicate.');
514
+ }
515
+ }
516
+
1091
517
  /**
1092
518
  * Handle check-tools CLI command.
519
+ *
520
+ * Reports completeness, validity, uniqueness and currency in ONE list. The
521
+ * audit is injectable so tests drive every branch without touching the network
522
+ * or the real toolchain.
523
+ *
1093
524
  * @param {string[]} args - Command arguments
525
+ * @param {{
526
+ * projectRoot?: string,
527
+ * languages?: string[]|null,
528
+ * audit?: (tools: Array, deps: object) => Array,
529
+ * resolveLatest?: (name: string) => string|null,
530
+ * }} [options]
1094
531
  * @returns {Promise<number>} Exit code
1095
532
  */
1096
- async function handleCheckTools(args) {
1097
- const projectRoot = process.cwd();
533
+ /**
534
+ * Collect the tools the question covers, then audit each through the gate's resolver.
535
+ *
536
+ * Resolving through the SAME helper the gates use (#843) is the point: a binary in
537
+ * `~/.local/bin` IS installed even when the hook's PATH omits it, and reporting it
538
+ * missing sends the reader off to install what is already there.
539
+ *
540
+ * `--all` passes null languages, meaning "every registered tool" rather than "this
541
+ * project's".
542
+ */
543
+ function auditRequestedTools(args, selection, options) {
544
+ const { languages, includeCrossLanguage } = selection;
545
+ const tools = collectGateTools({
546
+ registry: LANGUAGE_REGISTRY,
547
+ cliTools: GATE_CLI_TOOLS,
548
+ // `--all` asks about every registered tool, not just this project's.
549
+ languages: args.includes('--all') ? null : (languages.length ? languages : null),
550
+ }).filter((t) => includeCrossLanguage || (t.languages && t.languages.length > 0));
551
+
552
+ const audit = options.audit || ((list, deps) => auditAllTools(list, deps));
553
+ // Resolve tools through the SAME helper the gates use (#843): a binary in
554
+ // ~/.local/bin is installed even when the hook's PATH omits it, and reporting
555
+ // it missing sends the reader off to install what is already there.
556
+ const rows = audit(tools, {
557
+ resolveLatest: options.resolveLatest || ((n) => resolveLatestVersion(n)),
558
+ resolveTool: options.resolveTool || ((name) => resolveToolViaShell(name)),
559
+ });
560
+ const summary = summarizeAudit(rows);
561
+ return { rows, summary };
562
+ }
563
+
564
+ /**
565
+ * Emit the audit as JSON in the shape callers expect.
566
+ *
567
+ * CONTRACT, preserved from #468: the TOP LEVEL is keyed by language name, each value
568
+ * being that language's tool list. Callers parse it that way and a shape change here
569
+ * silently broke them once. The audit's newer facts (duplicates, currency,
570
+ * cross-language tools) ride ALONGSIDE in `summary` and `crossLanguage` rather than
571
+ * replacing the old shape.
572
+ */
573
+ /**
574
+ * The JSON shape of one audited tool.
575
+ *
576
+ * One factory for both call sites. They had drifted already -- the cross-language
577
+ * copy carried `npxInvoked` and the per-language one did not -- which is exactly the
578
+ * kind of divergence a second hand-written literal produces.
579
+ *
580
+ * `reason` is `undefined` when absent rather than omitted, so the key is stable for
581
+ * consumers that read it.
582
+ */
583
+ function toolEntry(row) {
584
+ return {
585
+ name: row.name,
586
+ status: statusOfRow(row),
587
+ optional: row.optional,
588
+ version: row.version,
589
+ gates: row.gates,
590
+ duplicated: row.duplicated,
591
+ paths: row.paths,
592
+ outdated: row.outdated,
593
+ latestVersion: row.latestVersion,
594
+ currency: row.currency,
595
+ reason: row.validityReason || undefined,
596
+ };
597
+ }
598
+
599
+ function printAuditJson(rows, summary, args) {
600
+ // CONTRACT, preserved from #468: the top level is keyed by language name and
601
+ // each value is that language's tool list. Callers parse it that way, and a
602
+ // shape change here silently broke them once already. The audit's new facts
603
+ // (duplicates, currency, cross-language tools) therefore ride alongside in
604
+ // `summary` and `crossLanguage` rather than replacing the old shape.
605
+ const byLanguage = {};
606
+ for (const row of rows) {
607
+ for (const lang of (row.languages && row.languages.length ? row.languages : ['(cross-language)'])) {
608
+ if (!byLanguage[lang]) byLanguage[lang] = [];
609
+ byLanguage[lang].push(toolEntry(row));
610
+ }
611
+ }
612
+ // Tools the gate scripts call directly; reported once, not per language.
613
+ // Only emitted when such tools exist: an always-present empty group would
614
+ // add a key to a contract callers compare exactly (#468).
615
+ const crossLanguage = rows
616
+ .filter((r) => !r.languages || r.languages.length === 0)
617
+ .map((r) => ({ ...toolEntry(r), npxInvoked: r.npxInvoked }));
618
+ if (crossLanguage.length > 0) byLanguage['(cross-language)'] = crossLanguage;
619
+
620
+ // `summary` and the flat view are additive: they appear only when asked
621
+ // for, so the historical shape ({ <language>: [...] }) stays byte-identical
622
+ // for callers that parse it exactly (#468).
623
+ const wantsAuditFields = args.includes('--audit') || args.includes('--flat');
624
+ // The flat view uses the SAME field names as the grouped view (`status`,
625
+ // `version`), so a consumer can switch between them without remapping.
626
+ const flatView = rows.map((r) => ({
627
+ name: r.name,
628
+ status: statusOfRow(r),
629
+ optional: r.optional,
630
+ version: r.version,
631
+ installedVersion: r.installedVersion,
632
+ gates: r.gates,
633
+ languages: r.languages,
634
+ duplicated: r.duplicated,
635
+ paths: r.paths,
636
+ distinctRealPaths: r.distinctRealPaths,
637
+ outdated: r.outdated,
638
+ latestVersion: r.latestVersion,
639
+ currency: r.currency,
640
+ npxInvoked: r.npxInvoked,
641
+ reason: r.validityReason || undefined,
642
+ }));
643
+ console.log(JSON.stringify({
644
+ ...byLanguage,
645
+ ...(wantsAuditFields ? { summary } : {}),
646
+ ...(args.includes('--flat') ? { tools: flatView } : {}),
647
+ }, null, 2));
648
+ }
649
+
650
+ async function handleCheckTools(args, options = {}) {
651
+ const projectRoot = options.projectRoot || process.cwd();
1098
652
  const jsonOutput = args.includes('--json');
1099
- let languages = parseLanguageFlag(args);
653
+ let languages = options.languages !== undefined ? options.languages : parseLanguageFlag(args);
1100
654
 
1101
655
  // Auto-detect if no languages specified
1102
- if (!languages) {
656
+ if (languages === undefined || languages === null) {
1103
657
  const detected = detectProjectLanguages(projectRoot);
1104
658
  languages = detected.detected;
1105
659
  }
1106
660
 
1107
- if (languages.length === 0) {
1108
- console.log('No languages detected or specified. Use --languages=<langs> to specify.');
1109
- return 1;
1110
- }
661
+ // The cross-language CLI tools are part of the answer even when no detected
662
+ // language mentions them: they are what the gate SCRIPTS call directly.
663
+ // The cross-language CLI tools belong to the answer when we are describing the
664
+ // whole toolchain (auto-detected or --all). When the caller names languages
665
+ // explicitly, they asked "what does THIS language need" and a cross-language
666
+ // section would answer a different question.
667
+ const explicitSelection = parseLanguageFlag(args);
668
+ // An EMPTY selection is "nothing was asked for", not "ask for nothing": the
669
+ // auto-detect path and `options.languages = []` must still describe the whole
670
+ // toolchain, or the report silently becomes empty and reads as complete.
671
+ const includeCrossLanguage = !explicitSelection || explicitSelection.length === 0
672
+ || args.includes('--all');
1111
673
 
1112
- const toolStatus = getToolsForLanguages(languages);
674
+ const { rows, summary } = auditRequestedTools(args, { languages, includeCrossLanguage }, options);
1113
675
 
1114
- if (jsonOutput) {
1115
- const result = {};
1116
- for (const [lang, tools] of Object.entries(toolStatus)) {
1117
- result[lang] = tools.map(t => ({
1118
- name: t.tool.name,
1119
- status: t.status,
1120
- optional: t.tool.optional,
1121
- version: t.version,
1122
- gates: t.tool.gates,
1123
- }));
676
+ if (jsonOutput) printAuditJson(rows, summary, args);
677
+ else printAuditReport(rows, summary);
678
+
679
+ return 0;
680
+ }
681
+
682
+ /**
683
+ * Paths owned by the distribution. A copy here is the SYSTEM's copy, not a
684
+ * duplicate install: removing it can take unrelated software with it, and the
685
+ * user asked explicitly for distro packages to be left alone (2026-11-23).
686
+ */
687
+ const { SYSTEM_PATH_PREFIXES } = require('./tool-audit.js');
688
+
689
+ /**
690
+ * Build a repair plan from audit rows. Pure: no IO, no execution.
691
+ *
692
+ * Rules, in the order they are applied per tool:
693
+ * 1. npx-invoked tools have no PATH entity — nothing to remove.
694
+ * 2. A distro-owned copy is never removed; it is reported as kept.
695
+ * 3. Duplicates: keep the FIRST path (what gates execute today) and remove the
696
+ * rest, so repairing does not change which binary the gates run.
697
+ * 4. Missing REQUIRED tool -> install. Missing optional -> skipped and named.
698
+ * 5. Outdated required tool -> upgrade.
699
+ *
700
+ * @param {Array} rows audit rows
701
+ * @param {{definitions?: Array, systemPrefixes?: string[], platform?: string}} [options]
702
+ * @returns {{actions: Array, clean: boolean}}
703
+ */
704
+ /**
705
+ * Plan an upgrade, and detect the plan that cancels itself.
706
+ *
707
+ * MEASURED DEFECT (2026-11-23): hadolint was duplicated AND outdated. The plan removed
708
+ * `~/.local/bin/hadolint`, then ran an installer whose command writes to that exact
709
+ * path -- so the duplicate came straight back and the repair silently achieved
710
+ * nothing. `writesToRemovedPath` names that case instead of reporting a success that
711
+ * is not one.
712
+ */
713
+ function planUpgrade(row, installCmd, actions) {
714
+ if (row.outdated === true) {
715
+ // MEASURED DEFECT (2026-11-23): hadolint was duplicated AND outdated. The
716
+ // plan removed ~/.local/bin/hadolint, then ran an installer whose command
717
+ // writes to that exact path — so the duplicate came straight back and the
718
+ // repair silently achieved nothing. Detect it and say so loudly instead of
719
+ // reporting a success that is not one.
720
+ const removedHere = actions
721
+ .filter((a) => a.kind === 'remove-duplicate' && a.tool === row.name)
722
+ .map((a) => a.path);
723
+ const writesToRemovedPath = Boolean(installCmd)
724
+ && removedHere.some((removedPath) => String(installCmd).includes(removedPath));
725
+ actions.push({
726
+ kind: 'upgrade',
727
+ tool: row.name,
728
+ command: installCmd,
729
+ from: row.installedVersion,
730
+ to: row.latestVersion,
731
+ writesToRemovedPath,
732
+ conflictsWith: writesToRemovedPath ? removedHere : undefined,
733
+ });
734
+ }
735
+ }
736
+
737
+ /**
738
+ * Plan removal of a duplicated tool's extra copies.
739
+ *
740
+ * Only USER-owned duplicates are a repair. A distro copy plus a user copy is
741
+ * coexistence (jq from apt vs a newer ~/.local/bin/jq), and removing either is not a
742
+ * fix: the distro one can drag dependencies with it, the user one is what the reader
743
+ * installed on purpose.
744
+ *
745
+ * The KEEP copy is the one the resolver hands to the gates, not whichever path came
746
+ * first. Measured 2026-11-24: with the same tool and the same two paths, listing the
747
+ * installer's copy FIRST made `writesToRemovedPath` false and listing it SECOND made
748
+ * it true -- the self-cancelling guard depended on the order of `distinctRealPaths`,
749
+ * which follows however the locator walked PATH. A guard that only fires for half the
750
+ * callers is not a guard.
751
+ *
752
+ * @returns {boolean} true when the row is fully handled and needs no further action
753
+ */
754
+ function planDuplicateRemoval(row, userCopies, actions) {
755
+ if (row.duplicated && userCopies.length > 1) {
756
+ // Keep the copy the resolver actually hands to the gates, not whichever
757
+ // path happened to come first.
758
+ //
759
+ // Measured 2026-11-24: with the same tool and the same two paths, listing
760
+ // the copy the installer writes to FIRST made `writesToRemovedPath` false
761
+ // and listing it SECOND made it true -- the self-cancelling-plan guard
762
+ // therefore depended on the order of `distinctRealPaths`, which comes from
763
+ // however the locator walked PATH. A guard that only fires for half the
764
+ // callers is not a guard.
765
+ const preferred = row.resolvedPath && userCopies.includes(row.resolvedPath)
766
+ ? row.resolvedPath
767
+ : userCopies[0];
768
+ const keep = preferred;
769
+ const rest = userCopies.filter((p) => p !== keep);
770
+ actions.push({ kind: 'keep', tool: row.name, path: keep });
771
+ for (const dup of rest) {
772
+ actions.push({ kind: 'remove-duplicate', tool: row.name, path: dup, keepPath: keep });
1124
773
  }
1125
- console.log(JSON.stringify(result, null, 2));
1126
- } else {
1127
- console.log('Quality Gate Tool Status:\n');
1128
- let totalAvailable = 0;
1129
- let totalMissing = 0;
774
+ // A tool that is duplicated but otherwise current needs no install step.
775
+ if (row.available && !row.outdated) return true;
776
+ }
1130
777
 
1131
- for (const [lang, tools] of Object.entries(toolStatus)) {
1132
- const langDef = LANGUAGE_REGISTRY[lang];
1133
- console.log(`${langDef?.name || lang}:`);
1134
-
1135
- for (const t of tools) {
1136
- const statusIcon = t.status === 'available' ? '✓' : '✗';
1137
- const optMark = t.tool.optional ? ' (optional)' : '';
1138
- const version = t.version || 'N/A';
1139
- console.log(` ${statusIcon} ${t.tool.name}${optMark} — ${version}`);
1140
- if (t.status === 'available') {
1141
- totalAvailable++;
1142
- } else {
1143
- totalMissing++;
1144
- }
778
+ return false;
779
+ }
780
+
781
+ function planToolRepairs(rows, options = {}) {
782
+ const definitions = options.definitions || [];
783
+ const platform = options.platform || process.platform;
784
+ const systemPrefixes = options.systemPrefixes || SYSTEM_PATH_PREFIXES;
785
+ const defByName = new Map(definitions.map((d) => [d.name, d]));
786
+ const isSystemOwned = (p) => systemPrefixes.some((pre) => String(p).startsWith(pre));
787
+
788
+ const actions = [];
789
+ for (const row of rows || []) {
790
+ if (row.npxInvoked) continue;
791
+
792
+ const def = defByName.get(row.name);
793
+ const installCmd = def && def.install
794
+ ? (def.install[platform] || def.install.linux || def.install.npm || null)
795
+ : null;
796
+
797
+ // Only USER-owned duplicates are a repair. A distro copy plus a user copy is
798
+ // coexistence (jq from apt vs a newer ~/.local/bin/jq), and removing either
799
+ // is not a fix: the distro one can drag dependencies with it, the user one is
800
+ // what the reader installed on purpose.
801
+ // `distinctRealPaths` is only present on rows that were actually located on
802
+ // disk; a row can be flagged `duplicated` by another producer (or by a
803
+ // caller assembling rows by hand) without that list. Defaulting to [] keeps
804
+ // the plan honest -- no copies means no duplicate to remove -- instead of
805
+ // throwing out of a planning function.
806
+ const userCopies = (row.userCopies || (row.distinctRealPaths || []).filter((p) => !isSystemOwned(p)));
807
+ if (planDuplicateRemoval(row, userCopies, actions)) continue;
808
+
809
+ if (!row.available) {
810
+ if (row.optional) {
811
+ actions.push({ kind: 'skip-optional', tool: row.name, reason: 'optional tool not installed' });
812
+ } else {
813
+ actions.push({ kind: 'install', tool: row.name, command: installCmd });
1145
814
  }
1146
- console.log('');
815
+ continue;
1147
816
  }
1148
817
 
1149
- console.log(`Summary: ${totalAvailable} available, ${totalMissing} missing`);
1150
- if (totalMissing > 0) {
1151
- console.log('Run `xp-gate install-tools` to install missing tools.');
1152
- }
818
+ planUpgrade(row, installCmd, actions);
1153
819
  }
1154
820
 
1155
- return 0;
821
+ return { actions, clean: actions.length === 0 };
822
+ }
823
+
824
+ /** Human line for one planned action. */
825
+ function describeAction(action) {
826
+ switch (action.kind) {
827
+ case 'remove-duplicate':
828
+ return `remove duplicate ${action.tool}: ${action.path} (keeping ${action.keepPath})`;
829
+ case 'keep':
830
+ return `keep ${action.tool}: ${action.path}`;
831
+ case 'keep-system':
832
+ return `keep (system) ${action.tool}: ${action.path}`;
833
+ case 'skip-optional':
834
+ return `skip (optional) ${action.tool}`;
835
+ case 'install':
836
+ return `install ${action.tool} ← ${action.command || 'no installer known'}`;
837
+ case 'upgrade':
838
+ return `upgrade ${action.tool} ${action.from} → ${action.to} ← ${action.command || 'no installer known'}`;
839
+ default:
840
+ return `${action.kind} ${action.tool}`;
841
+ }
842
+ }
843
+
844
+ /** Default command runner: returns {status}. Injectable so tests never execute. */
845
+ function defaultRunCommand(command) {
846
+ if (!command) return { status: 1, error: 'no installer command' };
847
+ try {
848
+ execSync(command, { stdio: 'inherit', timeout: INSTALL_EXEC_TIMEOUT_MS, shell: true });
849
+ return { status: 0 };
850
+ } catch (err) {
851
+ return { status: typeof err.status === 'number' ? err.status : 1, error: String(err.message || err) };
852
+ }
853
+ }
854
+
855
+ /** Default file remover, used only for duplicate cleanup. */
856
+ function defaultRemoveFile(target) {
857
+ try {
858
+ fs.rmSync(target, { force: true });
859
+ return true;
860
+ } catch {
861
+ return false;
862
+ }
1156
863
  }
1157
864
 
1158
865
  /**
1159
866
  * Handle install-tools CLI command.
867
+ *
868
+ * Installs missing required tools, upgrades outdated ones and removes duplicate
869
+ * copies so each tool ends up as one current, working entity.
870
+ *
871
+ * Without `--yes` nothing is executed: the plan is printed and the command says
872
+ * plainly that it changed nothing. Silence there would be indistinguishable
873
+ * from "the repair ran and needed no work".
874
+ *
1160
875
  * @param {string[]} args - Command arguments
876
+ * @param {{
877
+ * projectRoot?: string,
878
+ * languages?: string[],
879
+ * audit?: (tools: Array, deps: object) => Array,
880
+ * definitions?: Array,
881
+ * run?: (cmd: string) => {status: number},
882
+ * removeFile?: (p: string) => boolean,
883
+ * }} [options]
1161
884
  * @returns {Promise<number>} Exit code
1162
885
  */
1163
- async function handleInstallTools(args) {
1164
- const projectRoot = process.cwd();
1165
- const dryRun = args.includes('--dry-run');
1166
- const autoYes = args.includes('--yes') || args.includes('-y');
1167
- let languages = parseLanguageFlag(args);
886
+ /**
887
+ * Build the repair plan for this project's toolchain.
888
+ *
889
+ * Installer commands come from the registry entry (a language tool) or the CLI entry,
890
+ * which is why `definitions` concatenates both: a tool reachable from either side must
891
+ * be installable, and `planToolRepairs` looks definitions up by name alone.
892
+ */
893
+ function buildInstallPlan(args, options, projectRoot) {
894
+ let languages = options.languages !== undefined ? options.languages : parseLanguageFlag(args);
895
+ if (languages === undefined || languages === null) {
896
+ languages = detectProjectLanguages(projectRoot).detected;
897
+ }
1168
898
 
1169
- // Auto-detect if no languages specified
1170
- if (!languages) {
1171
- const detected = detectProjectLanguages(projectRoot);
1172
- languages = detected.detected;
1173
- }
899
+ const tools = collectGateTools({
900
+ registry: LANGUAGE_REGISTRY,
901
+ cliTools: GATE_CLI_TOOLS,
902
+ languages: args.includes('--all') || !languages.length ? null : languages,
903
+ });
1174
904
 
1175
- if (languages.length === 0) {
1176
- console.log('No languages detected or specified.');
1177
- return 1;
1178
- }
905
+ const audit = options.audit || ((list, deps) => auditAllTools(list, deps));
906
+ const rows = audit(tools, { resolveLatest: options.resolveLatest || ((n) => resolveLatestVersion(n)) });
1179
907
 
1180
- console.log('Checking tools for languages:', languages.join(', '));
1181
- console.log('');
908
+ // Installer commands come from the registry entry (language) or the CLI entry.
909
+ const definitions = options.definitions
910
+ || [
911
+ ...tools,
912
+ ...GATE_CLI_TOOLS.map((c) => ({ name: c.tool, install: c.install, optional: false })),
913
+ ];
1182
914
 
1183
- const toolStatus = getToolsForLanguages(languages);
1184
- const missingTools = [];
915
+ const plan = planToolRepairs(rows, { definitions });
1185
916
 
1186
- for (const [lang, tools] of Object.entries(toolStatus)) {
1187
- for (const t of tools) {
1188
- if (t.status === 'missing' && !t.tool.optional) {
1189
- missingTools.push({ lang, tool: t.tool });
1190
- }
1191
- }
917
+ return planToolRepairs(rows, { definitions });
918
+ }
919
+
920
+ /**
921
+ * Report a plan whose parts undo each other, and say whether it must be refused.
922
+ *
923
+ * A repair whose parts cancel is not a repair. Refusing -- rather than running it and
924
+ * watching a duplicate survive a "successful" run -- points the operator at the
925
+ * installer command, which is the thing that actually needs fixing.
926
+ *
927
+ * @param {{actions: Array}} plan
928
+ * @returns {boolean} true when the plan is self-cancelling
929
+ */
930
+ function reportSelfCancellingPlan(plan) {
931
+ // A repair whose parts undo each other is not a repair. Refuse to run it and
932
+ // say which action conflicts, so the operator can fix the installer instead of
933
+ // watching a duplicate survive a "successful" run.
934
+ const conflicting = plan.actions.filter((a) => a.kind === 'upgrade' && a.writesToRemovedPath);
935
+ if (conflicting.length) {
936
+ for (const a of conflicting) {
937
+ console.log(`CONFLICT ${a.tool}: its installer writes to ${(a.conflictsWith || []).join(', ')},`);
938
+ console.log(' which this same plan removes — the duplicate would come back.');
1192
939
  }
940
+ console.log('Refusing to apply a self-cancelling plan. Fix the installer command first.');
941
+ return 1;
942
+ }
1193
943
 
1194
- if (missingTools.length === 0) {
1195
- console.log('All required tools are available!');
1196
- return 0;
944
+ return false;
945
+ }
946
+
947
+ /**
948
+ * Run the mutating actions, counting failures without stopping.
949
+ *
950
+ * One failed install must not strand the rest -- the operator wants to see every
951
+ * outcome in one pass, not discover them one re-run at a time. A missing installer
952
+ * command counts as a failure rather than being skipped silently: the tool stays
953
+ * broken either way, and only one of those tells the reader.
954
+ */
955
+ function applyPlanActions(actions, io) {
956
+ const { run, removeFile } = io;
957
+ let failed = 0;
958
+ for (const action of actions) {
959
+ if (action.kind === 'remove-duplicate') {
960
+ const ok = removeFile(action.path);
961
+ if (!ok) failed += 1;
962
+ console.log(`${ok ? 'removed' : 'FAILED to remove'} ${action.path}`);
963
+ continue;
964
+ }
965
+ if (!action.command) {
966
+ failed += 1;
967
+ console.log(`FAILED ${action.tool}: no installer command for this platform`);
968
+ continue;
969
+ }
970
+ console.log(`> ${action.command}`);
971
+ const result = run(action.command) || { status: 1 };
972
+ if (result.status !== 0) {
973
+ failed += 1;
974
+ console.log(`FAILED ${action.tool} (exit ${result.status})`);
1197
975
  }
976
+ }
977
+
978
+ return failed;
979
+ }
1198
980
 
1199
- console.log(`Found ${missingTools.length} missing required tool(s):\n`);
1200
- for (const { lang, tool } of missingTools) {
1201
- const installCmd = tool.install[process.platform] || tool.install.linux || 'N/A';
1202
- console.log(` • ${tool.name} (${lang})`);
1203
- console.log(` Install: ${installCmd}`);
981
+ async function handleInstallTools(args, options = {}) {
982
+ const projectRoot = options.projectRoot || process.cwd();
983
+ const autoYes = args.includes('--yes') || args.includes('-y');
984
+ const run = options.run || defaultRunCommand;
985
+ const removeFile = options.removeFile || defaultRemoveFile;
986
+
987
+ const plan = buildInstallPlan(args, options, projectRoot);
988
+ if (plan.clean) {
989
+ console.log('Toolchain is already up to date: nothing to install, upgrade or remove.');
990
+ return 0;
1204
991
  }
992
+
993
+ console.log('Planned toolchain changes:\n');
994
+ for (const action of plan.actions) console.log(` • ${describeAction(action)}`);
1205
995
  console.log('');
1206
996
 
1207
- if (dryRun) {
1208
- console.log('Dry run — no tools installed.');
997
+ if (reportSelfCancellingPlan(plan)) return 1;
998
+
999
+ const mutating = plan.actions.filter((a) =>
1000
+ a.kind === 'install' || a.kind === 'upgrade' || a.kind === 'remove-duplicate');
1001
+ if (!mutating.length) {
1002
+ console.log('No changes needed for the required tools.');
1209
1003
  return 0;
1210
1004
  }
1211
1005
 
1212
1006
  if (!autoYes) {
1213
- console.log('Run with --yes to install missing tools.');
1007
+ console.log(`${mutating.length} change(s) planned. No changes were made — re-run with --yes to apply them.`);
1214
1008
  return 0;
1215
1009
  }
1216
1010
 
1217
- console.log('Installing missing tools...\n');
1218
- let successCount = 0;
1219
- let failCount = 0;
1220
-
1221
- for (const { lang, tool } of missingTools) {
1222
- console.log(`Installing ${tool.name} for ${lang}...`);
1223
- const result = installTool(tool);
1224
- if (result.success) {
1225
- console.log(` ✓ ${result.message}\n`);
1226
- successCount++;
1227
- } else {
1228
- console.log(` ✗ ${result.message}\n`);
1229
- failCount++;
1230
- }
1231
- }
1011
+ const failed = applyPlanActions(mutating, { run, removeFile });
1232
1012
 
1233
- console.log(`Installation complete: ${successCount} succeeded, ${failCount} failed.`);
1234
- return failCount > 0 ? 1 : 0;
1013
+ console.log('');
1014
+ if (failed > 0) {
1015
+ console.log(`${failed} of ${mutating.length} change(s) failed.`);
1016
+ return 1;
1017
+ }
1018
+ console.log(`Applied ${mutating.length} change(s) successfully.`);
1019
+ return 0;
1235
1020
  }