@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
package/lib/doctor.js CHANGED
@@ -16,12 +16,20 @@ const { detectPlatform, getTemplateDir } = sharedPaths;
16
16
  // written the config, and `--fix` returned 1 on a healthy installation.
17
17
  //
18
18
  // These are therefore read through the module at each use, not destructured.
19
- const HOME_DIR = () => sharedPaths.HOME_DIR;
20
- const CONFIG_FILE = () => sharedPaths.CONFIG_FILE;
21
- const GLOBAL_HOOKS_DIR = () => sharedPaths.GLOBAL_HOOKS_DIR;
22
- const GLOBAL_ADAPTERS_DIR = () => sharedPaths.GLOBAL_ADAPTERS_DIR;
19
+ const {
20
+ HOME_DIR,
21
+ CONFIG_FILE,
22
+ GLOBAL_HOOKS_DIR,
23
+ GLOBAL_ADAPTERS_DIR,
24
+ PKG_DIR,
25
+ DELPHI_ROLES,
26
+ MIN_DISTINCT_MODELS,
27
+ } = require('./doctor-constants.js');
23
28
  const { checkUpgrade, formatUpgradeMsg } = require('./check-version.js');
24
29
  const { GATE_CLI_TOOLS, checkCliTool, getToolInstallCmd, checkBash, detectInstalledPlatforms, getSkillsDirs } = require('./detect-deps.js');
30
+ // Doctor's tool section is built from the shared audit, so the validity /
31
+ // uniqueness / currency rules live in exactly one place (2026-11-23).
32
+ const { mapAuditRowsToDoctorChecks, auditGateCliTools } = require('./doctor-tool-checks.js');
25
33
  // #505: the single source of truth for module resolution order. The hook reads a
26
34
  // generated shell projection of this same module.
27
35
  const {
@@ -45,7 +53,6 @@ const {
45
53
  } = require('./doctor-tui.js');
46
54
 
47
55
  // npm package source dir (template hooks/adapters)
48
- const PKG_DIR = path.dirname(__dirname);
49
56
 
50
57
  /**
51
58
  * Read the package version from the installed package.json.
@@ -208,7 +215,7 @@ async function execWithTimeout(cmd, opts = {}) {
208
215
  // tool as exit 1 + "'x' is not recognized"), and re-running it would only
209
216
  // burn time, so that path still returns null immediately.
210
217
  const { attempts, ...execOpts } = opts;
211
- const maxAttempts = process.platform === 'win32' ? (attempts || 3) : 1;
218
+ const maxAttempts = process.platform === 'win32' ? (attempts || WINDOWS_EXEC_ATTEMPTS) : 1;
212
219
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
213
220
  try {
214
221
  const { stdout, stderr } = await execAsync(cmd, {
@@ -221,7 +228,7 @@ async function execWithTimeout(cmd, opts = {}) {
221
228
  // existing null check ("probe produced nothing") applies — an empty
222
229
  // non-null result would read as a present tool with no version.
223
230
  if (attempt + 1 < maxAttempts) {
224
- await new Promise(resolve => setTimeout(resolve, 50));
231
+ await new Promise(resolve => setTimeout(resolve, EXEC_RETRY_DELAY_MS));
225
232
  continue;
226
233
  }
227
234
  return null;
@@ -356,8 +363,19 @@ function getConfig() {
356
363
  }
357
364
  }
358
365
 
366
+ /**
367
+ * Persist the config, or fail loudly with the path.
368
+ *
369
+ * Every fix path in this file ends here, so a silent failure would report a repair
370
+ * that was never written.
371
+ */
359
372
  function saveConfig(config) {
360
- fs.writeFileSync(CONFIG_FILE(), JSON.stringify(config, null, 2));
373
+ const target = CONFIG_FILE();
374
+ try {
375
+ fs.writeFileSync(target, JSON.stringify(config, null, 2));
376
+ } catch (err) {
377
+ throw new Error(`cannot save config to ${target}: ${err.message}`);
378
+ }
361
379
  }
362
380
 
363
381
  async function getGitDir() {
@@ -671,26 +689,21 @@ const HOOK_SUPPORT_FILES = [
671
689
  * @param {{repoRoot?: string, repoHooks?: string, installedHooks?: string}} [ctx]
672
690
  * @returns {{checks: Array<{name: string, status: string, detail: string}>, issues: number}}
673
691
  */
674
- function diagnoseHookDrift(ctx = {}) {
675
- const checks = [];
692
+ /**
693
+ * Compare each tracked hook against its installed copy.
694
+ *
695
+ * The DIRECTION of the drift is reported, not just the fact: "githooks/ is newer"
696
+ * means sync, "installed is newer" means the installed copy has work the repo does
697
+ * not. Telling an operator which way it went is the difference between a fix and a
698
+ * guess.
699
+ *
700
+ * @param {string} repoHooks
701
+ * @param {string} installedHooks
702
+ * @param {Array} checks appended to
703
+ * @returns {number} issues found
704
+ */
705
+ function compareHookCopies(repoHooks, installedHooks, checks) {
676
706
  let issues = 0;
677
-
678
- // XP_GATE_REPO_ROOT lets a caller (or a test) name the canonical repo
679
- // explicitly instead of inferring it from the process cwd.
680
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
681
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
682
- const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
683
-
684
- // Nothing to compare when the project carries no canonical *hook* source, or
685
- // when no global copy exists at all. Both must stay completely silent.
686
- //
687
- // A `githooks/` directory holding only `adapters/` is NOT a hook source of
688
- // truth -- consumer projects get that layout from `xp-gate init`, and the
689
- // adapters there are unrelated to which hook file executes.
690
- if (!hasCanonicalHooks(repoHooks) || !fs.existsSync(installedHooks)) {
691
- return { checks, issues };
692
- }
693
-
694
707
  for (const name of DRIFT_COMPARED_HOOKS) {
695
708
  const repoFile = path.join(repoHooks, name);
696
709
  const installedFile = path.join(installedHooks, name);
@@ -721,43 +734,81 @@ function diagnoseHookDrift(ctx = {}) {
721
734
  });
722
735
  issues++;
723
736
  }
737
+ return issues;
738
+ }
724
739
 
725
- // lib/ shared libraries: pre-commit sources lib/*.sh at runtime, so a missing
726
- // or stale installed lib/ copy breaks the hook entirely after a sync (#488).
740
+ /**
741
+ * Compare the shared `lib/` copies that pre-commit sources at runtime.
742
+ *
743
+ * A missing or stale installed `lib/` breaks the hook ENTIRELY after a sync (#488),
744
+ * which is why these are compared separately from the hook files themselves.
745
+ *
746
+ * @param {string} repoHooks
747
+ * @param {string} installedHooks
748
+ * @param {Array} checks appended to
749
+ * @returns {number} issues found
750
+ */
751
+ function compareLibCopies(repoHooks, installedHooks, checks) {
727
752
  const repoLib = path.join(repoHooks, 'lib');
728
753
  const installedLib = path.join(installedHooks, 'lib');
729
- if (fs.existsSync(repoLib) && fs.statSync(repoLib).isDirectory()) {
730
- let libEntries = [];
731
- try {
732
- libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
733
- } catch {
734
- libEntries = [];
735
- }
736
- for (const entry of libEntries) {
737
- if (!entry.isFile()) continue;
738
- const rel = `lib/${entry.name}`;
739
- const repoFile = path.join(repoLib, entry.name);
740
- const installedFile = path.join(installedLib, entry.name);
741
- const label = `Hook drift: ${rel}`;
742
- if (!fs.existsSync(installedFile)) {
743
- checks.push({
744
- name: label,
745
- status: 'FAIL',
746
- detail: 'installed lib/ copy is missing (hooks source lib/ at runtime)',
747
- });
748
- issues++;
749
- } else if (!filesAreIdentical(repoFile, installedFile)) {
750
- checks.push({
751
- name: label,
752
- status: 'FAIL',
753
- detail: 'installed lib/ copy differs from githooks/lib/',
754
- });
755
- issues++;
756
- } else {
757
- checks.push({ name: label, status: 'PASS', detail: 'Installed copy matches githooks/' });
758
- }
754
+ if (!fs.existsSync(repoLib) || !fs.statSync(repoLib).isDirectory()) return 0;
755
+
756
+ let issues = 0;
757
+ let libEntries = [];
758
+ try {
759
+ libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
760
+ } catch {
761
+ libEntries = [];
762
+ }
763
+ for (const entry of libEntries) {
764
+ if (!entry.isFile()) continue;
765
+ const rel = `lib/${entry.name}`;
766
+ const repoFile = path.join(repoLib, entry.name);
767
+ const installedFile = path.join(installedLib, entry.name);
768
+ const label = `Hook drift: ${rel}`;
769
+ if (!fs.existsSync(installedFile)) {
770
+ checks.push({
771
+ name: label,
772
+ status: 'FAIL',
773
+ detail: 'installed lib/ copy is missing (hooks source lib/ at runtime)',
774
+ });
775
+ issues++;
776
+ } else if (!filesAreIdentical(repoFile, installedFile)) {
777
+ checks.push({
778
+ name: label,
779
+ status: 'FAIL',
780
+ detail: 'installed lib/ copy differs from githooks/lib/',
781
+ });
782
+ issues++;
783
+ } else {
784
+ checks.push({ name: label, status: 'PASS', detail: 'Installed copy matches githooks/' });
759
785
  }
760
786
  }
787
+ return issues;
788
+ }
789
+
790
+ function diagnoseHookDrift(ctx = {}) {
791
+ const checks = [];
792
+ let issues = 0;
793
+
794
+ // XP_GATE_REPO_ROOT lets a caller (or a test) name the canonical repo
795
+ // explicitly instead of inferring it from the process cwd.
796
+ const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
797
+ const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
798
+ const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
799
+
800
+ // Nothing to compare when the project carries no canonical *hook* source, or
801
+ // when no global copy exists at all. Both must stay completely silent.
802
+ //
803
+ // A `githooks/` directory holding only `adapters/` is NOT a hook source of
804
+ // truth -- consumer projects get that layout from `xp-gate init`, and the
805
+ // adapters there are unrelated to which hook file executes.
806
+ if (!hasCanonicalHooks(repoHooks) || !fs.existsSync(installedHooks)) {
807
+ return { checks, issues };
808
+ }
809
+
810
+ issues += compareHookCopies(repoHooks, installedHooks, checks);
811
+ issues += compareLibCopies(repoHooks, installedHooks, checks);
761
812
 
762
813
  return { checks, issues };
763
814
  }
@@ -912,50 +963,115 @@ function readPair(repoFile, installedFile) {
912
963
  * import the .ts module). Grandfathers everything before AUDIT_LEDGER_SINCE;
913
964
  * only NEW implausible durations or unattributed commits count as issues.
914
965
  */
966
+ /** The npm registry probe is a network call; it gets 8 s before being skipped. */
967
+ const NPM_PROBE_TIMEOUT_MS = 8000;
968
+
969
+ /** The runner gates on this; below it, a review exits 1 mid-run. */
970
+ const MIN_NODE_MAJOR = 18;
971
+
972
+ /** Windows reports a missing tool as exit 1, so a retry separates a real failure
973
+ * from a transient one. */
974
+ const WINDOWS_EXEC_ATTEMPTS = 3;
975
+ /** Back-off between those attempts (the previous inline value). */
976
+ const EXEC_RETRY_DELAY_MS = 50;
977
+
978
+ /** A tool call longer than this is a measurement artefact, not a real duration. */
979
+ const AUDIT_MAX_PLAUSIBLE_HOURS = 6;
980
+
915
981
  const AUDIT_LEDGER_SINCE = '2026-10-30T00:00:00.000Z';
916
- const AUDIT_MAX_PLAUSIBLE_MS = 6 * 60 * 60 * 1000;
982
+ const AUDIT_MAX_PLAUSIBLE_MS = AUDIT_MAX_PLAUSIBLE_HOURS * 60 * 60 * 1000;
917
983
 
918
984
  function diagnoseAuditLedger(ctx = {}) {
919
- const checks = [];
920
- let issues = 0;
921
985
  const repoRoot = ctx.repoRoot || process.cwd();
922
986
  const logPath = path.join(repoRoot, '.xp-gate', 'audit.jsonl');
987
+
988
+ const loaded = loadAuditEntries(logPath);
989
+ if (loaded.verdict) return { checks: [loaded.verdict], issues: 0 };
990
+
991
+ const tally = tallyAuditAnomalies(loaded.entries);
992
+ return { checks: [auditLedgerCheck(tally)], issues: 0 };
993
+ }
994
+
995
+ /**
996
+ * Read the audit ledger, or the SKIP/WARN check that stands in for it.
997
+ *
998
+ * Returns `{ verdict }` when there is nothing to scan, `{ entries }` otherwise --
999
+ * one exit shape per outcome so the caller does not branch on three sentinels.
1000
+ *
1001
+ * @param {string} logPath
1002
+ * @returns {{verdict?: object, entries?: object[]}}
1003
+ */
1004
+ function loadAuditEntries(logPath) {
1005
+ const name = 'Audit ledger';
923
1006
  if (!fs.existsSync(logPath)) {
924
- checks.push({ name: 'Audit ledger', status: 'SKIP', detail: 'no .xp-gate/audit.jsonl' });
925
- return { checks, issues };
1007
+ return { verdict: { name, status: 'SKIP', detail: 'no .xp-gate/audit.jsonl' } };
926
1008
  }
927
- let entries;
928
1009
  try {
929
- entries = fs.readFileSync(logPath, 'utf8').split(/\r?\n/).filter((l) => l.trim()).map((l) => JSON.parse(l));
1010
+ const entries = fs.readFileSync(logPath, 'utf8')
1011
+ .split(/\r?\n/)
1012
+ .filter((l) => l.trim())
1013
+ .map((l) => JSON.parse(l));
1014
+ return { entries };
930
1015
  } catch (err) {
931
- checks.push({ name: 'Audit ledger', status: 'WARN', detail: `unreadable: ${err.message}` });
932
- return { checks, issues };
933
- }
934
- let implausible = 0;
935
- let missingCommit = 0;
936
- let considered = 0;
937
- for (const e of entries) {
938
- if (typeof e.timestamp === 'string' && e.timestamp < AUDIT_LEDGER_SINCE) continue;
939
- considered += 1;
940
- if (typeof e.duration_ms === 'number'
941
- && (!Number.isFinite(e.duration_ms) || e.duration_ms < 0 || e.duration_ms > AUDIT_MAX_PLAUSIBLE_MS)) {
942
- implausible += 1;
943
- }
944
- if (!e.commit_hash || e.commit_hash === 'unknown') missingCommit += 1;
945
- }
946
- const total = implausible + missingCommit;
947
- if (total > 0) {
948
- checks.push({
949
- name: 'Audit ledger',
950
- status: 'WARN',
951
- detail: `${total} anomal${total === 1 ? 'y' : 'ies'} since ${AUDIT_LEDGER_SINCE} (${implausible} implausible duration, ${missingCommit} unattributed) — run: xp-gate audit --check`,
952
- });
953
- // WARN, not FAIL: telemetry integrity is not a blocking gate, but it must
954
- // be visible. Kept at 0 issues so it never inflates the FAIL count.
955
- } else {
956
- checks.push({ name: 'Audit ledger', status: 'PASS', detail: `${considered} entr${considered === 1 ? 'y' : 'ies'} clean since ${AUDIT_LEDGER_SINCE}` });
1016
+ return { verdict: { name, status: 'WARN', detail: `unreadable: ${err.message}` } };
957
1017
  }
958
- return { checks, issues };
1018
+ }
1019
+
1020
+ /**
1021
+ * An implausible duration, or a commit the entry cannot be attributed to.
1022
+ *
1023
+ * An entry older than the ledger cutoff is skipped: the anomalies this check exists
1024
+ * for were introduced by a specific release, and counting everything before it would
1025
+ * report the same fixed history forever.
1026
+ *
1027
+ * @param {object[]} entries
1028
+ * @returns {{considered: number, implausible: number, missingCommit: number}}
1029
+ */
1030
+ function tallyAuditAnomalies(entries) {
1031
+ const recent = entries.filter((e) => !(typeof e.timestamp === 'string' && e.timestamp < AUDIT_LEDGER_SINCE));
1032
+ return {
1033
+ considered: recent.length,
1034
+ implausible: recent.filter(hasImplausibleDuration).length,
1035
+ missingCommit: recent.filter(hasNoCommit).length,
1036
+ };
1037
+ }
1038
+
1039
+ /** A duration that is present but negative, non-finite, or absurdly long. */
1040
+ function hasImplausibleDuration(entry) {
1041
+ if (typeof entry.duration_ms !== 'number') return false;
1042
+ return !Number.isFinite(entry.duration_ms)
1043
+ || entry.duration_ms < 0
1044
+ || entry.duration_ms > AUDIT_MAX_PLAUSIBLE_MS;
1045
+ }
1046
+
1047
+ /** An entry that cannot be attributed to a commit. */
1048
+ function hasNoCommit(entry) {
1049
+ return !entry.commit_hash || entry.commit_hash === 'unknown';
1050
+ }
1051
+
1052
+ /**
1053
+ * The ledger's verdict.
1054
+ *
1055
+ * WARN, not FAIL: telemetry integrity is not a blocking gate, but it must be
1056
+ * visible. The issue count stays 0 so it never inflates the FAIL tally.
1057
+ *
1058
+ * @param {{considered: number, implausible: number, missingCommit: number}} tally
1059
+ * @returns {object}
1060
+ */
1061
+ function auditLedgerCheck(tally) {
1062
+ const name = 'Audit ledger';
1063
+ const anomalies = tally.implausible + tally.missingCommit;
1064
+ if (anomalies === 0) {
1065
+ const noun = tally.considered === 1 ? 'entry' : 'entries';
1066
+ return { name, status: 'PASS', detail: `${tally.considered} ${noun} clean since ${AUDIT_LEDGER_SINCE}` };
1067
+ }
1068
+ const plural = anomalies === 1 ? 'y' : 'ies';
1069
+ return {
1070
+ name,
1071
+ status: 'WARN',
1072
+ detail: `${anomalies} anomal${plural} since ${AUDIT_LEDGER_SINCE} `
1073
+ + `(${tally.implausible} implausible duration, ${tally.missingCommit} unattributed) — run: xp-gate audit --check`,
1074
+ };
959
1075
  }
960
1076
 
961
1077
  /**
@@ -1000,31 +1116,30 @@ function diagnoseFlakyQuarantine(ctx = {}) {
1000
1116
  return { checks, issues };
1001
1117
  }
1002
1118
 
1003
- function diagnoseModuleDrift(ctx = {}) {
1004
- const checks = [];
1119
+ /**
1120
+ * Compare each module the hook ACTUALLY executes against the repo's copy.
1121
+ *
1122
+ * A module that is not installed has nothing to judge. A module whose executed copy
1123
+ * IS the repo's own copy is not drift. Everything else is examined, with three
1124
+ * verdicts rather than two:
1125
+ *
1126
+ * - identical bytes -> PASS
1127
+ * - same content, different
1128
+ * line endings/indentation -> PASS (FAILing on a re-wrap teaches the reader
1129
+ * to distrust the check)
1130
+ * - genuinely different -> FAIL, with the tier hint
1131
+ *
1132
+ * `executedFor` is filled in because the caller reports shadow copies against it
1133
+ * (#500).
1134
+ *
1135
+ * @param {string} repoHooks
1136
+ * @param {string[]} dirs resolution tiers
1137
+ * @param {Array} checks appended to
1138
+ * @param {Map<string, string|undefined>} executedFor filled in
1139
+ * @returns {number} issues found
1140
+ */
1141
+ function compareExecutedModules(repoHooks, dirs, checks, executedFor) {
1005
1142
  let issues = 0;
1006
-
1007
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
1008
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
1009
-
1010
- // Silent without a canonical repo source to compare against: consumer
1011
- // projects have no `githooks/` root of truth, only what was installed.
1012
- if (!hasCanonicalHooks(repoHooks)) {
1013
- return { checks, issues };
1014
- }
1015
-
1016
- const dirs = resolveExecutedModuleDirs({
1017
- globalAdapterDir: ctx.globalAdapterDir || ctx.installedAdapters,
1018
- projectGithooks: ctx.projectGithooks || repoHooks,
1019
- scriptDir: ctx.scriptDir,
1020
- });
1021
-
1022
- // Copies the hook never resolves to, occupying the lookup positions it does
1023
- // resolve through. They are not drift -- nothing executes them -- but they are
1024
- // how #500 reproduces: the next install order shift, or a move to project
1025
- // mode, promotes one silently. Report with the absolute path so the developer
1026
- // can judge; do not count, because no shipped command removes them (#495 R2).
1027
- const executedFor = new Map();
1028
1143
  for (const name of repoModuleNames(repoHooks)) {
1029
1144
  const source = repoModuleSource(repoHooks, name);
1030
1145
  if (!source) continue;
@@ -1065,6 +1180,36 @@ function diagnoseModuleDrift(ctx = {}) {
1065
1180
  checks.push({ name: label, status: 'FAIL', detail: `${driftDetail}${hint}` });
1066
1181
  issues++;
1067
1182
  }
1183
+ return issues;
1184
+ }
1185
+
1186
+ function diagnoseModuleDrift(ctx = {}) {
1187
+ const checks = [];
1188
+ let issues = 0;
1189
+
1190
+ const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
1191
+ const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
1192
+
1193
+ // Silent without a canonical repo source to compare against: consumer
1194
+ // projects have no `githooks/` root of truth, only what was installed.
1195
+ if (!hasCanonicalHooks(repoHooks)) {
1196
+ return { checks, issues };
1197
+ }
1198
+
1199
+ const dirs = resolveExecutedModuleDirs({
1200
+ globalAdapterDir: ctx.globalAdapterDir || ctx.installedAdapters,
1201
+ projectGithooks: ctx.projectGithooks || repoHooks,
1202
+ scriptDir: ctx.scriptDir,
1203
+ });
1204
+
1205
+ // Copies the hook never resolves to, occupying the lookup positions it does
1206
+ // resolve through. They are not drift -- nothing executes them -- but they are
1207
+ // how #500 reproduces: the next install order shift, or a move to project
1208
+ // mode, promotes one silently. Report with the absolute path so the developer
1209
+ // can judge; do not count, because no shipped command removes them (#495 R2).
1210
+
1211
+ const executedFor = new Map();
1212
+ issues += compareExecutedModules(repoHooks, dirs, checks, executedFor);
1068
1213
 
1069
1214
  for (const [name, file] of nonExecutedCopies(dirs, executedFor)) {
1070
1215
  checks.push({
@@ -1206,6 +1351,52 @@ function moduleDriftDetail(repoText, installedText) {
1206
1351
  * @param {{repoRoot?: string, repoHooks?: string, installedAdapters?: string, force?: boolean}} [ctx]
1207
1352
  * @returns {{synced: string[], skipped: string[], refused: Array<{name: string, repoOnly: number, installedOnly: number}>, errors: string[], installedAdapters: string}}
1208
1353
  */
1354
+ /**
1355
+ * Sync one gate module to the path that actually executes it.
1356
+ *
1357
+ * The ORDER of the checks is the substance. A module that is not installed is not
1358
+ * this command's business (residue is reported by the diagnosis, never deleted by a
1359
+ * sync). A module differing only in formatting is skipped rather than rewritten --
1360
+ * copying it would churn the file and change nothing. Only after both does the copy
1361
+ * guard run, and a refusal there is a decision about destroying machine-only
1362
+ * hardening.
1363
+ *
1364
+ * @param {{name: string, repoHooks: string, dirs: object, force: boolean,
1365
+ * synced: string[], skipped: string[], refused: Array, errors: string[]}} q
1366
+ * arrays mutated in place
1367
+ */
1368
+ function syncOneModule(q) {
1369
+ const { name, repoHooks, dirs, force, synced, skipped, refused, errors } = q;
1370
+ const source = repoModuleSource(repoHooks, name);
1371
+ if (!source) return;
1372
+ const target = executedModulePath(name, dirs);
1373
+ if (!target) return; // nothing executes this module
1374
+
1375
+ if (pathsEquivalent(source, target) || filesAreIdentical(source, target)) {
1376
+ skipped.push(name);
1377
+ return;
1378
+ }
1379
+
1380
+ const decision = copyGuardDecision(source, target, force);
1381
+ // Formatting-only: nothing to repair, and rewriting the file would churn it.
1382
+ if (!decision.refuse && !decision.forced && decision.repoOnly === 0 && decision.installedOnly === 0) {
1383
+ skipped.push(name);
1384
+ return;
1385
+ }
1386
+ if (decision.refuse) {
1387
+ refused.push({ name, repoOnly: decision.repoOnly, installedOnly: decision.installedOnly, unknown: decision.unknown, target });
1388
+ return;
1389
+ }
1390
+
1391
+ try {
1392
+ fs.copyFileSync(source, target);
1393
+ fs.chmodSync(target, 0o755);
1394
+ synced.push(name);
1395
+ } catch (err) {
1396
+ errors.push(`${name}: ${err.message}`);
1397
+ }
1398
+ }
1399
+
1209
1400
  function syncModulesFromRepo(ctx = {}) {
1210
1401
  const synced = [];
1211
1402
  const skipped = [];
@@ -1234,37 +1425,7 @@ function syncModulesFromRepo(ctx = {}) {
1234
1425
  const installedAdapters = dirs.globalAdapterDir;
1235
1426
 
1236
1427
  for (const name of repoModuleNames(repoHooks)) {
1237
- const source = repoModuleSource(repoHooks, name);
1238
- if (!source) continue;
1239
- const target = executedModulePath(name, dirs);
1240
- if (!target) continue; // nothing executes this module; residue is not this command's business
1241
- if (pathsEquivalent(source, target)) {
1242
- skipped.push(name);
1243
- continue;
1244
- }
1245
- if (filesAreIdentical(source, target)) {
1246
- skipped.push(name);
1247
- continue;
1248
- }
1249
-
1250
- const decision = copyGuardDecision(source, target, !!ctx.force);
1251
- // Formatting-only: nothing to repair, and rewriting the file would churn it.
1252
- if (!decision.refuse && !decision.forced && decision.repoOnly === 0 && decision.installedOnly === 0) {
1253
- skipped.push(name);
1254
- continue;
1255
- }
1256
- if (decision.refuse) {
1257
- refused.push({ name, repoOnly: decision.repoOnly, installedOnly: decision.installedOnly, unknown: decision.unknown, target });
1258
- continue;
1259
- }
1260
-
1261
- try {
1262
- fs.copyFileSync(source, target);
1263
- fs.chmodSync(target, 0o755);
1264
- synced.push(name);
1265
- } catch (err) {
1266
- errors.push(`${name}: ${err.message}`);
1267
- }
1428
+ syncOneModule({ name, repoHooks, dirs, force: !!ctx.force, synced, skipped, refused, errors });
1268
1429
  }
1269
1430
 
1270
1431
  return { synced, skipped, refused, errors, installedAdapters, dirs, sourceMissing: false };
@@ -1678,160 +1839,216 @@ function appendDeployLogEntry(logPath, entry) {
1678
1839
  *
1679
1840
  * @returns {{synced: string[], skipped: string[], refused: Array<{name: string, repoOnly: number, installedOnly: number}>, errors: string[], installedHooks: string, backups: string[]}}
1680
1841
  */
1681
- function syncGlobalHooksFromRepo(ctx = {}) {
1682
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
1683
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
1684
- const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
1685
- // #583: the version that performs the overwrite is part of the record. Read the
1686
- // repo's VERSION beside the hooks, so the log answers "which release did this"
1687
- // without the caller having to remember to pass it.
1688
- const version = ctx.version
1689
- || readVersionFile(path.join(repoRoot, 'VERSION'))
1690
- || 'unknown';
1691
-
1692
- const synced = [];
1693
- const skipped = [];
1694
- const refused = [];
1695
- const errors = [];
1696
- const backups = [];
1697
- const backupsDir = path.join(installedHooks, 'backups');
1698
- const deployLog = path.join(installedHooks, 'deploy.log');
1699
-
1700
- if (!fs.existsSync(repoHooks)) {
1701
- errors.push(`no githooks/ directory at ${repoHooks}`);
1702
- return { synced, skipped, refused, errors, installedHooks, backups };
1703
- }
1704
-
1705
- if (!hasCanonicalHooks(repoHooks)) {
1706
- errors.push(`no hook files in ${repoHooks} (only adapters?) -- nothing to sync from`);
1707
- return { synced, skipped, refused, errors, installedHooks, backups };
1708
- }
1709
-
1710
- try {
1711
- fs.mkdirSync(installedHooks, { recursive: true });
1712
- } catch (err) {
1713
- errors.push(`cannot create ${installedHooks}: ${err.message}`);
1714
- return { synced, skipped, refused, errors, installedHooks, backups };
1715
- }
1716
-
1717
- for (const name of DRIFT_COMPARED_HOOKS) {
1718
- const source = path.join(repoHooks, name);
1842
+ /**
1843
+ * Copy a set of files from the repo into the install directory, recording what
1844
+ * happened to each.
1845
+ *
1846
+ * Three outcomes per file, and the distinction matters: an identical file is
1847
+ * `skipped` (nothing to do), a missing source is also `skipped` (this project does
1848
+ * not carry it), and only a copy that actually ran is `synced`.
1849
+ *
1850
+ * #566: the previous version is backed up BEFORE the overwrite, because this is
1851
+ * the moment machine-only work is lost. The exec bit is re-applied explicitly --
1852
+ * a copied hook that is not executable silently never runs.
1853
+ *
1854
+ * Support files differ from hook entry points in two ways, and both are options
1855
+ * rather than a second copy of this loop: they may live in a subdirectory (so the
1856
+ * parent must be created -- #798, where `copyFileSync` failed with ENOENT and left
1857
+ * a HALF-SYNCED hook that died on its first gate), and they are not executed by
1858
+ * git, so no exec bit is set.
1859
+ *
1860
+ * @param {{names: string[], repoDir: string, installDir: string, version: string,
1861
+ * backupsDir: string, deployLog: string, synced: string[], skipped: string[],
1862
+ * errors: string[], backups: string[], createParents?: boolean,
1863
+ * keepExecBit?: boolean}} ctx arrays mutated in place
1864
+ */
1865
+ function syncHookEntries(ctx) {
1866
+ const { names, repoDir, installDir, version, backupsDir, deployLog, synced, skipped, errors, backups } = ctx;
1867
+ const createParents = ctx.createParents === true;
1868
+ const keepExecBit = ctx.keepExecBit !== false;
1869
+ for (const name of names) {
1870
+ const source = path.join(repoDir, name);
1719
1871
  if (!fs.existsSync(source)) {
1720
1872
  skipped.push(name);
1721
1873
  continue;
1722
1874
  }
1723
- const target = path.join(installedHooks, name);
1875
+ const target = path.join(installDir, name);
1724
1876
  try {
1725
1877
  if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1726
1878
  skipped.push(name);
1727
1879
  continue;
1728
1880
  }
1729
- // #566: the previous version is kept, because this overwrite is the moment
1730
- // machine-only work is lost.
1731
1881
  const backup = backupBeforeOverwrite(target, backupsDir);
1732
1882
  if (backup) backups.push(backup);
1733
- // copyFileSync preserves content; the exec bit is re-applied explicitly
1734
- // because a copied hook that is not executable silently never runs.
1883
+ if (createParents) fs.mkdirSync(path.dirname(target), { recursive: true });
1735
1884
  fs.copyFileSync(source, target);
1736
- fs.chmodSync(target, 0o755);
1885
+ if (keepExecBit) fs.chmodSync(target, 0o755);
1737
1886
  // #583: record it, so a downstream can tell an overwrite from a fresh
1738
- // install without having to diff checksums first.
1887
+ // install without diffing checksums first.
1739
1888
  appendDeployLogEntry(deployLog, { file: name, version, backup });
1740
1889
  synced.push(name);
1741
1890
  } catch (err) {
1742
1891
  errors.push(`${name}: ${err.message}`);
1743
1892
  }
1744
1893
  }
1894
+ }
1745
1895
 
1746
- // Hook support files (#505): sourced by the hooks but not Git entry points, so
1747
- // they need the same copy treatment or an upgraded install dies at the source
1748
- // line. Treated like the hooks themselves (always refreshed, no refusal) —
1749
- // they hold no machine-local content.
1750
- for (const name of HOOK_SUPPORT_FILES) {
1751
- const source = path.join(repoHooks, name);
1752
- if (!fs.existsSync(source)) continue;
1753
- const target = path.join(installedHooks, name);
1754
- try {
1755
- if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1756
- skipped.push(name);
1757
- continue;
1896
+ /**
1897
+ * Sync the shared `lib/` directory that pre-commit sources at runtime.
1898
+ *
1899
+ * A synced hook file without its libraries dies at the source line on the machine
1900
+ * (#488), so this is not optional housekeeping. Each library gets the same refusal
1901
+ * treatment as a gate module -- a shared library can carry machine-only hardening
1902
+ * just as a module does, and the module guard and the lib guard must not disagree
1903
+ * about how destructive a sync may be. Unreadable content refuses too: unknown is
1904
+ * not the same as safe.
1905
+ *
1906
+ * @param {{repoHooks: string, installedHooks: string, version: string,
1907
+ * backupsDir: string, deployLog: string, synced: string[], skipped: string[],
1908
+ * refused: Array, errors: string[], backups: string[], force: boolean}} ctx
1909
+ * arrays mutated in place
1910
+ */
1911
+ /**
1912
+ * Copy one shared library, honouring the copy guard.
1913
+ *
1914
+ * Three outcomes before anything is written: identical is skipped, a refused guard
1915
+ * is recorded as `refused` (the caller reports it), and a guard that reports no
1916
+ * divergence at all is skipped. Only after those does the backup-then-copy happen.
1917
+ *
1918
+ * @param {{source: string, target: string, rel: string, force: boolean,
1919
+ * backupsDir: string, deployLog: string, version: string, synced: string[],
1920
+ * skipped: string[], refused: Array, errors: string[], backups: string[]}} p
1921
+ * arrays mutated in place
1922
+ */
1923
+ function syncOneLibFile(p) {
1924
+ const { source, target, rel, force, backupsDir, deployLog, version, synced, skipped, refused, errors, backups } = p;
1925
+ try {
1926
+ if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1927
+ skipped.push(rel);
1928
+ return;
1929
+ }
1930
+ if (fs.existsSync(target)) {
1931
+ const decision = copyGuardDecision(source, target, force);
1932
+ if (decision.refuse) {
1933
+ refused.push({ name: rel, repoOnly: decision.repoOnly, installedOnly: decision.installedOnly, unknown: decision.unknown });
1934
+ return;
1935
+ }
1936
+ if (decision.forced === false && decision.repoOnly === 0 && decision.installedOnly === 0) {
1937
+ skipped.push(rel);
1938
+ return;
1758
1939
  }
1759
- const backup = backupBeforeOverwrite(target, backupsDir);
1760
- if (backup) backups.push(backup);
1761
- // #798: support files may live in a subdirectory (gate-entries/*.sh). The
1762
- // install directory has no such subdirectory yet on an upgraded install, and
1763
- // copyFileSync does not create parents -- the entries failed with ENOENT
1764
- // while gate-driver.sh succeeded, leaving a half-synced hook that dies on
1765
- // its first gate instead of before any.
1766
- fs.mkdirSync(path.dirname(target), { recursive: true });
1767
- fs.copyFileSync(source, target);
1768
- appendDeployLogEntry(deployLog, { file: name, version, backup });
1769
- synced.push(name);
1770
- } catch (err) {
1771
- errors.push(`${name}: ${err.message}`);
1772
1940
  }
1941
+ const backup = backupBeforeOverwrite(target, backupsDir);
1942
+ if (backup) backups.push(backup);
1943
+ fs.copyFileSync(source, target);
1944
+ fs.chmodSync(target, 0o755);
1945
+ appendDeployLogEntry(deployLog, { file: rel, version, backup });
1946
+ synced.push(rel);
1947
+ } catch (err) {
1948
+ errors.push(`${rel}: ${err.message}`);
1773
1949
  }
1950
+ }
1774
1951
 
1775
- // lib/ shared libraries: pre-commit sources lib/*.sh, so a synced hook file
1776
- // without its libraries dies at the source line on the machine (#488).
1952
+ function syncLibDirectory(ctx) {
1953
+ const { repoHooks, installedHooks, version, backupsDir, deployLog, synced, skipped, refused, errors, backups, force } = ctx;
1777
1954
  const repoLib = path.join(repoHooks, 'lib');
1778
1955
  const installedLib = path.join(installedHooks, 'lib');
1779
- if (fs.existsSync(repoLib) && fs.statSync(repoLib).isDirectory()) {
1780
- try {
1781
- fs.mkdirSync(installedLib, { recursive: true });
1782
- } catch (err) {
1783
- errors.push(`cannot create ${installedLib}: ${err.message}`);
1784
- return { synced, skipped, refused, errors, installedHooks, backups };
1785
- }
1786
- let libEntries = [];
1787
- try {
1788
- libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
1789
- } catch (err) {
1790
- errors.push(`cannot read ${repoLib}: ${err.message}`);
1791
- return { synced, skipped, refused, errors, installedHooks, backups };
1792
- }
1793
- for (const entry of libEntries) {
1794
- if (!entry.isFile()) continue;
1795
- const rel = `lib/${entry.name}`;
1796
- const source = path.join(repoLib, entry.name);
1797
- const target = path.join(installedLib, entry.name);
1798
- try {
1799
- if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1800
- skipped.push(rel);
1801
- continue;
1802
- }
1803
- // A shared library can carry machine-only hardening just like a gate
1804
- // module does, so it gets the same refusal instead of an unconditional
1805
- // overwrite (#488 Round 2 -- the module guard and the lib guard must not
1806
- // disagree about how destructive a sync is allowed to be). Unreadable
1807
- // content refuses too: unknown is not the same as safe (#495 Round 3).
1808
- if (fs.existsSync(target)) {
1809
- const decision = copyGuardDecision(source, target, !!ctx.force);
1810
- if (decision.refuse) {
1811
- refused.push({
1812
- name: rel,
1813
- repoOnly: decision.repoOnly,
1814
- installedOnly: decision.installedOnly,
1815
- unknown: decision.unknown,
1816
- });
1817
- continue;
1818
- }
1819
- if (decision.forced === false && decision.repoOnly === 0 && decision.installedOnly === 0) {
1820
- skipped.push(rel);
1821
- continue;
1822
- }
1823
- }
1824
- const backup = backupBeforeOverwrite(target, backupsDir);
1825
- if (backup) backups.push(backup);
1826
- fs.copyFileSync(source, target);
1827
- fs.chmodSync(target, 0o755);
1828
- appendDeployLogEntry(deployLog, { file: rel, version, backup });
1829
- synced.push(rel);
1830
- } catch (err) {
1831
- errors.push(`${rel}: ${err.message}`);
1832
- }
1833
- }
1956
+ if (!fs.existsSync(repoLib) || !fs.statSync(repoLib).isDirectory()) return;
1957
+
1958
+ try {
1959
+ fs.mkdirSync(installedLib, { recursive: true });
1960
+ } catch (err) {
1961
+ errors.push(`cannot create ${installedLib}: ${err.message}`);
1962
+ return;
1963
+ }
1964
+ let libEntries = [];
1965
+ try {
1966
+ libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
1967
+ } catch (err) {
1968
+ errors.push(`cannot read ${repoLib}: ${err.message}`);
1969
+ return;
1970
+ }
1971
+ for (const entry of libEntries) {
1972
+ if (!entry.isFile()) continue;
1973
+ const rel = `lib/${entry.name}`;
1974
+ const source = path.join(repoLib, entry.name);
1975
+ const target = path.join(installedLib, entry.name);
1976
+ syncOneLibFile({ source, target, rel, force, backupsDir, deployLog, version,
1977
+ synced, skipped, refused, errors, backups });
1978
+ }
1979
+ }
1980
+
1981
+ /**
1982
+ * Check there is something to sync, and make sure the install directory exists.
1983
+ *
1984
+ * Returns a reason when the sync cannot proceed. Three failures share one exit
1985
+ * here because they all mean the same thing to the caller: nothing was synced, and
1986
+ * the reason is in `errors`.
1987
+ *
1988
+ * @param {string} repoHooks
1989
+ * @param {string} installedHooks
1990
+ * @param {string[]} errors appended to
1991
+ * @returns {string|null} the reason, or null when the sync may proceed
1992
+ */
1993
+ function prepareInstallDir(repoHooks, installedHooks, errors) {
1994
+ if (!fs.existsSync(repoHooks)) {
1995
+ errors.push(`no githooks/ directory at ${repoHooks}`);
1996
+ return 'missing';
1997
+ }
1998
+ if (!hasCanonicalHooks(repoHooks)) {
1999
+ errors.push(`no hook files in ${repoHooks} (only adapters?) -- nothing to sync from`);
2000
+ return 'empty';
2001
+ }
2002
+ try {
2003
+ fs.mkdirSync(installedHooks, { recursive: true });
2004
+ } catch (err) {
2005
+ errors.push(`cannot create ${installedHooks}: ${err.message}`);
2006
+ return 'unwritable';
1834
2007
  }
2008
+ return null;
2009
+ }
2010
+
2011
+ function syncGlobalHooksFromRepo(ctx = {}) {
2012
+ const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
2013
+ const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
2014
+ const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
2015
+ // #583: the version that performs the overwrite is part of the record. Read the
2016
+ // repo's VERSION beside the hooks, so the log answers "which release did this"
2017
+ // without the caller having to remember to pass it.
2018
+ const version = ctx.version
2019
+ || readVersionFile(path.join(repoRoot, 'VERSION'))
2020
+ || 'unknown';
2021
+
2022
+ const synced = [];
2023
+ const skipped = [];
2024
+ const refused = [];
2025
+ const errors = [];
2026
+ const backups = [];
2027
+ const backupsDir = path.join(installedHooks, 'backups');
2028
+ const deployLog = path.join(installedHooks, 'deploy.log');
2029
+
2030
+ const blocked = prepareInstallDir(repoHooks, installedHooks, errors);
2031
+ if (blocked) return { synced, skipped, refused, errors, installedHooks, backups };
2032
+
2033
+ syncHookEntries({
2034
+ names: DRIFT_COMPARED_HOOKS, repoDir: repoHooks, installDir: installedHooks,
2035
+ version, backupsDir, deployLog, synced, skipped, errors, backups,
2036
+ });
2037
+
2038
+ // Hook support files (#505): sourced by the hooks but not Git entry points, so
2039
+ // they need the same copy treatment or an upgraded install dies at the source
2040
+ // line. Treated like the hooks themselves (always refreshed, no refusal) —
2041
+ // they hold no machine-local content.
2042
+ syncHookEntries({
2043
+ names: HOOK_SUPPORT_FILES, repoDir: repoHooks, installDir: installedHooks,
2044
+ version, backupsDir, deployLog, synced, skipped, errors, backups,
2045
+ createParents: true, keepExecBit: false,
2046
+ });
2047
+
2048
+ syncLibDirectory({
2049
+ repoHooks, installedHooks, version, backupsDir, deployLog,
2050
+ synced, skipped, refused, errors, backups, force: !!ctx.force,
2051
+ });
1835
2052
 
1836
2053
  return { synced, skipped, refused, errors, installedHooks, backups };
1837
2054
  }
@@ -1916,7 +2133,15 @@ async function checkAdapters(checks, mode, gitDirPromise) {
1916
2133
  checks.push({ name: 'Adapters directory', status: 'FAIL', detail: 'Missing' });
1917
2134
  return 1;
1918
2135
  }
1919
- const adapterFiles = fs.readdirSync(adaptersDir).filter(f => f.endsWith('.sh'));
2136
+ let adapterFiles;
2137
+ try {
2138
+ adapterFiles = fs.readdirSync(adaptersDir).filter(f => f.endsWith('.sh'));
2139
+ } catch (err) {
2140
+ // An unreadable directory is not an EMPTY one; saying "Empty" would send the
2141
+ // reader to reinstall when the problem is permissions.
2142
+ checks.push({ name: 'Adapters directory', status: 'FAIL', detail: `Unreadable: ${err.message}` });
2143
+ return 1;
2144
+ }
1920
2145
  if (adapterFiles.length === 0) {
1921
2146
  checks.push({ name: 'Adapters directory', status: 'FAIL', detail: 'Empty directory' });
1922
2147
  return 1;
@@ -1951,6 +2176,70 @@ async function checkAdapters(checks, mode, gitDirPromise) {
1951
2176
  * D) Env + CLI tools — fully independent, run IN PARALLEL
1952
2177
  * E) TUI + Skills — independent, run IN PARALLEL
1953
2178
  */
2179
+ /**
2180
+ * Run the independent check groups concurrently and total their issue counts.
2181
+ *
2182
+ * The groups only share the `checks` sink and the git directory; nothing reads
2183
+ * another's result. Running them concurrently is what keeps `doctor` responsive on
2184
+ * a machine where every tool probe is a child process.
2185
+ *
2186
+ * The hook-drift group is deferred behind a resolved promise on purpose: it is
2187
+ * repo-scoped (it compares `githooks/` against the install), so it must not delay
2188
+ * the groups that apply to every project.
2189
+ *
2190
+ * @param {Array} checks shared sink, appended to by every group
2191
+ * @param {object} config
2192
+ * @param {{refreshEnv: boolean}} opts
2193
+ * @returns {Promise<number>} total issues found
2194
+ */
2195
+ async function runDiagnosticGroups(checks, config, opts) {
2196
+ const gitDirPromise = getGitDir();
2197
+
2198
+ const hooksPromise = (async () => {
2199
+ if (config.mode === 'local') return checkLocalHooks(checks);
2200
+ return checkGlobalHooks(checks);
2201
+ })();
2202
+
2203
+ const adaptersPromise = checkAdapters(checks, config.mode, gitDirPromise);
2204
+
2205
+ const envPromise = checkEnv(checks);
2206
+ // #469: the tool probes run in the hook environment; --refresh-env swaps in the
2207
+ // registry PATH so "installed but invisible" separates from "not installed". The
2208
+ // staleness check always runs: it is what makes a stale terminal honest.
2209
+ const cliToolsPromise = diagnoseCliToolsAsync(checks, { refreshEnv: opts.refreshEnv });
2210
+ const stalenessPromise = diagnosePathStaleness(checks);
2211
+
2212
+ const tuiPromise = diagnoseTuiRegistration(checks);
2213
+ const skillsPromise = diagnoseInstalledSkills(config, checks);
2214
+
2215
+ // Group E: repo-vs-installed hook drift (#451). Independent of config.mode: the
2216
+ // drift matters exactly because the installed copy, not githooks/, is what
2217
+ // executes. Gate modules drift independently of the hook files (#495), and the
2218
+ // audit ledger rides the same repo-scoped group.
2219
+ const driftPromise = Promise.resolve().then(() => {
2220
+ const drift = diagnoseHookDrift();
2221
+ checks.push(...drift.checks);
2222
+ const moduleDrift = diagnoseModuleDrift();
2223
+ checks.push(...moduleDrift.checks);
2224
+ const ledger = diagnoseAuditLedger();
2225
+ checks.push(...ledger.checks);
2226
+ return drift.issues + moduleDrift.issues + ledger.issues;
2227
+ });
2228
+
2229
+ const results = await Promise.allSettled([
2230
+ hooksPromise, adaptersPromise, envPromise, cliToolsPromise,
2231
+ stalenessPromise, tuiPromise, skillsPromise, driftPromise,
2232
+ ]);
2233
+
2234
+ let issues = 0;
2235
+ for (const result of results) {
2236
+ if (result.status === 'fulfilled' && typeof result.value === 'number') {
2237
+ issues += result.value;
2238
+ }
2239
+ }
2240
+ return issues;
2241
+ }
2242
+
1954
2243
  async function diagnoseAsync(refreshEnv = false, progress = null) {
1955
2244
  // #629: `progress` is a live view of the checks completed so far. The global
1956
2245
  // timeout used to discard everything diagnoseAsync had already produced; with a
@@ -1985,69 +2274,7 @@ async function diagnoseAsync(refreshEnv = false, progress = null) {
1985
2274
  issues += diagnoseTemplateDir(config, checks);
1986
2275
  // (Spawn capability probe already ran at the top of diagnoseAsync — #525.)
1987
2276
 
1988
- // --- Phase 2: Fetch gitDir early (needed by hooks and adapters) ---
1989
- const gitDirPromise = getGitDir();
1990
-
1991
- // --- Phase 3: Run independent groups in parallel ---
1992
- // Group A: Hooks (needs config.mode + gitDir)
1993
- const hooksPromise = (async () => {
1994
- if (config.mode === 'local') {
1995
- return checkLocalHooks(checks);
1996
- }
1997
- return checkGlobalHooks(checks);
1998
- })();
1999
-
2000
- // Group B: Adapters (needs config.mode + gitDir)
2001
- const adaptersPromise = checkAdapters(checks, config.mode, gitDirPromise);
2002
-
2003
- // Group C: Environment checks + CLI tools — fully parallel
2004
- const envPromise = checkEnv(checks);
2005
- // #469: the tool probes run in the hook environment; --refresh-env swaps in
2006
- // the registry PATH so "installed but invisible" separates from "not
2007
- // installed". The staleness check runs always: it is what makes a stale
2008
- // terminal's green verdict honest.
2009
- const cliToolsPromise = diagnoseCliToolsAsync(checks, { refreshEnv });
2010
- const stalenessPromise = diagnosePathStaleness(checks);
2011
-
2012
- // Group D: TUI + Skills (independent)
2013
- const tuiPromise = diagnoseTuiRegistration(checks);
2014
- const skillsPromise = diagnoseInstalledSkills(config, checks);
2015
-
2016
- // Group E: repo-vs-installed hook drift (#451). Independent of config.mode:
2017
- // the drift matters exactly because the installed copy, not githooks/, is
2018
- // what executes. Detect if this is the xp-gate repo itself.
2019
- const driftPromise = Promise.resolve().then(() => {
2020
- const drift = diagnoseHookDrift();
2021
- checks.push(...drift.checks);
2022
- // The gate modules pre-commit sources at runtime drift independently of the
2023
- // hook files and live in a different directory (#495).
2024
- const moduleDrift = diagnoseModuleDrift();
2025
- checks.push(...moduleDrift.checks);
2026
- // Audit-ledger health (P0): telemetry anomalies are not hook drift, but
2027
- // they ride the same repo-scoped group and must be surfaced by doctor.
2028
- const ledger = diagnoseAuditLedger();
2029
- checks.push(...ledger.checks);
2030
- return drift.issues + moduleDrift.issues + ledger.issues;
2031
- });
2032
-
2033
- // Wait for ALL parallel groups
2034
- const results = await Promise.allSettled([
2035
- hooksPromise,
2036
- adaptersPromise,
2037
- envPromise,
2038
- cliToolsPromise,
2039
- stalenessPromise,
2040
- tuiPromise,
2041
- skillsPromise,
2042
- driftPromise,
2043
- ]);
2044
-
2045
- // Collect issue counts from settled promises
2046
- for (const result of results) {
2047
- if (result.status === 'fulfilled' && typeof result.value === 'number') {
2048
- issues += result.value;
2049
- }
2050
- }
2277
+ issues += await runDiagnosticGroups(checks, config, { refreshEnv });
2051
2278
 
2052
2279
  return { checks, issues };
2053
2280
  }
@@ -2210,6 +2437,89 @@ async function readRegistryPath() {
2210
2437
  * be perfectly healthy; only this terminal is stale, and the remedy is a
2211
2438
  * new terminal (or `xp-gate doctor --refresh-env`).
2212
2439
  */
2440
+ /**
2441
+ * Report that PATH freshness could not be determined.
2442
+ *
2443
+ * Fail closed: no readable registry hive is NOT evidence of freshness, so this is
2444
+ * a WARN with the reason attached, never a PASS. The advice is included because the
2445
+ * consequence is concrete -- after installing a tool, a stale PATH makes "not
2446
+ * found" mean "not in this terminal", and the operator needs to know that before
2447
+ * believing any verdict.
2448
+ *
2449
+ * @param {Array<{label: string, error: string}>} halves
2450
+ * @param {Array} checks appended to
2451
+ * @returns {number} 0 -- a WARN contributes no issue count
2452
+ */
2453
+ function reportUnreadablePath(halves, checks) {
2454
+ const reasons = halves.map((h) => `${h.label}: ${h.error}`).join('; ');
2455
+ checks.push({
2456
+ name: 'PATH freshness',
2457
+ status: 'WARN',
2458
+ detail: `Could not read the registry PATH (${reasons}) — staleness unknown. `
2459
+ + 'After installing a tool, open a new terminal before trusting any "not found" verdict.',
2460
+ });
2461
+ return 0;
2462
+ }
2463
+
2464
+ /**
2465
+ * Gate tools that are installed but invisible to THIS terminal.
2466
+ *
2467
+ * A tool visible only under the refreshed (registry) PATH is "installed but
2468
+ * invisible", never "not installed" -- the distinction the whole staleness check
2469
+ * exists for. The hook environment is probed first, because that is where the gate
2470
+ * will look for the tool; the refreshed path is the counterfactual.
2471
+ *
2472
+ * @param {object} registry as returned by readRegistryPath()
2473
+ * @param {string} refreshedPath the registry PATH
2474
+ * @returns {Promise<string[]>} `tool -> resolved path` entries
2475
+ */
2476
+ async function findStaleInvisibleTools(registry, refreshedPath) {
2477
+ const bash = checkBash();
2478
+ const bashPath = bash.ok ? bash.path : null;
2479
+ if (!bashPath) return [];
2480
+
2481
+ const invisible = [];
2482
+ await Promise.all(GATE_CLI_TOOLS.map(async (entry) => {
2483
+ const now = await probeToolInHookEnv(entry.tool, bashPath);
2484
+ if (now) return;
2485
+ const refreshed = await probeToolInHookEnv(entry.tool, bashPath, {
2486
+ ...process.env,
2487
+ PATH: refreshedPath,
2488
+ });
2489
+ if (refreshed) invisible.push(`${entry.tool} → ${refreshed}`);
2490
+ }));
2491
+ return invisible;
2492
+ }
2493
+
2494
+ /**
2495
+ * The stale-PATH warning: what is invisible, and what to do about it.
2496
+ *
2497
+ * The preview is capped at three entries. A machine can have dozens of stale
2498
+ * entries, and a wall of paths is the reason a warning gets skimmed -- the count
2499
+ * carries the scale, the three examples carry the shape.
2500
+ *
2501
+ * @param {{stale: string[], parts: string[], invisible: string[], checks: Array}} p
2502
+ * `checks` and `parts` are mutated
2503
+ */
2504
+
2505
+ /** Three entries convey the pattern; a wall of paths gets skimmed. */
2506
+ const PREVIEW_ITEMS = 3;
2507
+
2508
+ function reportStalePath(p) {
2509
+ const { stale, parts, invisible, checks } = p;
2510
+ const preview = stale.length <= PREVIEW_ITEMS
2511
+ ? stale.join(' ; ')
2512
+ : `${stale.slice(0, PREVIEW_ITEMS).join(' ; ')} ; …+${stale.length - PREVIEW_ITEMS} more`;
2513
+ parts.unshift(`PATH is stale — ${stale.length} registry entr${stale.length === 1 ? 'y' : 'ies'} invisible to this process (${preview})`);
2514
+ checks.push({
2515
+ name: 'PATH freshness',
2516
+ status: 'WARN',
2517
+ detail: parts.join(' — ')
2518
+ + '. A tool installed after this terminal opened needs a NEW terminal — or re-run: xp-gate doctor --refresh-env'
2519
+ + (invisible.length ? ` — installed-but-invisible gate tools: ${invisible.join(', ')}` : ''),
2520
+ });
2521
+ }
2522
+
2213
2523
  async function diagnosePathStaleness(checks, options = {}) {
2214
2524
  if (process.platform !== 'win32') return 0;
2215
2525
  const registry = options.registry || (await readRegistryPath());
@@ -2227,15 +2537,7 @@ async function diagnosePathStaleness(checks, options = {}) {
2227
2537
  let status = 'PASS';
2228
2538
  const parts = [];
2229
2539
  let stale;
2230
- if (usable.length === 0) {
2231
- // Fail closed: no readable hive is not evidence of freshness.
2232
- checks.push({
2233
- name: 'PATH freshness',
2234
- status: 'WARN',
2235
- detail: `Could not read the registry PATH (${halves.map((h) => `${h.label}: ${h.error}`).join('; ')}) — staleness unknown. After installing a tool, open a new terminal before trusting any "not found" verdict.`,
2236
- });
2237
- return 0;
2238
- }
2540
+ if (usable.length === 0) return reportUnreadablePath(halves, checks);
2239
2541
  stale = [
2240
2542
  ...usable.flatMap((h) => findStalePathEntries(process.env.PATH || '', h.entries)),
2241
2543
  ];
@@ -2256,32 +2558,9 @@ async function diagnosePathStaleness(checks, options = {}) {
2256
2558
  // Which gate tools does THIS terminal lose to staleness? A tool visible in
2257
2559
  // the hook env only under the registry PATH is "installed but invisible" —
2258
2560
  // never "not installed".
2259
- const bash = checkBash();
2260
- const bashPath = bash.ok ? bash.path : null;
2261
2561
  const refreshedPath = buildRefreshedPath(process.env.PATH || '', registry);
2262
- const invisible = [];
2263
- if (bashPath) {
2264
- await Promise.all(GATE_CLI_TOOLS.map(async (entry) => {
2265
- const now = await probeToolInHookEnv(entry.tool, bashPath);
2266
- if (now) return;
2267
- const refreshed = await probeToolInHookEnv(entry.tool, bashPath, {
2268
- ...process.env,
2269
- PATH: refreshedPath,
2270
- });
2271
- if (refreshed) invisible.push(`${entry.tool} → ${refreshed}`);
2272
- }));
2273
- }
2274
- const preview = stale.length <= 3
2275
- ? stale.join(' ; ')
2276
- : `${stale.slice(0, 3).join(' ; ')} ; …+${stale.length - 3} more`;
2277
- parts.unshift(`PATH is stale — ${stale.length} registry entr${stale.length === 1 ? 'y' : 'ies'} invisible to this process (${preview})`);
2278
- checks.push({
2279
- name: 'PATH freshness',
2280
- status: 'WARN',
2281
- detail: parts.join(' — ')
2282
- + '. A tool installed after this terminal opened needs a NEW terminal — or re-run: xp-gate doctor --refresh-env'
2283
- + (invisible.length ? ` — installed-but-invisible gate tools: ${invisible.join(', ')}` : ''),
2284
- });
2562
+ const invisible = await findStaleInvisibleTools(registry, refreshedPath);
2563
+ reportStalePath({ stale, parts, invisible, checks });
2285
2564
  return 0;
2286
2565
  }
2287
2566
 
@@ -2300,56 +2579,22 @@ async function diagnosePathStaleness(checks, options = {}) {
2300
2579
  * @returns {Promise<number>} issue count
2301
2580
  */
2302
2581
  async function diagnoseCliToolsAsync(checks, options = {}) {
2582
+ // DELEGATED (2026-11-23): this used to probe each tool itself, in parallel,
2583
+ // with an exit-code-only verdict. That made doctor disagree with check-tools
2584
+ // in three ways: an empty-output probe read as "available"
2585
+ // (psscriptanalyzer), duplicate installs were invisible (two identical
2586
+ // hadolint binaries), and versions were printed but never compared.
2587
+ // The rule now lives once, in tool-audit; this function only adapts its rows
2588
+ // to doctor's report contract.
2589
+ const rows = options.rows || (await auditGateCliTools(options));
2590
+ const mapped = mapAuditRowsToDoctorChecks(rows);
2303
2591
  let issues = 0;
2304
- const platform = process.platform;
2305
- const isWindows = platform === 'win32';
2306
-
2307
- const bash = checkBash();
2308
- const bashPath = bash.ok ? bash.path : null;
2309
-
2310
- let probeEnv;
2311
- if (options.refreshEnv && isWindows) {
2312
- const registry = await readRegistryPath();
2313
- if (!registry.error) {
2314
- probeEnv = { ...process.env, PATH: buildRefreshedPath(process.env.PATH || '', registry) };
2315
- }
2592
+ for (const check of mapped) {
2593
+ checks.push(check);
2594
+ if (check.status === 'WARN') issues += 1;
2316
2595
  }
2317
-
2318
- // Build parallel checks for each tool
2319
- const toolChecks = GATE_CLI_TOOLS.map(async (entry) => {
2320
- const toolName = entry.tool;
2321
- const result = await detectCliToolAsync(toolName, isWindows, { bashPath, env: probeEnv });
2322
- return { entry, toolName, result };
2323
- });
2324
-
2325
- // Run ALL tool checks in parallel
2326
- const results = await Promise.allSettled(toolChecks);
2327
-
2328
- // Collect results (maintain original order)
2329
- for (const settled of results) {
2330
- if (settled.status === 'rejected') continue;
2331
- const { entry, result } = settled.value;
2332
- const gateLabels = entry.gates.join(', ');
2333
-
2334
- if (result.available) {
2335
- checks.push({
2336
- name: `CLI tool: ${entry.tool} (${gateLabels})`,
2337
- status: 'PASS',
2338
- detail: result.version || 'available',
2339
- });
2340
- } else {
2341
- const installCmd = getToolInstallCmd(entry, platform);
2342
- checks.push({
2343
- name: `CLI tool: ${entry.tool} (${gateLabels})`,
2344
- status: 'WARN',
2345
- detail: `Not found — install with: ${installCmd}`,
2346
- });
2347
- issues++;
2348
- }
2349
- }
2350
-
2351
- return issues;
2352
- }
2596
+ return issues;
2597
+ }
2353
2598
 
2354
2599
  /**
2355
2600
  * Async CLI tool detection — mirrors checkCliTool but uses async exec
@@ -2371,49 +2616,116 @@ async function detectCliToolAsync(toolName, isWindows, options = {}) {
2371
2616
  const bashPath = options.bashPath || null;
2372
2617
  const env = options.env || undefined;
2373
2618
 
2374
- if (bashPath) {
2375
- const hookEnvPath = await probeToolInHookEnv(toolName, bashPath, env);
2376
- if (hookEnvPath) {
2377
- const version = await getVersionAsync(hookEnvPath, isWindows, { bashPath, env });
2378
- return { available: true, path: hookEnvPath, version };
2379
- }
2380
- return { available: false };
2619
+ // Inside the hook environment there is exactly ONE answer: the path the gate would
2620
+ // resolve. Falling through to a host probe would report a tool the hook cannot see.
2621
+ if (bashPath) return probeInHookEnv(toolName, isWindows, bashPath, env);
2622
+
2623
+ // The steps are a LIST, tried in order: each returns null when it finds nothing.
2624
+ // Written as `||` chaining it was three branches to say "first one wins".
2625
+ const steps = [
2626
+ () => probeViaLocator(toolName, isWindows, env),
2627
+ () => probeViaDirectExec(toolName, isWindows, env),
2628
+ () => probeViaLocalPaths(toolName, isWindows),
2629
+ ];
2630
+ return unwrapProbeHit(await firstProbeHit(steps));
2631
+ }
2632
+
2633
+ /**
2634
+ * Run each probe until one reports a hit.
2635
+ *
2636
+ * @param {Array<() => Promise<object|null>>} steps
2637
+ * @returns {Promise<object|null>} the first non-null result, or null
2638
+ */
2639
+ /**
2640
+ * Normalise a probe result so the caller always gets an object.
2641
+ *
2642
+ * @param {object|null} hit
2643
+ * @returns {{available: boolean}}
2644
+ */
2645
+ function unwrapProbeHit(hit) {
2646
+ return hit || { available: false };
2647
+ }
2648
+
2649
+ async function firstProbeHit(steps) {
2650
+ for (const step of steps) {
2651
+ const hit = await step();
2652
+ if (hit) return hit;
2381
2653
  }
2654
+ return null;
2655
+ }
2656
+
2657
+ /**
2658
+ * Probe where the gate would look, and stop there either way.
2659
+ *
2660
+ * @param {string} toolName
2661
+ * @param {boolean} isWindows
2662
+ * @param {string} bashPath
2663
+ * @param {object|undefined} env
2664
+ * @returns {Promise<{available: boolean, path?: string, version?: string}>}
2665
+ */
2666
+ async function probeInHookEnv(toolName, isWindows, bashPath, env) {
2667
+ const hookEnvPath = await probeToolInHookEnv(toolName, bashPath, env);
2668
+ if (!hookEnvPath) return { available: false };
2669
+ const version = await getVersionAsync(hookEnvPath, isWindows, { bashPath, env });
2670
+ return { available: true, path: hookEnvPath, version };
2671
+ }
2382
2672
 
2383
- const shell = isWindows ? 'cmd.exe' : '/bin/sh';
2384
- const execOpts = { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], shell, timeout: EXEC_TIMEOUT_MS, env };
2673
+ /** The exec options every host probe shares: a shell, a hard timeout, piped streams. */
2674
+ function hostExecOptions(isWindows) {
2675
+ return {
2676
+ encoding: 'utf8',
2677
+ stdio: ['pipe', 'pipe', 'pipe'],
2678
+ shell: isWindows ? 'cmd.exe' : '/bin/sh',
2679
+ timeout: EXEC_TIMEOUT_MS,
2680
+ };
2681
+ }
2385
2682
 
2386
- // Step 1: Locate tool via which/where (async, 3s timeout)
2683
+ /**
2684
+ * Step 1: `which` / `where`.
2685
+ *
2686
+ * @returns {Promise<{available: boolean, path?: string, version?: string}|null>} null
2687
+ * when the locator found nothing, so the caller can try the next step.
2688
+ */
2689
+ async function probeViaLocator(toolName, isWindows, env) {
2387
2690
  const locator = isWindows ? 'where' : 'which';
2388
- const locatorResult = await execWithTimeout(`${locator} ${toolName}`, execOpts);
2389
- if (locatorResult && locatorResult.stdout) {
2390
- const resolvedPath = locatorResult.stdout.split('\n')[0].trim();
2391
- if (resolvedPath) {
2392
- const version = await getVersionAsync(resolvedPath, isWindows);
2393
- return { available: true, path: resolvedPath, version };
2394
- }
2395
- }
2691
+ const result = await execWithTimeout(`${locator} ${toolName}`, { ...hostExecOptions(isWindows), env });
2692
+ const resolvedPath = result && result.stdout ? result.stdout.split('\n')[0].trim() : '';
2693
+ if (!resolvedPath) return null;
2694
+ return { available: true, path: resolvedPath, version: await getVersionAsync(resolvedPath, isWindows) };
2695
+ }
2396
2696
 
2397
- // Step 2: Direct exec fallback (async, 3s timeout)
2398
- const fallbackCmd = isWindows
2697
+ /**
2698
+ * Step 2: run the tool directly.
2699
+ *
2700
+ * The POSIX form tries `--version` then `-v`, because tools disagree about which one
2701
+ * they answer and a silent failure here means "not installed" to the caller.
2702
+ *
2703
+ * @returns {Promise<{available: boolean, path?: string, version?: string}|null>}
2704
+ */
2705
+ async function probeViaDirectExec(toolName, isWindows, env) {
2706
+ const command = isWindows
2399
2707
  ? `${toolName} --version`
2400
2708
  : `${toolName} --version 2>/dev/null || ${toolName} -v 2>/dev/null`;
2401
- const fallbackResult = await execWithTimeout(fallbackCmd, execOpts);
2402
- if (fallbackResult && fallbackResult.stdout) {
2403
- return { available: true, path: toolName, version: fallbackResult.stdout.split('\n')[0] };
2404
- }
2709
+ const result = await execWithTimeout(command, { ...hostExecOptions(isWindows), env });
2710
+ if (!result || !result.stdout) return null;
2711
+ return { available: true, path: toolName, version: result.stdout.split('\n')[0] };
2712
+ }
2405
2713
 
2406
- // Step 3: Check local fallback paths (sync fs, no exec)
2407
- const localPaths = getLocalFallbackPathsSync(toolName, isWindows);
2408
- for (const localPath of localPaths) {
2714
+ /**
2715
+ * Step 3: the well-known install directories, with no exec at all.
2716
+ *
2717
+ * Last because it is the most expensive to be wrong about: a stale path here reports
2718
+ * a tool as present that no shell would actually find.
2719
+ *
2720
+ * @returns {Promise<{available: boolean, path?: string, version?: string}|null>}
2721
+ */
2722
+ async function probeViaLocalPaths(toolName, isWindows) {
2723
+ for (const localPath of getLocalFallbackPathsSync(toolName, isWindows)) {
2409
2724
  if (!fs.existsSync(localPath)) continue;
2410
2725
  const version = await getVersionAsync(localPath, isWindows);
2411
- if (version) {
2412
- return { available: true, path: localPath, version };
2413
- }
2726
+ if (version) return { available: true, path: localPath, version };
2414
2727
  }
2415
-
2416
- return { available: false };
2728
+ return null;
2417
2729
  }
2418
2730
 
2419
2731
  /**
@@ -2448,30 +2760,38 @@ async function getVersionAsync(execPath, isWindows, options = {}) {
2448
2760
  * Get local fallback paths for CLI tool (sync, no exec).
2449
2761
  * Mirrors getLocalFallbackPaths from detect-deps.js.
2450
2762
  */
2763
+ /**
2764
+ * `<Python install>/Scripts/<tool>.exe` for every Python under LOCALAPPDATA.
2765
+ *
2766
+ * Windows installs put console scripts there rather than on PATH, which is why a tool
2767
+ * that IS installed can still look missing. A Python tree that cannot be listed
2768
+ * contributes nothing -- this is a fallback list, not a diagnostic.
2769
+ */
2770
+ function windowsPythonScripts(toolName, home) {
2771
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
2772
+ const pythonBase = path.join(localAppData, 'Programs', 'Python');
2773
+ try {
2774
+ return fs.readdirSync(pythonBase)
2775
+ .filter((entry) => entry.startsWith('Python'))
2776
+ .map((entry) => path.join(pythonBase, entry, 'Scripts', `${toolName}.exe`));
2777
+ } catch {
2778
+ return [];
2779
+ }
2780
+ }
2781
+
2451
2782
  function getLocalFallbackPathsSync(toolName, isWindows) {
2452
2783
  const os = require('os');
2453
2784
  const home = os.homedir();
2454
2785
  const paths = [path.join(home, '.local', 'bin', toolName)];
2455
2786
 
2456
- if (isWindows) {
2457
- const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
2458
- const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
2459
- paths.push(
2460
- path.join(appData, 'npm', `${toolName}.cmd`),
2461
- path.join(home, '.local', 'bin', `${toolName}.exe`),
2462
- );
2463
- const pythonBase = path.join(localAppData, 'Programs', 'Python');
2464
- if (fs.existsSync(pythonBase)) {
2465
- try {
2466
- for (const entry of fs.readdirSync(pythonBase)) {
2467
- if (entry.startsWith('Python')) {
2468
- paths.push(path.join(pythonBase, entry, 'Scripts', `${toolName}.exe`));
2469
- }
2470
- }
2471
- } catch { /* skip */ }
2472
- }
2473
- }
2787
+ if (!isWindows) return paths;
2474
2788
 
2789
+ const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
2790
+ paths.push(
2791
+ path.join(appData, 'npm', `${toolName}.cmd`),
2792
+ path.join(home, '.local', 'bin', `${toolName}.exe`),
2793
+ ...windowsPythonScripts(toolName, home),
2794
+ );
2475
2795
  return paths;
2476
2796
  }
2477
2797
 
@@ -2520,12 +2840,15 @@ function diagnoseTemplateDir(config, checks) {
2520
2840
  * @param {Array} checks
2521
2841
  * @returns {number} issue count
2522
2842
  */
2523
- function diagnoseCliTools(checks) {
2843
+ function diagnoseCliTools(checks, options = {}) {
2524
2844
  let issues = 0;
2525
2845
  const platform = process.platform;
2846
+ // Injectable probe: the real one shells out to every gate tool, which is why
2847
+ // this loop was only ever reached by a full doctor run.
2848
+ const probe = options.check || checkCliTool;
2526
2849
 
2527
2850
  for (const entry of GATE_CLI_TOOLS) {
2528
- const { available, version } = checkCliTool(entry.tool);
2851
+ const { available, version } = probe(entry.tool);
2529
2852
  const gateLabels = entry.gates.join(', ');
2530
2853
 
2531
2854
  if (available) {
@@ -2568,12 +2891,22 @@ function printReport(checks) {
2568
2891
  /**
2569
2892
  * Copy a hook file from package source to target, creating parent dir if needed.
2570
2893
  */
2894
+ /**
2895
+ * Copy a hook from the package into place and make it executable.
2896
+ *
2897
+ * The chmod is part of the repair, not a detail: a hook without the execute bit
2898
+ * is one git silently ignores, which looks exactly like "the fix did nothing".
2899
+ */
2571
2900
  function restoreHook(srcFile, destFile, label) {
2572
2901
  if (!fs.existsSync(srcFile)) return false;
2573
- const destDir = path.dirname(destFile);
2574
- fs.mkdirSync(destDir, { recursive: true });
2575
- fs.copyFileSync(srcFile, destFile);
2576
- fs.chmodSync(destFile, 0o755);
2902
+ try {
2903
+ const destDir = path.dirname(destFile);
2904
+ fs.mkdirSync(destDir, { recursive: true });
2905
+ fs.copyFileSync(srcFile, destFile);
2906
+ fs.chmodSync(destFile, 0o755);
2907
+ } catch (err) {
2908
+ throw new Error(`cannot restore ${label} to ${destFile}: ${err.message}`);
2909
+ }
2577
2910
  console.log(` ✓ Restored ${label}`);
2578
2911
  return true;
2579
2912
  }
@@ -2660,19 +2993,38 @@ function fixCoreHooksPath(globalHooksDir) {
2660
2993
  * @returns {boolean} Whether adapters were restored
2661
2994
  */
2662
2995
  function fixMissingAdapters(mode, srcDir, adaptersDir) {
2663
- if (adaptersDir && (!fs.existsSync(adaptersDir) || fs.readdirSync(adaptersDir).filter(f => f.endsWith('.sh')).length === 0)) {
2664
- const pkgAdaptersDir = path.join(srcDir, 'adapters');
2665
- if (fs.existsSync(pkgAdaptersDir)) {
2666
- fs.mkdirSync(adaptersDir, { recursive: true });
2667
- const adapterFiles = fs.readdirSync(pkgAdaptersDir).filter(f => f.endsWith('.sh'));
2668
- for (const f of adapterFiles) {
2669
- fs.copyFileSync(path.join(pkgAdaptersDir, f), path.join(adaptersDir, f));
2670
- }
2671
- console.log(` ✓ Restored ${adapterFiles.length} adapter(s)`);
2672
- return true;
2996
+ if (!adaptersDir || !needsAdapterRepair(adaptersDir)) return false;
2997
+ const pkgAdaptersDir = path.join(srcDir, 'adapters');
2998
+ if (!fs.existsSync(pkgAdaptersDir)) return false;
2999
+ try {
3000
+ fs.mkdirSync(adaptersDir, { recursive: true });
3001
+ const adapterFiles = fs.readdirSync(pkgAdaptersDir).filter(f => f.endsWith('.sh'));
3002
+ for (const f of adapterFiles) {
3003
+ fs.copyFileSync(path.join(pkgAdaptersDir, f), path.join(adaptersDir, f));
2673
3004
  }
3005
+ console.log(` ✓ Restored ${adapterFiles.length} adapter(s)`);
3006
+ return true;
3007
+ } catch (err) {
3008
+ // A partial restore leaves a half-installed adapter set; naming the failure is
3009
+ // what stops the caller reporting a repair that did not finish.
3010
+ console.log(` ✗ Could not restore adapters to ${adaptersDir}: ${err.message}`);
3011
+ return false;
3012
+ }
3013
+ }
3014
+
3015
+ /**
3016
+ * Whether the adapters directory is missing or holds no `.sh` files.
3017
+ *
3018
+ * An unreadable directory counts as needing repair: the copy would fail anyway, and
3019
+ * reporting it as "already fine" would skip the only code that can say why.
3020
+ */
3021
+ function needsAdapterRepair(adaptersDir) {
3022
+ if (!fs.existsSync(adaptersDir)) return true;
3023
+ try {
3024
+ return fs.readdirSync(adaptersDir).filter((f) => f.endsWith('.sh')).length === 0;
3025
+ } catch {
3026
+ return true;
2674
3027
  }
2675
- return false;
2676
3028
  }
2677
3029
 
2678
3030
  /**
@@ -2683,7 +3035,14 @@ function fixMissingAdapters(mode, srcDir, adaptersDir) {
2683
3035
  function fixMissingGateScripts(srcDir, adaptersDir) {
2684
3036
  if (!adaptersDir || !fs.existsSync(adaptersDir)) return false;
2685
3037
 
2686
- const existingFiles = fs.readdirSync(adaptersDir);
3038
+ let existingFiles;
3039
+ try {
3040
+ existingFiles = fs.readdirSync(adaptersDir);
3041
+ } catch (err) {
3042
+ // Unreadable is not empty: "no gate scripts missing" would skip the only repair.
3043
+ console.log(` ✗ Could not read ${adaptersDir}: ${err.message}`);
3044
+ return false;
3045
+ }
2687
3046
  const missingGates = EXPECTED_GATE_SCRIPTS.filter(g => !existingFiles.includes(g));
2688
3047
 
2689
3048
  if (missingGates.length === 0) return false;
@@ -2692,10 +3051,14 @@ function fixMissingGateScripts(srcDir, adaptersDir) {
2692
3051
  for (const gateScript of missingGates) {
2693
3052
  const srcFile = path.join(srcDir, gateScript);
2694
3053
  const destFile = path.join(adaptersDir, gateScript);
2695
- if (fs.existsSync(srcFile)) {
3054
+ if (!fs.existsSync(srcFile)) continue;
3055
+ try {
2696
3056
  fs.copyFileSync(srcFile, destFile);
2697
3057
  fs.chmodSync(destFile, 0o755);
2698
3058
  restored++;
3059
+ } catch (err) {
3060
+ // One unwritable gate script must not strand the others.
3061
+ console.log(` ✗ Could not restore ${gateScript}: ${err.message}`);
2699
3062
  }
2700
3063
  }
2701
3064
 
@@ -2811,23 +3174,92 @@ function fixHookDriftFromRepo() {
2811
3174
  *
2812
3175
  * @returns {boolean} Whether any hooks were updated
2813
3176
  */
3177
+ /**
3178
+ * Where the hooks and adapters live for this install mode.
3179
+ *
3180
+ * Global mode uses one machine-wide pair. Local mode derives both from the git
3181
+ * directory, and a project with no resolvable git dir cannot be repaired -- there is
3182
+ * nowhere to write, so the caller reports "nothing fixed" rather than guessing a
3183
+ * path.
3184
+ *
3185
+ * @param {boolean} isGlobal
3186
+ * @returns {{hooksDestDir: string, adaptersDestDir: string}|null}
3187
+ */
3188
+ function resolveHookDestinations(isGlobal) {
3189
+ if (isGlobal) {
3190
+ return { hooksDestDir: GLOBAL_HOOKS_DIR(), adaptersDestDir: GLOBAL_ADAPTERS_DIR() };
3191
+ }
3192
+ const gitDir = getGitDirSync();
3193
+ if (!gitDir) return null;
3194
+ const projectRoot = path.dirname(gitDir);
3195
+ return {
3196
+ hooksDestDir: path.join(gitDir, 'hooks'),
3197
+ adaptersDestDir: path.join(projectRoot, 'githooks'),
3198
+ };
3199
+ }
3200
+
3201
+ /**
3202
+ * Print what the sync refused to touch, and why it refused.
3203
+ *
3204
+ * The warning ends by saying there is NO rollback. That is not decoration: the
3205
+ * refusal exists because the installed copy may hold work that exists nowhere else,
3206
+ * so the operator has to judge against a copy they kept -- telling them to "undo" a
3207
+ * write that never happened would be worse than saying nothing.
3208
+ *
3209
+ * @param {{diverged: Array, unknown: Array}} plan
3210
+ */
3211
+ function reportBlockedHookSync(plan) {
3212
+ if (!plan.hasBlocking) return;
3213
+ console.log(` ⚠️ ${plan.diverged.length + plan.unknown.length} hook/adapter file(s) NOT refreshed —`);
3214
+ console.log(' the installed copy carries content the package does not, and overwriting');
3215
+ console.log(' it would delete work that exists nowhere else:');
3216
+ for (const d of plan.diverged) {
3217
+ console.log(` - ${d.name}: install has ${d.installedOnly} unique line(s), package has ${d.repoOnly}`);
3218
+ }
3219
+ for (const u of plan.unknown) {
3220
+ console.log(` - ${u.name}: installed copy could not be read`);
3221
+ }
3222
+ console.log(' Judge them (fold the hardening into the package, or move the file aside),');
3223
+ console.log(' then re-run --fix.');
3224
+ console.log(' There is no automatic backup of an overwritten hook/adapter file and nothing');
3225
+ console.log(' in this tool can undo one — judge against a copy you kept, not against a rollback.');
3226
+ }
3227
+
3228
+ /**
3229
+ * Copy the files the plan judged safe, one at a time.
3230
+ *
3231
+ * A failure on one file is printed and the rest continue: a single unwritable
3232
+ * target must not strand the other outdated hooks.
3233
+ *
3234
+ * @param {Array<{name: string, source: string, target: string}>} safe
3235
+ * @returns {boolean} whether anything was refreshed
3236
+ */
3237
+ function refreshSafeHooks(safe) {
3238
+ console.log(` Refreshing ${safe.length} outdated hook/adapter file(s)...`);
3239
+ let refreshed = 0;
3240
+ for (const entry of safe) {
3241
+ if (!fs.existsSync(entry.source)) continue;
3242
+ try {
3243
+ fs.mkdirSync(path.dirname(entry.target), { recursive: true });
3244
+ fs.copyFileSync(entry.source, entry.target);
3245
+ fs.chmodSync(entry.target, 0o755);
3246
+ refreshed++;
3247
+ } catch (err) {
3248
+ console.log(` ✗ Could not refresh ${entry.name}: ${err.message}`);
3249
+ }
3250
+ }
3251
+ return refreshed > 0;
3252
+ }
3253
+
2814
3254
  function fixStaleHooks(config) {
2815
3255
  try {
2816
3256
  const { detectLocalModifications, getPackageRoot } = require('./update-hooks.js');
2817
3257
  const isGlobal = config.mode === 'global';
2818
3258
  const srcDir = getPackageRoot();
2819
3259
 
2820
- let hooksDestDir, adaptersDestDir;
2821
- if (isGlobal) {
2822
- hooksDestDir = GLOBAL_HOOKS_DIR();
2823
- adaptersDestDir = GLOBAL_ADAPTERS_DIR();
2824
- } else {
2825
- const gitDir = getGitDirSync();
2826
- if (!gitDir) return false;
2827
- const projectRoot = path.dirname(gitDir);
2828
- hooksDestDir = path.join(gitDir, 'hooks');
2829
- adaptersDestDir = path.join(projectRoot, 'githooks');
2830
- }
3260
+ const dest = resolveHookDestinations(isGlobal);
3261
+ if (!dest) return false;
3262
+ const { hooksDestDir, adaptersDestDir } = dest;
2831
3263
 
2832
3264
  // Check if any hook files are stale (differ from package version)
2833
3265
  const modified = detectLocalModifications(srcDir, hooksDestDir, adaptersDestDir);
@@ -2844,38 +3276,9 @@ function fixStaleHooks(config) {
2844
3276
  modified.flatMap((label) => staleSyncEntries(label, srcDir, hooksDestDir, adaptersDestDir)),
2845
3277
  );
2846
3278
 
2847
- if (plan.hasBlocking) {
2848
- console.log(` ⚠️ ${plan.diverged.length + plan.unknown.length} hook/adapter file(s) NOT refreshed —`);
2849
- console.log(' the installed copy carries content the package does not, and overwriting');
2850
- console.log(' it would delete work that exists nowhere else:');
2851
- for (const d of plan.diverged) {
2852
- console.log(` - ${d.name}: install has ${d.installedOnly} unique line(s), package has ${d.repoOnly}`);
2853
- }
2854
- for (const u of plan.unknown) {
2855
- console.log(` - ${u.name}: installed copy could not be read`);
2856
- }
2857
- console.log(' Judge them (fold the hardening into the package, or move the file aside),');
2858
- console.log(' then re-run --fix.');
2859
- console.log(' There is no automatic backup of an overwritten hook/adapter file and nothing');
2860
- console.log(' in this tool can undo one — judge against a copy you kept, not against a rollback.');
2861
- }
2862
-
3279
+ reportBlockedHookSync(plan);
2863
3280
  if (plan.safe.length === 0) return plan.hasBlocking;
2864
-
2865
- console.log(` Refreshing ${plan.safe.length} outdated hook/adapter file(s)...`);
2866
- let refreshed = 0;
2867
- for (const entry of plan.safe) {
2868
- if (!fs.existsSync(entry.source)) continue;
2869
- try {
2870
- fs.mkdirSync(path.dirname(entry.target), { recursive: true });
2871
- fs.copyFileSync(entry.source, entry.target);
2872
- fs.chmodSync(entry.target, 0o755);
2873
- refreshed++;
2874
- } catch (err) {
2875
- console.log(` ✗ Could not refresh ${entry.name}: ${err.message}`);
2876
- }
2877
- }
2878
- return refreshed > 0;
3281
+ return refreshSafeHooks(plan.safe);
2879
3282
  } catch {
2880
3283
  return false;
2881
3284
  }
@@ -3024,12 +3427,22 @@ function diagnoseOpenCodePlugin(checks) {
3024
3427
 
3025
3428
  /**
3026
3429
  * Diagnose language-specific tool availability.
3430
+ *
3431
+ * Takes its inputs as options so the loop below is reachable from a test: it used
3432
+ * to read `process.cwd()` and call the real detection + probing chain directly,
3433
+ * which made 34 lines of output logic untestable except by running a whole
3434
+ * `doctor` against a real project (and vitest workers cannot chdir).
3435
+ *
3436
+ * @param {{detect?: Function, getTools?: Function, registry?: object, projectRoot?: string}} [options]
3027
3437
  * @returns {number} Number of issues found (missing required tools)
3028
3438
  */
3029
- function diagnoseLanguageTools() {
3439
+ function diagnoseLanguageTools(options = {}) {
3030
3440
  try {
3031
- const { detectProjectLanguages, getToolsForLanguages, LANGUAGE_REGISTRY } = require('./language-tools.js');
3032
- const projectRoot = process.cwd();
3441
+ const lt = require('./language-tools.js');
3442
+ const detectProjectLanguages = options.detect || lt.detectProjectLanguages;
3443
+ const getToolsForLanguages = options.getTools || lt.getToolsForLanguages;
3444
+ const LANGUAGE_REGISTRY = options.registry || lt.LANGUAGE_REGISTRY;
3445
+ const projectRoot = options.projectRoot || process.cwd();
3033
3446
  const { detected } = detectProjectLanguages(projectRoot);
3034
3447
 
3035
3448
  if (detected.length === 0) return 0;
@@ -3085,177 +3498,400 @@ const KNOWN_FLAGS = ['--fix', '--sync-hooks', '--force', '--install-tools', '--j
3085
3498
  *
3086
3499
  * @returns {{errors: string[], fixMode: boolean, syncHooks: boolean, force: boolean, installToolsFlag: boolean, jsonMode: boolean}}
3087
3500
  */
3501
+ /**
3502
+ * Reject flag combinations that would silently do nothing, or do the wrong thing.
3503
+ *
3504
+ * Each rule here exists because the combination was accepted and misled someone.
3505
+ * The recurring shape is a flag that only one code path reads: passing it alone was
3506
+ * accepted, printed nothing, and changed nothing (#488 Round 4 found this for
3507
+ * `--force`), which is indistinguishable from a repair that ran and found nothing
3508
+ * to do.
3509
+ *
3510
+ * @param {{fixMode: boolean, syncHooks: boolean, force: boolean,
3511
+ * installToolsFlag: boolean, jsonMode: boolean, briefFlag: boolean}} f
3512
+ * @param {{formatGiven: boolean, formatValue: string|null}} format
3513
+ * @returns {string[]}
3514
+ */
3515
+ /** `--format` accepts exactly these; anything else is a typo, not a mode. */
3516
+ const FORMAT_VALUES = ['json', 'text'];
3517
+
3518
+ /**
3519
+ * Reject flag combinations that would silently do nothing, or do the wrong thing.
3520
+ *
3521
+ * Each rule exists because the combination was accepted and misled someone. The
3522
+ * recurring shape is a flag that only ONE code path reads: passing it alone was
3523
+ * accepted, printed nothing, and changed nothing (#488 Round 4 found this for
3524
+ * `--force`), which is indistinguishable from a repair that ran and found nothing
3525
+ * to do.
3526
+ *
3527
+ * The rules are DATA -- `{ when, messages }` -- rather than an `if` ladder. Each rule
3528
+ * is a sentence about a combination; the ladder made that five branches inside one
3529
+ * function and buried the sentences in control flow.
3530
+ *
3531
+ * @param {object} f parsed flags
3532
+ * @param {{formatGiven: boolean, formatValue: string|null}} format
3533
+ * @returns {string[]}
3534
+ */
3535
+ /** A JSON report is a read; the repair surface writes. They cannot share a run. */
3536
+ function isReadMixedWithRepair(f) {
3537
+ return f.jsonMode && (f.fixMode || f.syncHooks);
3538
+ }
3539
+
3540
+ /** `--force` is read only by `--sync-hooks`, so alone it changes nothing. */
3541
+ function isOrphanedForce(f) {
3542
+ return f.force && !f.syncHooks;
3543
+ }
3544
+
3545
+ /** `--install-tools` is read only by `--fix`. */
3546
+ function isOrphanedInstallTools(f) {
3547
+ return f.installToolsFlag && !f.fixMode;
3548
+ }
3549
+
3550
+ /** `--brief` is a read-only fact dump and cannot carry a write flag. */
3551
+ function isBriefWithWrite(f) {
3552
+ return f.briefFlag && (f.fixMode || f.syncHooks || f.installToolsFlag || f.force);
3553
+ }
3554
+
3555
+ function validateFlagCombinations(f, format) {
3556
+ const formatProblem = format.formatGiven && !FORMAT_VALUES.includes(format.formatValue)
3557
+ ? [`Unknown --format value: ${format.formatValue || '(none)'} — expected ${FORMAT_VALUES.join(' or ')}`]
3558
+ : [];
3559
+
3560
+ const rules = [
3561
+ {
3562
+ // A JSON report is a read; mixing it with the repair surface would put progress
3563
+ // prose into the stream a script is parsing.
3564
+ when: isReadMixedWithRepair(f),
3565
+ messages: ['--json/--format json cannot be combined with --fix or --sync-hooks'],
3566
+ },
3567
+ {
3568
+ when: isOrphanedForce(f),
3569
+ messages: [
3570
+ '--force is only read by --sync-hooks, where it overrides the divergence refusal and overwrites without a backup',
3571
+ 'Pass --sync-hooks --force, or drop --force',
3572
+ ],
3573
+ },
3574
+ {
3575
+ when: isOrphanedInstallTools(f),
3576
+ messages: [
3577
+ '--install-tools is only read by --fix, and it is the only flag that installs toolchains onto this machine',
3578
+ 'Pass --fix --install-tools, or drop --install-tools',
3579
+ ],
3580
+ },
3581
+ {
3582
+ // #653: --brief collapses exploratory probes into one cheap read. Users call it
3583
+ // often BECAUSE it is cheap, so a write smuggled in would compound state changes
3584
+ // instead of only latency.
3585
+ when: isBriefWithWrite(f),
3586
+ messages: ['--brief is a read-only fact dump and cannot be combined with --fix, --sync-hooks, --install-tools or --force'],
3587
+ },
3588
+ ];
3589
+
3590
+ return [...formatProblem, ...rules.filter((r) => r.when).flatMap((r) => r.messages)];
3591
+ }
3592
+
3088
3593
  function doctorFlagContract(args) {
3089
3594
  const errors = [];
3090
- // `--format json` carries a value; without this the value itself would be
3091
- // reported as an unknown flag and the documented machine-readable mode could
3092
- // never be reached (#304 promised it, nothing ever implemented it).
3093
- const formatValue = args[args.indexOf('--format') + 1] || null;
3094
- const flagTokens = args.filter((a, i) => !(i > 0 && args[i - 1] === '--format'));
3095
- const unknownFlags = flagTokens.filter(a => !KNOWN_FLAGS.includes(a));
3096
- if (unknownFlags.length > 0) {
3097
- errors.push(`Unknown flag(s) for doctor: ${unknownFlags.join(', ')}`);
3098
- errors.push(`Supported flags: ${KNOWN_FLAGS.join(', ')}`);
3099
- }
3100
- const fixMode = args.includes('--fix');
3101
- const syncHooks = args.includes('--sync-hooks');
3102
- // #495: overwriting a module whose installed copy holds lines the repo lacks
3103
- // destroys machine-only hardening, so it needs this explicit opt-in.
3104
- const force = args.includes('--force');
3105
- // Installing a toolchain changes the machine, not the repository, so it is
3106
- // never a side effect of --fix (#502). --fix reports the missing tools.
3107
- const installToolsFlag = args.includes('--install-tools');
3108
- // #469: re-probe CLI tools against the registry PATH (what a freshly opened
3109
- // terminal would see) instead of this process's possibly-stale snapshot.
3110
- // Read-only: it changes the probe environment, never the machine.
3111
- const refreshEnv = args.includes('--refresh-env');
3112
- const jsonMode = args.includes('--json') || (args.includes('--format') && formatValue === 'json');
3113
- if (args.includes('--format') && !['json', 'text'].includes(formatValue)) {
3114
- errors.push(`Unknown --format value: ${formatValue || '(none)'} — expected json or text`);
3115
- }
3116
- if (jsonMode && (fixMode || syncHooks)) {
3117
- // A JSON report is a read; mixing it with the repair surface would put
3118
- // progress prose into the stream a script is parsing.
3119
- errors.push('--json/--format json cannot be combined with --fix or --sync-hooks');
3120
- }
3121
- // Round 4 (feasibility) caught the original #488 defect in a new place:
3122
- // `--force` is read only by the sync path, so `doctor --force` and
3123
- // `doctor --fix --force` were accepted, printed nothing and changed nothing.
3124
- if (force && !syncHooks) {
3125
- errors.push('--force is only read by --sync-hooks, where it overrides the divergence refusal and overwrites without a backup');
3126
- errors.push('Pass --sync-hooks --force, or drop --force');
3127
- }
3128
- // Same class: --install-tools installs only inside the --fix repair surface.
3129
- if (installToolsFlag && !fixMode) {
3130
- errors.push('--install-tools is only read by --fix, and it is the only flag that installs toolchains onto this machine');
3131
- errors.push('Pass --fix --install-tools, or drop --install-tools');
3132
- }
3133
- // #653: --brief exists to collapse a class of exploratory probes (`where gcc`,
3134
- // Test-Path, per-file reads) into one cheap read. It is read-only by contract:
3135
- // users call it often precisely because it is cheap, so a write smuggled in
3136
- // would compound state changes instead of only latency.
3137
- const briefFlag = args.includes('--brief');
3138
- if (briefFlag && (fixMode || syncHooks || installToolsFlag || force)) {
3139
- errors.push('--brief is a read-only fact dump and cannot be combined with --fix, --sync-hooks, --install-tools or --force');
3140
- }
3141
- return { errors, fixMode, syncHooks, force, installToolsFlag, jsonMode, refreshEnv, briefFlag };
3595
+ // One pass over argv, not eight `args.includes` calls. Each `includes` is a branch
3596
+ // to the complexity metric, and eight of them put this function at CCN 6 for no
3597
+ // reason: the flags are a SET, and a set is built in one pass.
3598
+ const present = new Set(args);
3599
+
3600
+ // `--format` has THREE states, not two: absent (no opinion), present with a value,
3601
+ // and present with nothing after it (an error -- silently dropping the flag was
3602
+ // #488 AC-09). `indexOf` returns -1 when absent and -1 + 1 is 0, so a run without
3603
+ // `--format` used to read its own first flag as the format value and reject
3604
+ // `doctor --fix` as "unknown --format".
3605
+ const formatIndex = args.indexOf('--format');
3606
+ const formatGiven = formatIndex >= 0;
3607
+ const formatValue = formatGiven ? (args[formatIndex + 1] ?? null) : null;
3608
+
3609
+ errors.push(...unknownFlagErrors(args, formatGiven));
3610
+
3611
+ const flags = {
3612
+ fixMode: present.has('--fix'),
3613
+ syncHooks: present.has('--sync-hooks'),
3614
+ force: present.has('--force'),
3615
+ installToolsFlag: present.has('--install-tools'),
3616
+ refreshEnv: present.has('--refresh-env'),
3617
+ jsonMode: present.has('--json') || (formatGiven && formatValue === 'json'),
3618
+ briefFlag: present.has('--brief'),
3619
+ };
3620
+ errors.push(...validateFlagCombinations(flags, { formatGiven, formatValue }));
3621
+
3622
+ return { errors, ...flags };
3142
3623
  }
3143
3624
 
3144
- async function doctor(args) {
3145
- const { errors, fixMode, syncHooks, force, installToolsFlag, jsonMode, refreshEnv, briefFlag } = doctorFlagContract(args);
3146
- if (briefFlag && errors.length === 0) {
3147
- // Answers the whole "what is this machine set up like" question in one shot.
3148
- const { buildBriefReport } = require('./doctor-brief');
3149
- const report = buildBriefReport({ cwd: process.cwd() });
3150
- if (jsonMode) {
3151
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
3152
- } else {
3153
- process.stdout.write(`${report.summary}\n`);
3154
- }
3155
- process.exitCode = 0;
3156
- return;
3157
- }
3158
- if (errors.length > 0) {
3159
- for (const error of errors) console.error(error);
3625
+ /**
3626
+ * Unknown-flag errors, if any.
3627
+ *
3628
+ * The `--format` VALUE is skipped: without that, `doctor --format json` would report
3629
+ * `json` itself as an unknown flag and the documented machine-readable mode could
3630
+ * never be reached (#304 promised it, nothing ever implemented it).
3631
+ *
3632
+ * @param {string[]} args
3633
+ * @param {boolean} formatGiven
3634
+ * @returns {string[]}
3635
+ */
3636
+ function unknownFlagErrors(args, formatGiven) {
3637
+ const tokens = args.filter((a, i) => !(formatGiven && i > 0 && args[i - 1] === '--format'));
3638
+ const unknown = tokens.filter((a) => !KNOWN_FLAGS.includes(a));
3639
+ if (unknown.length === 0) return [];
3640
+ return [
3641
+ `Unknown flag(s) for doctor: ${unknown.join(', ')}`,
3642
+ `Supported flags: ${KNOWN_FLAGS.join(', ')}`,
3643
+ ];
3644
+ }
3645
+
3646
+ /**
3647
+ * Report one sync result group: what was written, what was refused and why.
3648
+ *
3649
+ * The hook sync and the gate-module sync (#495) produced the same six-branch
3650
+ * printout, including word-for-word the refusal warning. They differ only in
3651
+ * the nouns, so the shape is here once and the callers supply those.
3652
+ *
3653
+ * @param {{synced: string[], skipped?: string[], refused: Array<{name: string, installedOnly: number, repoOnly: number}>, errors: string[], target?: string, syncedLabel?: string, refusedNouns?: string}} result
3654
+ * @returns {number} 1 when errors were reported, 0 otherwise
3655
+ */
3656
+ function reportSyncResult(result) {
3657
+ if (result.errors.length > 0) {
3658
+ for (const err of result.errors) console.log(` ✗ ${err}`);
3160
3659
  return 1;
3161
3660
  }
3162
-
3163
- if (!jsonMode) {
3164
- console.log('XP-Gate Doctor');
3165
- console.log('==============');
3661
+ if (result.synced.length > 0) {
3662
+ console.log(` ✓ Synced ${result.synced.join(', ')} from githooks/ to ${result.target}`);
3663
+ console.log(' The updated hooks take effect on the next commit.');
3664
+ } else if (result.skipped) {
3665
+ console.log(` ✓ Global hooks already match githooks/ (${result.skipped.join(', ') || 'nothing to sync'})`);
3166
3666
  }
3667
+ if (result.refused.length > 0) {
3668
+ console.log('');
3669
+ console.log(` ⚠️ ${result.refused.length} ${result.refusedLabel} NOT synced — the installed copy`);
3670
+ console.log(' carries content githooks/ does not, so overwriting would delete work:');
3671
+ for (const r of result.refused) {
3672
+ console.log(` - ${r.name}: install has ${r.installedOnly} unique line(s), githooks/ has ${r.repoOnly}`);
3673
+ }
3674
+ console.log(' Review them, then either fold the hardening into githooks/ or re-run --sync-hooks --force.');
3675
+ console.log(' Forcing overwrites the installed file, whose previous version is saved under backups/.');
3676
+ }
3677
+ return 0;
3678
+ }
3167
3679
 
3168
- // §4.13 (#451 REQ-3): state which hook files actually execute, so "I edited
3169
- // githooks/ but nothing changed" is answerable without reading git config.
3170
- if (!jsonMode) printEffectiveHooks();
3171
- // #495: the same for the gate modules the hook sources at runtime.
3172
- if (!jsonMode) printEffectiveModules();
3680
+ /**
3681
+ * Sync installed hooks and gate modules from the repo, reporting both.
3682
+ *
3683
+ * @param {boolean} force
3684
+ * @returns {number} 0 on success, 1 when either sync reported errors
3685
+ */
3686
+ function runHookAndModuleSync(force) {
3687
+ const hookSync = syncGlobalHooksFromRepo({ force });
3688
+ const hookCode = reportSyncResult({
3689
+ synced: hookSync.synced,
3690
+ skipped: hookSync.skipped,
3691
+ refused: hookSync.refused,
3692
+ errors: hookSync.errors,
3693
+ target: hookSync.installedHooks,
3694
+ refusedLabel: 'shared library file(s)',
3695
+ });
3696
+ if (hookCode !== 0) return hookCode;
3697
+ if (hookSync.backups.length > 0) {
3698
+ console.log(` Previous version(s) saved under ${path.join(hookSync.installedHooks, 'backups')}/ (${hookSync.backups.length} file(s)).`);
3699
+ }
3700
+
3701
+ // #495: the gate modules are what the hook sources for Gates 3/4/7/8/9/10, so
3702
+ // syncing only the hook files left the executed surface untouched.
3703
+ const moduleSync = syncModulesFromRepo({ force });
3704
+ return reportSyncResult({
3705
+ synced: moduleSync.synced,
3706
+ refused: moduleSync.refused,
3707
+ errors: moduleSync.errors,
3708
+ target: moduleSync.installedAdapters,
3709
+ refusedLabel: 'module(s)',
3710
+ });
3711
+ }
3173
3712
 
3174
- const config = getConfig();
3175
3713
 
3176
- // §4.8: mode === "uninstalled" → print "xp-gate is not installed"
3177
- if (isUninstalledMode(config)) {
3178
- if (jsonMode) {
3179
- console.log(JSON.stringify(formatDoctorJson([{ name: 'Install', status: 'SKIP', detail: 'xp-gate is not installed' }], 0)));
3180
- return 0;
3181
- }
3182
- console.log('xp-gate is not installed.');
3183
- console.log('Run xp-gate init to install.');
3714
+ /**
3715
+ * The `--brief` answer: one cheap read of what this machine looks like.
3716
+ *
3717
+ * #653 designed `--brief` to replace a class of exploratory probes with a single
3718
+ * call, so it must stay cheap -- it loads one module and prints one summary.
3719
+ *
3720
+ * @param {boolean} jsonMode
3721
+ * @returns {Promise<void>} never returns a code; the caller sets the exit code
3722
+ */
3723
+ function runBriefReport(jsonMode) {
3724
+ const { buildBriefReport } = require('./doctor-brief');
3725
+ const report = buildBriefReport({ cwd: process.cwd() });
3726
+ if (jsonMode) {
3727
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
3728
+ } else {
3729
+ process.stdout.write(`${report.summary}\n`);
3730
+ }
3731
+ process.exitCode = 0;
3732
+ }
3733
+
3734
+ /**
3735
+ * Report that xp-gate is not installed, in whichever shape the caller asked for.
3736
+ *
3737
+ * Not an error: an uninstalled machine is a valid state, and `doctor` is the command
3738
+ * that tells you so.
3739
+ *
3740
+ * @param {boolean} jsonMode
3741
+ * @returns {number} exit code (always 0)
3742
+ */
3743
+ function reportUninstalled(jsonMode) {
3744
+ if (jsonMode) {
3745
+ const skip = [{ name: 'Install', status: 'SKIP', detail: 'xp-gate is not installed' }];
3746
+ console.log(JSON.stringify(formatDoctorJson(skip, 0)));
3184
3747
  return 0;
3185
3748
  }
3749
+ console.log('xp-gate is not installed.');
3750
+ console.log('Run xp-gate init to install.');
3751
+ return 0;
3752
+ }
3186
3753
 
3187
- // §4.13 (#451 REQ-2): explicit one-command sync from the repo's githooks/.
3188
- if (syncHooks) {
3189
- const { synced, skipped, refused, errors, installedHooks, backups } = syncGlobalHooksFromRepo({ force });
3190
- if (errors.length > 0) {
3191
- for (const err of errors) console.log(` ✗ ${err}`);
3192
- return 1;
3193
- }
3194
- if (synced.length > 0) {
3195
- console.log(` ✓ Synced ${synced.join(', ')} from githooks/ to ${installedHooks}`);
3196
- console.log(' The updated hooks take effect on the next commit.');
3197
- } else {
3198
- console.log(` ✓ Global hooks already match githooks/ (${skipped.join(', ') || 'nothing to sync'})`);
3199
- }
3200
- // #566: replacing an installed hook discards whatever was in it. Say where
3201
- // the previous version went, so a machine-only fix stays recoverable.
3202
- if (backups.length > 0) {
3203
- console.log(` Previous version(s) saved under ${path.join(installedHooks, 'backups')}/ (${backups.length} file(s)).`);
3204
- }
3205
- if (refused.length > 0) {
3206
- console.log('');
3207
- console.log(` ⚠️ ${refused.length} shared library file(s) NOT synced — the installed copy`);
3208
- console.log(' carries content githooks/ does not, so overwriting would delete work:');
3209
- for (const r of refused) {
3210
- console.log(` - ${r.name}: install has ${r.installedOnly} unique line(s), githooks/ has ${r.repoOnly}`);
3211
- }
3212
- console.log(' Review them, then either fold the hardening into githooks/ or re-run --sync-hooks --force.');
3213
- console.log(' Forcing overwrites the installed file, whose previous version is saved under backups/.');
3214
- }
3754
+ /**
3755
+ * Fill in what a timed-out run could not reach, and check the flaky ledger.
3756
+ *
3757
+ * #495 Round 2: a timeout discards every check that had not reported yet,
3758
+ * INCLUDING the drift surface, so a timed-out result must never read as clean --
3759
+ * that is exactly the "stale modules, doctor green" outcome. The drift checks are
3760
+ * re-run synchronously here and the issue count is floored at 1.
3761
+ *
3762
+ * The flaky-quarantine expiry (#603) is a WARN, not a FAIL: an overdue ledger breaks
3763
+ * nothing at runtime, it only means an intentional gap outlived its intent.
3764
+ *
3765
+ * @param {boolean} timedOut
3766
+ * @param {Array} checks appended to
3767
+ * @param {number} issues current count
3768
+ * @returns {number} the issues this function contributes
3769
+ */
3770
+ function coverIncompleteRun(timedOut, checks, issues) {
3771
+ let added = 0;
3215
3772
 
3216
- // #495: the gate modules are what the hook sources for Gates 3/4/7/8/9/10,
3217
- // so syncing only the hook files left the executed surface untouched.
3218
- const moduleSync = syncModulesFromRepo({ force });
3219
- if (moduleSync.errors.length > 0) {
3220
- for (const err of moduleSync.errors) console.log(` ✗ ${err}`);
3221
- return 1;
3222
- }
3223
- if (moduleSync.synced.length > 0) {
3224
- console.log(` ✓ Synced ${moduleSync.synced.length} gate module(s) to ${moduleSync.installedAdapters}`);
3225
- console.log(` ${moduleSync.synced.join(', ')}`);
3226
- }
3227
- if (moduleSync.refused.length > 0) {
3228
- console.log('');
3229
- console.log(` ⚠️ ${moduleSync.refused.length} module(s) NOT synced — the installed copy carries`);
3230
- console.log(' content the repo does not, so overwriting would delete work (#495):');
3231
- for (const r of moduleSync.refused) {
3232
- console.log(` - ${r.name}: install has ${r.installedOnly} unique line(s), githooks/ has ${r.repoOnly}`);
3233
- }
3234
- console.log(' Review them, then either fold the hardening into githooks/ or re-run --sync-hooks --force.');
3235
- console.log(' Forcing overwrites the installed file, whose previous version is saved under backups/.');
3236
- }
3773
+ if (timedOut) {
3774
+ const hookDrift = diagnoseHookDrift();
3775
+ const moduleDrift = diagnoseModuleDrift();
3776
+ checks.push(...hookDrift.checks, ...moduleDrift.checks);
3777
+ added += hookDrift.issues + moduleDrift.issues;
3237
3778
  }
3238
3779
 
3239
- // §4.13: --fix only when mode === "active"
3240
- if (fixMode && isActiveMode(config)) {
3241
- fixIssues(null, config, installToolsFlag);
3780
+ try {
3781
+ const flaky = diagnoseFlakyQuarantine({ repoRoot: process.cwd() });
3782
+ checks.push(...flaky.checks);
3783
+ added += flaky.issues;
3784
+ } catch (err) {
3785
+ // Surface the cause: a bare "could not be read" hid the real error and made this
3786
+ // look like a missing file rather than a bug in the check itself.
3787
+ const reason = err && err.message ? err.message : String(err);
3788
+ checks.push({ name: 'Flaky quarantine', status: 'SKIP', detail: `ledger check failed: ${reason}` });
3242
3789
  }
3243
3790
 
3244
- // Global timeout wrapper — ensures doctor completes within GLOBAL_DIAGNOSIS_TIMEOUT_MS
3245
- // even if network/subprocess checks stack up (fix #348: 43s on Windows).
3246
- // #629: give diagnoseAsync a live sink so a deadline can keep what finished.
3247
- // Without it, `Promise.race` discarded the entire diagnosis -- so the SAME
3248
- // healthy install reported different results run to run, and a timed-out run
3249
- // lost the skills section entirely (scrapers read 0/12 installed skills).
3791
+ return added;
3792
+ }
3793
+
3794
+ /**
3795
+ * The checks that run after the report: upgrade, plugin and language tools.
3796
+ *
3797
+ * Kept as one function because a `--format json` run still has to execute all of it
3798
+ * (#488) -- the machine-readable mode changes what is PRINTED, not what is checked.
3799
+ * The upgrade probe is raced against a 3 s timeout and its failure is ignored: it
3800
+ * reaches the network, and a doctor that blocks on a slow registry is worse than one
3801
+ * that does not mention an available upgrade.
3802
+ *
3803
+ * @param {Array} checks appended to
3804
+ * @returns {Promise<{issues: number, langIssues: number}>} `langIssues` is returned
3805
+ * separately because `--fix --install-tools` acts on it, and recomputing it
3806
+ * would probe the toolchain twice.
3807
+ */
3808
+ async function collectTrailing(checks) {
3809
+ try {
3810
+ const upgradePromise = diagnoseUpgrade();
3811
+ const upgradeTimeout = new Promise((resolve) => setTimeout(() => resolve(), UPGRADE_PROBE_TIMEOUT_MS));
3812
+ await Promise.race([upgradePromise, upgradeTimeout]);
3813
+ } catch {
3814
+ // Non-blocking: the upgrade hint is a convenience, never a verdict.
3815
+ }
3816
+ const trailing = diagnoseOpenCodePlugin(checks);
3817
+ const langIssues = diagnoseLanguageTools();
3818
+ return { issues: trailing + langIssues, langIssues };
3819
+ }
3820
+
3821
+ /**
3822
+ * Report missing language tools, and install them only on explicit opt-in.
3823
+ *
3824
+ * #502: installing a toolchain changes the MACHINE, not the repository, so it is
3825
+ * never a side effect of `--fix`. Without `--install-tools` this prints what is
3826
+ * missing and names the flag; with it, the install runs and a project config is
3827
+ * generated so the next run does not rediscover the same gaps.
3828
+ *
3829
+ * Failures are non-blocking: a package manager that cannot reach its registry must
3830
+ * not turn a diagnosis into an error.
3831
+ *
3832
+ * @param {{fixMode: boolean, installToolsFlag: boolean, langIssues: number}} opts
3833
+ */
3834
+ function reportLanguageToolRepairs(opts) {
3835
+ const { fixMode, installToolsFlag, langIssues } = opts;
3836
+ if (!fixMode || langIssues <= 0) return;
3837
+
3838
+ if (!installToolsFlag) {
3839
+ console.log(`\n ${langIssues} language tool(s) are missing. --fix did not install them —`);
3840
+ console.log(' installing a toolchain changes the machine, so opt in with --install-tools (#502).');
3841
+ return;
3842
+ }
3843
+
3844
+ try {
3845
+ const { detectProjectLanguages, getToolsForLanguages, installTool, generateProjectConfig } = require('./language-tools.js');
3846
+ const projectRoot = process.cwd();
3847
+ const { detected } = detectProjectLanguages(projectRoot);
3848
+ if (detected.length === 0) return;
3849
+
3850
+ const toolStatus = getToolsForLanguages(detected);
3851
+ let installed = 0;
3852
+ for (const [lang, tools] of Object.entries(toolStatus)) {
3853
+ for (const t of tools) {
3854
+ if (t.status === 'missing' && installTool(t.tool).success) {
3855
+ console.log(` \u2713 ${t.tool.name} (${lang}) installed`);
3856
+ installed++;
3857
+ }
3858
+ }
3859
+ }
3860
+ if (installed > 0) {
3861
+ console.log(` ${installed} language tool(s) installed.`);
3862
+ generateProjectConfig(projectRoot, detected, toolStatus);
3863
+ }
3864
+ } catch {
3865
+ // Non-blocking: a package manager failure is not a diagnosis failure.
3866
+ }
3867
+ }
3868
+
3869
+ /**
3870
+ * Run the diagnosis under a deadline, keeping whatever finished.
3871
+ *
3872
+ * #348: a stack of network/subprocess probes once took 43 s on Windows, so the whole
3873
+ * run needs a bound. #629: the naive `Promise.race` DISCARDED everything the
3874
+ * diagnosis had produced, so the same healthy install reported different results run
3875
+ * to run and a timed-out run lost the skills section entirely (scrapers read 0/12
3876
+ * installed skills). The live `progress` sink is what makes a deadline able to say
3877
+ * "these finished, those did not" instead of replacing the diagnosis with a
3878
+ * placeholder.
3879
+ *
3880
+ * The pending surfaces are named individually so the reader knows exactly which
3881
+ * conclusions are missing, not merely that "something timed out".
3882
+ *
3883
+ * @param {boolean} refreshEnv
3884
+ * @returns {Promise<{checks: Array, issues: number, timedOut: boolean}>}
3885
+ */
3886
+ async function raceDiagnosis(refreshEnv) {
3250
3887
  const progress = { checks: [], getIssues: () => 0 };
3251
3888
  const diagnosisPromise = diagnoseAsync(refreshEnv, progress);
3252
- let diagnosisTimer = null;
3889
+
3890
+ let timer = null;
3253
3891
  const timeoutPromise = new Promise((resolve) => {
3254
- diagnosisTimer = setTimeout(() => {
3892
+ timer = setTimeout(() => {
3255
3893
  const completed = Array.isArray(progress.checks) ? progress.checks : [];
3256
3894
  const reported = new Set(completed.map((c) => c && c.name));
3257
- // Name the surfaces that did NOT report, so the reader knows exactly which
3258
- // conclusions are missing rather than just "something timed out".
3259
3895
  const pending = ['Hooks', 'Adapters', 'Skills', 'Gate env', 'OpenCode TUI']
3260
3896
  .filter((name) => !reported.has(name));
3261
3897
  resolve(mergeTimedOutDiagnosis(
@@ -3264,103 +3900,169 @@ async function doctor(args) {
3264
3900
  ));
3265
3901
  }, GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3266
3902
  });
3267
- const { checks, issues: diagnosedIssues, timedOut } = await Promise.race([
3268
- diagnosisPromise.then(r => ({ ...r, timedOut: false })),
3903
+
3904
+ const result = await Promise.race([
3905
+ diagnosisPromise.then((r) => ({ ...r, timedOut: false })),
3269
3906
  timeoutPromise,
3270
3907
  ]);
3271
- clearTimeout(diagnosisTimer);
3272
- let issues = diagnosedIssues;
3908
+ clearTimeout(timer);
3909
+ return { checks: result.checks, issues: result.issues, timedOut: result.timedOut };
3910
+ }
3273
3911
 
3274
- // A timeout discards every check that had not reported yet, including the
3275
- // drift surface, so the raced result must never be allowed to read as clean
3276
- // (#495 Round 2 -- this is the "stale modules, doctor green" outcome itself).
3277
- if (timedOut) {
3278
- issues = Math.max(issues, 1);
3279
- const hookDrift = diagnoseHookDrift();
3280
- const moduleDrift = diagnoseModuleDrift();
3281
- checks.push(...hookDrift.checks, ...moduleDrift.checks);
3282
- issues += hookDrift.issues + moduleDrift.issues;
3283
- }
3912
+ /**
3913
+ * Run the explicitly requested hook/module sync.
3914
+ *
3915
+ * §4.13 (#451 REQ-2): `doctor --sync-hooks` exists because editing `githooks/` changes
3916
+ * nothing until the installed copies are refreshed -- the trap that made #451 read as
3917
+ * "my edit does nothing". A non-zero result stops the run: the diagnosis that follows
3918
+ * would describe the state the sync just failed to reach.
3919
+ *
3920
+ * @param {boolean} force
3921
+ * @returns {boolean} whether the sync succeeded
3922
+ */
3923
+ function runExplicitSync(force) {
3924
+ return runHookAndModuleSync(force) === 0;
3925
+ }
3284
3926
 
3285
- // Flaky-test quarantine expiry (#603). A WARN, not a FAIL: an overdue ledger
3286
- // breaks nothing at runtime, it only means an intentional gap outlived its
3287
- // intent -- doctor's business, not a gate's.
3927
+ /**
3928
+ * Emit the machine-readable report.
3929
+ *
3930
+ * `--format json` means EXACTLY one JSON document on stdout, so the human report and
3931
+ * the trailing checks' own chatter are silenced while their results are still
3932
+ * collected into `checks`. Silencing by swapping `console.log` is the blunt way to do
3933
+ * it, and the `finally` is not optional: a throwing check would otherwise leave the
3934
+ * process unable to print anything at all.
3935
+ *
3936
+ * @param {Array} checks
3937
+ * @param {number} issues
3938
+ * @param {number} issues
3939
+ * @returns {Promise<number>} exit code
3940
+ */
3941
+ async function emitJsonReport(checks, issues) {
3942
+ const say = console.log;
3943
+ console.log = () => {};
3288
3944
  try {
3289
- const flaky = diagnoseFlakyQuarantine({ repoRoot: process.cwd() });
3290
- checks.push(...flaky.checks);
3291
- issues += flaky.issues;
3292
- } catch (err) {
3293
- // Surface the cause: a bare "could not be read" hid the real error and made
3294
- // this look like a missing file rather than a bug in the check itself.
3295
- checks.push({ name: 'Flaky quarantine', status: 'SKIP', detail: `ledger check failed: ${err && err.message ? err.message : String(err)}` });
3945
+ // JSON mode is read-only by contract, so the language-tool count is discarded.
3946
+ issues += (await collectTrailing(checks)).issues;
3947
+ } finally {
3948
+ console.log = say;
3296
3949
  }
3950
+ console.log(JSON.stringify(formatDoctorJson(checks, issues)));
3951
+ return issues > 0 ? 1 : 0;
3952
+ }
3297
3953
 
3298
- let langIssues = 0;
3299
- // Upgrade + plugin + language-tool status, kept as one callable because a
3300
- // --format json run still has to execute all of it (#488).
3301
- const collectTrailingChecks = async () => {
3302
- try {
3303
- const upgradePromise = diagnoseUpgrade();
3304
- const upgradeTimeout = new Promise((resolve) => setTimeout(() => resolve(), 3000));
3305
- await Promise.race([upgradePromise, upgradeTimeout]);
3306
- } catch { /* non-blocking */ }
3307
- const trailing = diagnoseOpenCodePlugin(checks);
3308
- langIssues = diagnoseLanguageTools();
3309
- return trailing + langIssues;
3310
- };
3954
+ /**
3955
+ * Re-diagnose after `--fix` so the run reports the RESULT, not the intent.
3956
+ *
3957
+ * The post-fix race mirrors the pre-fix one, including its failure mode: a timeout
3958
+ * discards the drift surface, so the post-fix report must not read as "all clear".
3959
+ * The placeholder says the result is UNCONFIRMED, not clean -- otherwise a fix that
3960
+ * could not be verified would be indistinguishable from one that worked.
3961
+ *
3962
+ * @returns {Promise<void>}
3963
+ */
3964
+ async function reportPostFixDiagnosis() {
3965
+ console.log('\nRe-running diagnosis after fix...');
3966
+ const postDiagPromise = diagnoseAsync();
3967
+ let postTimer = null;
3968
+ const postTimeout = new Promise((resolve) => {
3969
+ postTimer = setTimeout(() => resolve({
3970
+ checks: [{
3971
+ name: 'Post-fix diagnosis',
3972
+ status: 'WARN',
3973
+ detail: `Timed out after ${GLOBAL_DIAGNOSIS_TIMEOUT_MS / 1000}s — the fix result is unconfirmed, not clean`,
3974
+ }],
3975
+ issues: 1,
3976
+ timedOut: true,
3977
+ }), GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3978
+ });
3311
3979
 
3312
- if (jsonMode) {
3313
- // Machine-readable output means EXACTLY one JSON document on stdout, so the
3314
- // human report and the trailing checks' chatter are silenced while their
3315
- // results are still collected into `checks`.
3316
- const say = console.log;
3317
- console.log = () => {};
3318
- try {
3319
- issues += await collectTrailingChecks();
3320
- } finally {
3321
- console.log = say;
3322
- }
3323
- console.log(JSON.stringify(formatDoctorJson(checks, issues)));
3324
- return issues > 0 ? 1 : 0;
3980
+ const { checks: postChecks, timedOut: postTimedOut } = await Promise.race([
3981
+ postDiagPromise.then((r) => ({ ...r, timedOut: false })),
3982
+ postTimeout,
3983
+ ]);
3984
+ clearTimeout(postTimer);
3985
+ if (postTimedOut) {
3986
+ postChecks.push(...diagnoseHookDrift().checks, ...diagnoseModuleDrift().checks);
3325
3987
  }
3988
+ printReport(postChecks);
3989
+ }
3990
+
3991
+ /**
3992
+ * Print the header and which hook files and gate modules actually execute.
3993
+ *
3994
+ * §4.13 (#451 REQ-3): the question "I edited `githooks/` but nothing changed" is
3995
+ * answered by printing the effective paths, not by asking the reader to work it out
3996
+ * from git config. #495 added the same for the gate modules the hook sources at
3997
+ * runtime, since those drift independently of the hook files.
3998
+ *
3999
+ * Human output only -- `--format json` puts one document on stdout and nothing else.
4000
+ */
4001
+ function printEffectiveLayout() {
4002
+ console.log('XP-Gate Doctor');
4003
+ console.log('==============');
4004
+ printEffectiveHooks();
4005
+ printEffectiveModules();
4006
+ }
4007
+
4008
+ /**
4009
+ * Handle the two ways a run can end before any diagnosis: `--brief`, and bad flags.
4010
+ *
4011
+ * `--brief` is checked FIRST and only when the flags are valid: it answers its own
4012
+ * question and never reads the diagnosis surface, so flagging an unrelated unknown
4013
+ * flag would be noise on a call designed to be cheap.
4014
+ *
4015
+ * @param {{briefFlag: boolean, errors: string[], jsonMode: boolean}} p
4016
+ * @returns {number|null} an exit code when the run ends here, else null
4017
+ */
4018
+ function handlePreflight(p) {
4019
+ const { briefFlag, errors, jsonMode } = p;
4020
+ if (briefFlag && errors.length === 0) {
4021
+ runBriefReport(jsonMode);
4022
+ return process.exitCode ?? 0;
4023
+ }
4024
+ if (errors.length === 0) return null;
4025
+ for (const error of errors) console.error(error);
4026
+ return 1;
4027
+ }
4028
+
4029
+ async function doctor(args) {
4030
+ const { errors, fixMode, syncHooks, force, installToolsFlag, jsonMode, refreshEnv, briefFlag } = doctorFlagContract(args);
4031
+ const preflight = handlePreflight({ briefFlag, errors, jsonMode });
4032
+ if (preflight !== null) return preflight;
4033
+
4034
+ const config = getConfig();
4035
+ if (!jsonMode) printEffectiveLayout();
4036
+ // §4.8: mode === "uninstalled" → print "xp-gate is not installed"
4037
+ if (isUninstalledMode(config)) return reportUninstalled(jsonMode);
4038
+
4039
+ if (syncHooks && !runExplicitSync(force)) return 1;
4040
+ if (fixMode && isActiveMode(config)) fixIssues(null, config, installToolsFlag);
4041
+
4042
+ // Global timeout wrapper — ensures doctor completes within GLOBAL_DIAGNOSIS_TIMEOUT_MS
4043
+ // even if network/subprocess checks stack up (fix #348: 43s on Windows).
4044
+ // #629: give diagnoseAsync a live sink so a deadline can keep what finished.
4045
+ // Without it, `Promise.race` discarded the entire diagnosis -- so the SAME
4046
+ // healthy install reported different results run to run, and a timed-out run
4047
+ // lost the skills section entirely (scrapers read 0/12 installed skills).
4048
+ const diagnosis = await raceDiagnosis(refreshEnv);
4049
+ const { checks, timedOut } = diagnosis;
4050
+ let issues = diagnosis.issues;
4051
+
4052
+ // A timeout discards every check that had not reported yet, including the
4053
+ // drift surface, so the raced result must never be allowed to read as clean
4054
+ // (#495 Round 2 -- this is the "stale modules, doctor green" outcome itself).
4055
+ issues += coverIncompleteRun(timedOut, checks, issues);
4056
+
4057
+ if (jsonMode) return await emitJsonReport(checks, issues);
3326
4058
 
3327
4059
  printReport(checks);
3328
4060
 
3329
- issues += await collectTrailingChecks();
4061
+ const trailing = await collectTrailing(checks);
4062
+ issues += trailing.issues;
4063
+ reportLanguageToolRepairs({ fixMode, installToolsFlag, langIssues: trailing.langIssues });
3330
4064
 
3331
- // In --fix mode, auto-install missing language tools — only on explicit
3332
- // --install-tools (#502: a diagnosis command must not run package managers).
3333
- if (fixMode && installToolsFlag && langIssues > 0) {
3334
- try {
3335
- const { detectProjectLanguages, getToolsForLanguages, installTool, generateProjectConfig, LANGUAGE_REGISTRY } = require('./language-tools.js');
3336
- const projectRoot = process.cwd();
3337
- const { detected } = detectProjectLanguages(projectRoot);
3338
- if (detected.length > 0) {
3339
- const toolStatus = getToolsForLanguages(detected);
3340
- let installed = 0;
3341
- for (const [lang, tools] of Object.entries(toolStatus)) {
3342
- for (const t of tools) {
3343
- if (t.status === 'missing') {
3344
- const result = installTool(t.tool);
3345
- if (result.success) {
3346
- console.log(` \u2713 ${t.tool.name} (${lang}) installed`);
3347
- installed++;
3348
- }
3349
- }
3350
- }
3351
- }
3352
- if (installed > 0) {
3353
- console.log(` ${installed} language tool(s) installed.`);
3354
- generateProjectConfig(projectRoot, detected, toolStatus);
3355
- }
3356
- }
3357
- } catch { /* non-blocking */ }
3358
- }
3359
4065
 
3360
- if (fixMode && !installToolsFlag && langIssues > 0) {
3361
- console.log(`\n ${langIssues} language tool(s) are missing. --fix did not install them —`);
3362
- console.log(' installing a toolchain changes the machine, so opt in with --install-tools (#502).');
3363
- }
3364
4066
 
3365
4067
  if (issues === 0) {
3366
4068
  console.log('\n✓ All checks passed');
@@ -3369,30 +4071,7 @@ async function doctor(args) {
3369
4071
 
3370
4072
  console.log(`\n✗ ${issues} issue(s) found`);
3371
4073
 
3372
- // Re-run diagnosis after fix to report updated status
3373
- if (fixMode && isActiveMode(config)) {
3374
- console.log('\nRe-running diagnosis after fix...');
3375
- const postDiagPromise = diagnoseAsync();
3376
- let postTimer = null;
3377
- const postTimeout = new Promise((resolve) => {
3378
- postTimer = setTimeout(() => resolve({
3379
- checks: [{ name: 'Post-fix diagnosis', status: 'WARN', detail: `Timed out after ${GLOBAL_DIAGNOSIS_TIMEOUT_MS / 1000}s — the fix result is unconfirmed, not clean` }],
3380
- issues: 1,
3381
- timedOut: true,
3382
- }), GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3383
- });
3384
- const { checks: postChecks, timedOut: postTimedOut } = await Promise.race([
3385
- postDiagPromise.then(r => ({ ...r, timedOut: false })),
3386
- postTimeout,
3387
- ]);
3388
- clearTimeout(postTimer);
3389
- // Symmetry with the pre-fix race above: a timeout here discards the drift
3390
- // surface too, so the post-fix report must not read as "all clear".
3391
- if (postTimedOut) {
3392
- postChecks.push(...diagnoseHookDrift().checks, ...diagnoseModuleDrift().checks);
3393
- }
3394
- printReport(postChecks);
3395
- }
4074
+ if (fixMode && isActiveMode(config)) await reportPostFixDiagnosis();
3396
4075
 
3397
4076
  return issues > 0 ? 1 : 0;
3398
4077
  }
@@ -3417,21 +4096,105 @@ function formatDoctorJson(checks, issues) {
3417
4096
  // real failure was silent: drifted agent bindings looked like a working setup
3418
4097
  // (B2), a stale skill copy made reinstall = downgrade (B4), and a missing
3419
4098
  // runner script surfaced only as a failed review (B3).
3420
- async function doctorDelphi(options = {}) {
3421
- const { configPath, npmLatest } = options;
3422
- // #541: the shadow check needs the loader's global fallback path. It is
3423
- // injectable for tests; the default mirrors delphi-config.ts /
3424
- // delphi-external-review.cjs resolution (XDG_CONFIG_HOME honored).
3425
- const globalConfigPath = options.globalConfigPath
3426
- || path.join(process.env.XDG_CONFIG_HOME || path.join(require('os').homedir(), '.config'), 'xp-gate', '.delphi-config.json');
3427
- const checks = [];
3428
- const add = (name, status, detail) => checks.push({ name, status, detail });
4099
+ /**
4100
+ * Check 2: Qoder Delphi agent bindings.
4101
+ *
4102
+ * Extracted from `doctorDelphi`, which measured CCN 81 over 235 lines by
4103
+ * holding five independent checks. Each one is its own question with its own
4104
+ * states, and inlining them made a failure impossible to locate.
4105
+ *
4106
+ * Reports through the caller's `add` so the check list stays one list.
4107
+ *
4108
+ * @param {(name: string, status: string, detail?: string) => void} add
4109
+ * @param {{projectDir?: string}} options
4110
+ */
4111
+ /** The three Delphi expert roles, in the order every report lists them. */
3429
4112
 
3430
- // 1. Node >= 18: the runner gates on it and exits 1 mid-review otherwise.
3431
- const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
3432
- add('Node.js >= 18', nodeMajor >= 18 ? 'PASS' : 'FAIL',
3433
- `current: ${process.versions.node}`);
4113
+ /**
4114
+ * Work out which Delphi agent directory applies, and whether the native path is
4115
+ * even in use.
4116
+ *
4117
+ * Project-level agents (from `delphi-setup --local --project`) take precedence when
4118
+ * a complete set exists there, so `doctor` agrees with the repair command (#414 R1
4119
+ * FC-09).
4120
+ *
4121
+ * #646: when the machine is configured for the external channel only, the native
4122
+ * path is DISABLED BY CHOICE, not broken. Reporting FAIL there told external users
4123
+ * their working setup was broken and pointed them at a repair that reinstalls what
4124
+ * they just removed. Callers SKIP with the reason, so the line can never read green
4125
+ * either.
4126
+ *
4127
+ * The channel home is the directory CONTAINING `.config`: `resolveChannels()`
4128
+ * appends `<home>/.config/xp-gate/...`, so passing `.config` itself would look in
4129
+ * `.config/.config/xp-gate` and never find the file.
4130
+ *
4131
+ * @param {{projectDir?: string}} options
4132
+ * @returns {{nativeDisabled: boolean, channelResolution: object, agentsDir: string,
4133
+ * agentsSource: string, agentDetails: string[]}} `channelResolution` is returned so
4134
+ * the SKIP detail can name the channels and where they came from.
4135
+ */
4136
+ function resolveAgentTarget(options) {
4137
+ const delphiChannel = require('./delphi-channel.js');
4138
+ const channelHome = process.env.XDG_CONFIG_HOME
4139
+ ? path.dirname(process.env.XDG_CONFIG_HOME)
4140
+ : undefined;
4141
+ const channelResolution = delphiChannel.resolveChannels({ home: channelHome });
4142
+
4143
+ const homeAgentsDir = path.join(HOME_DIR(), '.qoder', 'agents');
4144
+ // Injectable for tests; defaults to the cwd the doctor runs from.
4145
+ const projectAgentsDir = path.join(options.projectDir || process.cwd(), '.qoder', 'agents');
4146
+ const homeComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(homeAgentsDir, `delphi-${r}.md`)));
4147
+ const projectComplete = DELPHI_ROLES.every((r) => fs.existsSync(path.join(projectAgentsDir, `delphi-${r}.md`)));
4148
+ const agentsDir = projectComplete ? projectAgentsDir : homeAgentsDir;
4149
+ const agentsSource = projectComplete
4150
+ ? `project-level ${agentsDir}`
4151
+ : `user-level ${agentsDir}`;
4152
+
4153
+ return {
4154
+ nativeDisabled: !channelResolution.nativeEnabled,
4155
+ channelResolution,
4156
+ agentsDir,
4157
+ agentsSource,
4158
+ agentDetails: [agentsSource],
4159
+ };
4160
+ }
4161
+
4162
+ /**
4163
+ * Inspect ONE role's installed agent file against the bundled template.
4164
+ *
4165
+ * The three failure classes are reported separately because each has its own remedy
4166
+ * (#414 R1 MI-02): a missing file needs an install, an unparseable binding needs
4167
+ * `delphi-setup`, and a bundle without a parseable template is install CORRUPTION --
4168
+ * skipping that comparison would hide it behind a healthy-looking id (#414 R1 FC-08).
4169
+ *
4170
+ * @param {string} role
4171
+ * @param {string} agentsDir
4172
+ * @param {(p: string) => string|null} readId
4173
+ * @returns {{ok: boolean, detail: string, id?: string}}
4174
+ */
4175
+ function inspectAgentBinding(role, agentsDir, readId) {
4176
+ const agentPath = path.join(agentsDir, `delphi-${role}.md`);
4177
+ if (!fs.existsSync(agentPath)) {
4178
+ return {
4179
+ ok: false,
4180
+ detail: `delphi-${role}.md missing (run: xp-gate init --global, or delphi-setup --local --project for project scope)`,
4181
+ };
4182
+ }
4183
+ const id = readId(agentPath);
4184
+ if (id === null) {
4185
+ return { ok: false, detail: `delphi-${role}.md has no quoted model binding (repair: xp-gate delphi-setup)` };
4186
+ }
4187
+ const bundledId = readId(path.join(PKG_DIR, 'plugins', 'qoder', 'agents', `delphi-${role}.md`));
4188
+ if (bundledId === null) {
4189
+ return { ok: false, detail: `delphi-${role}: bundled template missing/unreadable — reinstall xp-gate` };
4190
+ }
4191
+ if (bundledId !== id) {
4192
+ return { ok: true, id, detail: `delphi-${role}: ${id} (this version ships ${bundledId} — repair: xp-gate delphi-setup)` };
4193
+ }
4194
+ return { ok: true, id, detail: `delphi-${role}: ${id}` };
4195
+ }
3434
4196
 
4197
+ function checkDelphiAgentBindings(add, options) {
3435
4198
  // 2. Qoder agent bindings: present, parseable, three distinct ids, matching
3436
4199
  // what this version ships. A stale binding is a repair, not an error to
3437
4200
  // retype: the detail names delphi-setup. Project-level agents (from
@@ -3443,29 +4206,10 @@ async function doctorDelphi(options = {}) {
3443
4206
  // users their working setup was broken and pointed them at a repair command that
3444
4207
  // reinstalls the thing they just removed. SKIP carries the reason so the line can
3445
4208
  // never be read as green either -- the same rule every other gate follows.
3446
- const delphiChannel = require('./delphi-channel.js');
3447
- // Pass the directory that CONTAINS `.config`, not the `.config` dir itself:
3448
- // resolveChannels() appends `<home>/.config/xp-gate/...`, so handing it `.config`
3449
- // would look in `.config/.config/xp-gate` and never find the file.
3450
- const channelHome = process.env.XDG_CONFIG_HOME
3451
- ? path.dirname(process.env.XDG_CONFIG_HOME)
3452
- : undefined;
3453
- const channelResolution = delphiChannel.resolveChannels({ home: channelHome });
3454
- const nativeDisabled = !channelResolution.nativeEnabled;
4209
+ const { nativeDisabled, channelResolution, agentsDir, agentsSource, agentDetails } = resolveAgentTarget(options);
3455
4210
  const { readQoderModelId } = require('./init.js');
3456
- const roles = ['architecture', 'technical', 'feasibility'];
3457
- const homeAgentsDir = path.join(HOME_DIR(), '.qoder', 'agents');
3458
- // Injectable for tests; defaults to the cwd the doctor runs from.
3459
- const projectAgentsDir = path.join(options.projectDir || process.cwd(), '.qoder', 'agents');
3460
- const homeComplete = roles.every((r) => fs.existsSync(path.join(homeAgentsDir, `delphi-${r}.md`)));
3461
- const projectComplete = roles.every((r) => fs.existsSync(path.join(projectAgentsDir, `delphi-${r}.md`)));
3462
- const agentsDir = projectComplete ? projectAgentsDir : homeAgentsDir;
3463
- const agentsSource = projectComplete
3464
- ? `project-level ${agentsDir}`
3465
- : `user-level ${agentsDir}`;
3466
4211
  const agentIds = [];
3467
4212
  let agentsStatus = 'PASS';
3468
- const agentDetails = [agentsSource];
3469
4213
  // #646: skip the whole native binding check when the machine is external-only.
3470
4214
  // The check exists to keep the native path healthy; when that path is switched off
3471
4215
  // by configuration there is nothing to keep healthy, and reporting its absence as
@@ -3475,33 +4219,11 @@ async function doctorDelphi(options = {}) {
3475
4219
  `native channel disabled (channels=${channelResolution.channels.join(',')} via ${channelResolution.source}) — `
3476
4220
  + 'Delphi review runs through the external provider');
3477
4221
  }
3478
- for (const role of nativeDisabled ? [] : roles) {
3479
- const agentPath = path.join(agentsDir, `delphi-${role}.md`);
3480
- if (!fs.existsSync(agentPath)) {
3481
- agentsStatus = 'FAIL';
3482
- agentDetails.push(`delphi-${role}.md missing (run: xp-gate init --global, or delphi-setup --local --project for project scope)`);
3483
- continue;
3484
- }
3485
- const id = readQoderModelId(agentPath);
3486
- if (id === null) {
3487
- agentsStatus = 'FAIL';
3488
- agentDetails.push(`delphi-${role}.md has no quoted model binding (repair: xp-gate delphi-setup)`);
3489
- continue;
3490
- }
3491
- const bundledId = readQoderModelId(path.join(PKG_DIR, 'plugins', 'qoder', 'agents', `delphi-${role}.md`));
3492
- if (bundledId === null) {
3493
- // A bundle without a parseable template is install corruption: skipping
3494
- // the comparison would hide it behind a healthy-looking id (#414 R1 FC-08).
3495
- agentsStatus = 'FAIL';
3496
- agentDetails.push(`delphi-${role}: bundled template missing/unreadable — reinstall xp-gate`);
3497
- continue;
3498
- }
3499
- if (bundledId !== id) {
3500
- agentDetails.push(`delphi-${role}: ${id} (this version ships ${bundledId} — repair: xp-gate delphi-setup)`);
3501
- } else {
3502
- agentDetails.push(`delphi-${role}: ${id}`);
3503
- }
3504
- agentIds.push(id);
4222
+ for (const role of nativeDisabled ? [] : DELPHI_ROLES) {
4223
+ const outcome = inspectAgentBinding(role, agentsDir, readQoderModelId);
4224
+ if (!outcome.ok) agentsStatus = 'FAIL';
4225
+ agentDetails.push(outcome.detail);
4226
+ if (outcome.id) agentIds.push(outcome.id);
3505
4227
  }
3506
4228
  // Report every problem class independently: missing files, unparseable
3507
4229
  // bindings and duplicates can coexist, and each has a different remedy
@@ -3511,14 +4233,88 @@ async function doctorDelphi(options = {}) {
3511
4233
  // empty agentIds (the disabled path) would compute `0 !== 3` and re-report the very
3512
4234
  // FAIL the SKIP above just replaced.
3513
4235
  if (!nativeDisabled) {
3514
- if (agentIds.length !== roles.length) agentsStatus = 'FAIL';
4236
+ if (agentIds.length !== DELPHI_ROLES.length) agentsStatus = 'FAIL';
3515
4237
  if (new Set(agentIds).size !== agentIds.length) {
3516
4238
  agentsStatus = 'FAIL';
3517
4239
  agentDetails.push('duplicate model binding across experts — three DISTINCT ids are required');
3518
4240
  }
3519
4241
  add('Qoder Delphi agent bindings', agentsStatus, agentDetails.join('; ') || 'all three bound');
3520
4242
  }
4243
+ }
4244
+
4245
+ /**
4246
+ * Check 3: installed skill copies match what this version ships.
4247
+ *
4248
+ * A drifted installed copy is how "reinstall from an old local repo" became a
4249
+ * downgrade (#414 B4). Every bundled file is compared, not just SKILL.md --
4250
+ * the install script copies *.json and references/ too (#414 R1 MI-03).
4251
+ *
4252
+ * @param {(name: string, status: string, detail?: string) => void} add
4253
+ * @param {object} options
4254
+ * @returns {string} the resolved installed skill dir, which the runner-locate
4255
+ * check below reads. Returning it keeps ONE resolution instead of duplicating
4256
+ * the platform mapping at the second call site.
4257
+ */
4258
+ /**
4259
+ * Every file in the bundled skill, relative to its root.
4260
+ *
4261
+ * A bundle we cannot read is reported as an EMPTY bundle, which the parity check
4262
+ * already treats as "every installed file is extra" -- a truthful, loud outcome.
4263
+ *
4264
+ * @param {string} dir
4265
+ * @param {string} [base]
4266
+ * @param {string[]} [out]
4267
+ * @returns {string[]}
4268
+ */
4269
+ function listBundledSkillFiles(dir, base = dir, out = []) {
4270
+ if (!fs.existsSync(dir)) return out;
4271
+ let entries;
4272
+ try {
4273
+ entries = fs.readdirSync(dir, { withFileTypes: true });
4274
+ } catch {
4275
+ return out;
4276
+ }
4277
+ for (const entry of entries) {
4278
+ const p = path.join(dir, entry.name);
4279
+ if (entry.isDirectory()) listBundledSkillFiles(p, base, out);
4280
+ else out.push(path.relative(base, p));
4281
+ }
4282
+ return out;
4283
+ }
3521
4284
 
4285
+ /**
4286
+ * Compare every deployed copy against the bundle and report the verdict.
4287
+ *
4288
+ * #725: EVERY platform with the skill deployed is checked, not only the one
4289
+ * `detectPlatform()` selects. On a machine with both Qoder and OpenCode the OpenCode
4290
+ * copy was frozen at an old version while this check reported PASS, because it never
4291
+ * looked there -- the drifted copy was invisible to both `update-skill` and `doctor`.
4292
+ */
4293
+ function reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256) {
4294
+ // #725: check every platform that has the skill deployed, not only the one
4295
+ // `detectPlatform()` selects. On a machine with both Qoder and OpenCode the
4296
+ // OpenCode copy was frozen at an old version and this check reported PASS,
4297
+ // because it never looked there -- the drifted copy was invisible to both
4298
+ // `update-skill` and `doctor`.
4299
+ const drifted = [];
4300
+ for (const dir of deployedDirs) {
4301
+ const dirDrift = collectSkillDrift(dir, bundledFiles, bundledSkillDir, sha256);
4302
+ if (dirDrift.length > 0) {
4303
+ drifted.push(`${platformTag(dir)}: ${dirDrift.join(', ')}`);
4304
+ }
4305
+ }
4306
+ if (drifted.length > 0) {
4307
+ add('Delphi skill install parity', 'FAIL',
4308
+ `installed copy differs from the ${getCliVersionSafe()} bundle — `
4309
+ + `${drifted.slice(0, 3).join('; ')}${drifted.length > 3 ? '; ...' : ''} `
4310
+ + '(reinstall: xp-gate install-skill delphi-review --force)');
4311
+ } else {
4312
+ add('Delphi skill install parity', 'PASS',
4313
+ `${bundledFiles.length} file(s) match the bundle across ${deployedDirs.length} platform(s)`);
4314
+ }
4315
+ }
4316
+
4317
+ function checkSkillInstallParity(add, options) {
3522
4318
  // 3. Skill install parity: a drifted installed copy is how "reinstall from
3523
4319
  // an old local repo" became a downgrade (#414 B4). Every bundled file is
3524
4320
  // compared, not just SKILL.md — the install script copies *.json and
@@ -3536,16 +4332,9 @@ async function doctorDelphi(options = {}) {
3536
4332
  // Injectable for tests (#414 R3 FC-01/FC-02): the empty-bundle branch is a
3537
4333
  // real failure mode and must be drivable without mutating the package.
3538
4334
  const bundledSkillDir = options.bundledSkillDir || path.join(PKG_DIR, 'skills', 'delphi-review');
3539
- const sha256 = (p) => require('crypto').createHash('sha256').update(fs.readFileSync(p)).digest('hex');
3540
- const listBundledSkillFiles = (dir, base = dir, out = []) => {
3541
- if (!fs.existsSync(dir)) return out;
3542
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
3543
- const p = path.join(dir, entry.name);
3544
- if (entry.isDirectory()) listBundledSkillFiles(p, base, out);
3545
- else out.push(path.relative(base, p));
3546
- }
3547
- return out;
3548
- };
4335
+ const sha256 = (p) => fileSha256(p);
4336
+ // A bundle we cannot read is reported as an empty bundle, which the parity check
4337
+ // already treats as "every installed file is extra" -- a truthful, loud outcome.
3549
4338
  // #725 follow-up: decide "installed anywhere?" from the full platform set, not
3550
4339
  // just the directory `detectPlatform()` selects — a dsh-only machine has no
3551
4340
  // marker detectPlatform() keys on, so the opencode fallback directory never
@@ -3566,63 +4355,262 @@ async function doctorDelphi(options = {}) {
3566
4355
  add('Delphi skill install parity', 'FAIL',
3567
4356
  `bundled skill directory missing or empty: ${bundledSkillDir} — reinstall xp-gate`);
3568
4357
  } else {
3569
- // #725: check every platform that has the skill deployed, not only the one
3570
- // `detectPlatform()` selects. On a machine with both Qoder and OpenCode the
3571
- // OpenCode copy was frozen at an old version and this check reported PASS,
3572
- // because it never looked there -- the drifted copy was invisible to both
3573
- // `update-skill` and `doctor`.
3574
- const drifted = [];
3575
- for (const dir of deployedDirs) {
3576
- const dirDrift = collectSkillDrift(dir, bundledFiles, bundledSkillDir, sha256);
3577
- if (dirDrift.length > 0) {
3578
- drifted.push(`${platformTag(dir)}: ${dirDrift.join(', ')}`);
3579
- }
3580
- }
3581
- if (drifted.length > 0) {
3582
- add('Delphi skill install parity', 'FAIL',
3583
- `installed copy differs from the ${getCliVersionSafe()} bundle — `
3584
- + `${drifted.slice(0, 3).join('; ')}${drifted.length > 3 ? '; ...' : ''} `
3585
- + '(reinstall: xp-gate install-skill delphi-review --force)');
3586
- } else {
3587
- add('Delphi skill install parity', 'PASS',
3588
- `${bundledFiles.length} file(s) match the bundle across ${deployedDirs.length} platform(s)`);
3589
- }
4358
+ reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256);
3590
4359
  }
3591
4360
  }
4361
+ return installedSkillDir;
4362
+ }
3592
4363
 
3593
- // 4. Runner script locate: the runner must be findable from the places a
3594
- // review actually starts.
3595
- const runnerCandidates = [
3596
- ['package bundle', path.join(PKG_DIR, 'scripts', 'delphi-external-review.cjs')],
3597
- ['project', path.join(process.cwd(), 'scripts', 'delphi-external-review.cjs')],
3598
- ['installed skill', path.join(installedSkillDir, 'scripts', 'delphi-external-review.cjs')],
4364
+ /**
4365
+ * Check 5: the Delphi config parses and names three distinct callable models.
4366
+ *
4367
+ * Pulled out of `doctorDelphi` because it is the largest single check and the
4368
+ * least related to the others: everything above asks "is this installed", this
4369
+ * one asks "will a review actually run".
4370
+ *
4371
+ * @param {(name: string, status: string, detail?: string) => void} add
4372
+ */
4373
+ /**
4374
+ * Problems with a Delphi profile's expert model bindings.
4375
+ *
4376
+ * Pure: profile in, problem list out. It was inline inside a try/catch inside an
4377
+ * if/else inside the config check, four levels down, where the three distinct
4378
+ * failure modes (missing role, duplicate model, unusable provider) were one
4379
+ * compound condition.
4380
+ *
4381
+ * @param {object} profile
4382
+ * @returns {string[]} human-readable problems; empty when the profile is usable
4383
+ */
4384
+ function delphiModelProblems(profile) {
4385
+ const experts = profile.experts || {};
4386
+ const providers = profile.providers || {};
4387
+ const models = DELPHI_ROLES.map((r) => experts[r] && experts[r].model);
4388
+
4389
+ const missingRoles = DELPHI_ROLES.filter((r, i) => !models[i]);
4390
+ const duplicates = models.filter((m, i) => m && models.indexOf(m) !== i);
4391
+ const badProviders = DELPHI_ROLES.filter((r) => !isSeatUsable(experts[r], providers));
4392
+
4393
+ // Collected as data and filtered once: three `if`s over three lists is three
4394
+ // branches to say "report whichever are non-empty".
4395
+ return [
4396
+ [missingRoles, `missing experts: ${missingRoles.join(', ')}`],
4397
+ [duplicates, `duplicate models: ${[...new Set(duplicates)].join(', ')}`],
4398
+ [badProviders, `unusable provider binding: ${badProviders.join(', ')}`],
4399
+ ].filter(([items]) => items.length > 0).map(([, message]) => message);
4400
+ }
4401
+
4402
+ /**
4403
+ * Whether one expert seat points at a provider that can actually be called.
4404
+ *
4405
+ * Three ways to fail, and they are reported as one because the remedy is the same
4406
+ * (fix the binding): no expert entry, a provider name the config does not define, or
4407
+ * a base_url that is missing or not an http(s) URL. The last check is `indexOf('http')
4408
+ * === 0` rather than a URL parse on purpose -- a config with `ftp://` or a bare host
4409
+ * both fail, and rejecting it early beats a network error later.
4410
+ *
4411
+ * @param {{provider?: string}|undefined} expert
4412
+ * @param {Object<string, {base_url?: string}>} providers
4413
+ * @returns {boolean}
4414
+ */
4415
+ function isSeatUsable(expert, providers) {
4416
+ if (!expert) return false;
4417
+ const provider = providers[expert.provider];
4418
+ if (!provider || !provider.base_url) return false;
4419
+ return String(provider.base_url).indexOf('http') === 0;
4420
+ }
4421
+
4422
+ /**
4423
+ * Report whether the installed xp-gate matches npm's latest.
4424
+ *
4425
+ * The npm probe is opt-in (`probeNpmLatest`) or pre-supplied (`npmLatest`): the
4426
+ * doctor never blocks on the network, which an offline CI or a restricted shell
4427
+ * would otherwise hit (#414 R1 FC-03).
4428
+ *
4429
+ * @param {(name: string, status: string, detail?: string) => void} add
4430
+ * @param {object} options
4431
+ * @param {string|null|undefined} npmLatest
4432
+ */
4433
+ async function checkDelphiVersionConsistency(add, options, npmLatest) {
4434
+ const localVersion = getCliVersionSafe();
4435
+ let versionStatus = 'PASS';
4436
+ let versionDetail = `xp-gate ${localVersion}`;
4437
+
4438
+ if (npmLatest === undefined && options.probeNpmLatest === true) {
4439
+ try {
4440
+ // `execWithTimeout` is async; reading `.trim()` off the Promise threw, and the
4441
+ // catch below swallowed it -- so a WORKING npm probe reported 'offline?' every
4442
+ // time. Measured: `Promise.prototype.trim` is undefined.
4443
+ const probed = await execWithTimeout('npm view @boyingliu01/xp-gate version', NPM_PROBE_TIMEOUT_MS);
4444
+ versionDetail += `; npm latest probe: ${String(probed).trim()}`;
4445
+ } catch {
4446
+ versionStatus = 'SKIP';
4447
+ versionDetail += '; npm latest probe unavailable (offline?) — skipped';
4448
+ }
4449
+ } else if (typeof npmLatest === 'string' && npmLatest !== localVersion) {
4450
+ versionStatus = 'FAIL';
4451
+ versionDetail += `; npm latest ${npmLatest} differs from local ${localVersion} — update (npm install -g @boyingliu01/xp-gate@latest) or verify which side is stale`;
4452
+ } else if (npmLatest === null || options.probeNpmLatest !== true) {
4453
+ versionDetail += '; npm latest probe skipped (pass --npm-check or options.probeNpmLatest to run it)';
4454
+ }
4455
+ add('Delphi version consistency', versionStatus, versionDetail);
4456
+ }
4457
+
4458
+
4459
+ /**
4460
+ * Check 7: DSH native-channel readiness (#443 REQ-6).
4461
+ *
4462
+ * Only meaningful when a DSH home exists. The two-layer switch (preset
4463
+ * capability plus host setting) defaults to DISABLED, and a review that
4464
+ * assumes native will silently run three same-model seats -- the failure this
4465
+ * check exists to make visible before a review spends money on it.
4466
+ *
4467
+ * @param {(name: string, status: string, detail?: string) => void} add
4468
+ */
4469
+ function checkDshChannelReadiness(add) {
4470
+ // 7. DSH native-channel readiness (#443 REQ-6): only meaningful when a DSH home
4471
+ // exists. The two-layer switch (preset capability + host setting) defaults to
4472
+ // disabled, and a review that assumes native will silently run three same-model
4473
+ // seats.
4474
+ const label = 'DSH subagent model selection';
4475
+ const dshHome = path.join(HOME_DIR(), '.dsh');
4476
+ if (!fs.existsSync(dshHome)) {
4477
+ add(label, 'SKIP', `no ${dshHome} — not a DSH environment`);
4478
+ return;
4479
+ }
4480
+
4481
+ const settingsCandidates = [
4482
+ path.join(dshHome, 'settings.json'),
4483
+ path.join(dshHome, 'settings', 'settings.json'),
4484
+ path.join(dshHome, 'config.json'),
3599
4485
  ];
3600
- const foundRunner = runnerCandidates.filter(([, p]) => fs.existsSync(p));
3601
- add('delphi-external-review runner', foundRunner.length > 0 ? 'PASS' : 'FAIL',
3602
- foundRunner.length > 0
3603
- ? foundRunner.map(([label, p]) => `${label}: ${p}`).join('; ')
3604
- : 'not found in package bundle, project, or installed skill');
4486
+ const settingsFile = settingsCandidates.find((p) => fs.existsSync(p));
4487
+ if (!settingsFile) {
4488
+ add(label, 'FAIL',
4489
+ `${dshHome} exists but no settings file found — subagent model selection defaults to disabled (#443)`);
4490
+ return;
4491
+ }
3605
4492
 
3606
- // 5. Config ping: parseable, three distinct callable models. A duplicate
3607
- // model here is a review that will BLOCK later — say so now.
3608
- //
3609
- // #684: resolve the SAME way the runner does. A project-local config wins; a
3610
- // machine-level one under XDG_CONFIG_HOME (or ~/.config) is the documented
3611
- // fallback, and a review keeps working on it. Checking only `cwd` reported
3612
- // FAIL on the layout SKILL.md recommends and told the user to copy the example
3613
- // into the project — manufacturing the drifted duplicate #541 warns about.
3614
- //
3615
- // An explicit `configPath` is an ANSWER, not a hint: a caller that names a
3616
- // file means that file, so it disables the fallback. Otherwise a test (or a
3617
- // caller) pinning an absent path silently reads the developer's real global
3618
- // config and reports PASS — the same vacuous-pass shape this batch is fixing.
3619
- const projectCfgPath = configPath
3620
- || path.join(options.projectDir || process.cwd(), '.delphi-config.json');
3621
- const usingGlobalConfig = !configPath
3622
- && !fs.existsSync(projectCfgPath)
3623
- && fs.existsSync(globalConfigPath);
3624
- const cfgPath = usingGlobalConfig ? globalConfigPath : projectCfgPath;
3625
- const cfgLabel = 'Delphi config (.delphi-config.json)';
4493
+ let settings;
4494
+ try {
4495
+ settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
4496
+ } catch (err) {
4497
+ add(label, 'SKIP', `${settingsFile} unparseable: ${err.message}`);
4498
+ return;
4499
+ }
4500
+ reportDshSelection(add, label, settingsFile, settings.subagentModelSelection);
4501
+ }
4502
+
4503
+ /**
4504
+ * Report whether the DSH switch is on AND properly provisioned.
4505
+ *
4506
+ * The switch shipping OFF is the platform default, not a defect: only an operator who
4507
+ * explicitly enables it and under-provisions `allowedModels` has a real
4508
+ * misconfiguration (#414 R1 FC-07). Collapsing those two into one FAIL is what told
4509
+ * working setups they were broken.
4510
+ */
4511
+ function reportDshSelection(add, label, settingsFile, selection) {
4512
+ const allowed = selection && Array.isArray(selection.allowedModels) ? selection.allowedModels : [];
4513
+ const ids = allowed.map((m) => (typeof m === 'string' ? m : m && m.id)).filter(Boolean);
4514
+ const distinct = new Set(ids).size;
4515
+
4516
+ if (!selection || selection.enabled !== true) {
4517
+ add(label, 'SKIP',
4518
+ `${settingsFile}: native model selection disabled (platform default) — the external channel is the contract path (#443)`);
4519
+ return;
4520
+ }
4521
+ if (distinct >= MIN_DISTINCT_MODELS) {
4522
+ add(label, 'PASS', `${settingsFile}: enabled, ${distinct} distinct allowed models`);
4523
+ return;
4524
+ }
4525
+ add(label, 'FAIL',
4526
+ `${settingsFile}: enabled but only ${distinct} distinct allowedModels (need >=${MIN_DISTINCT_MODELS}) — native channel unusable`);
4527
+ }
4528
+
4529
+ /**
4530
+ * Report seats that are not `local-*`, as a WARN.
4531
+ *
4532
+ * #574: the local-only rule is an operator preference (the 2026-10-03 quota burn),
4533
+ * so doctor surfaces the cost exposure without failing a deliberately hosted seat.
4534
+ * The HARD enforcement lives in Gate MW, which binds evidence to whatever the config
4535
+ * declares rather than to a `local-` prefix. `scripts/check_delphi_local_models.py`
4536
+ * holds the same rule with the same allowlist and exit code; reporting it here is
4537
+ * what finally gives that guard a caller instead of leaving it in its docstring.
4538
+ *
4539
+ * @param {Function} add
4540
+ * @param {Array<string|undefined>} models one per DELPHI_ROLES entry
4541
+ */
4542
+ function reportHostedSeats(add, models) {
4543
+ const label = 'Delphi local-model guard (#574)';
4544
+ const hosted = DELPHI_ROLES
4545
+ .map((role, i) => ({ role, model: models[i] }))
4546
+ .filter(({ model }) => model && !String(model).toLowerCase().startsWith('local-'));
4547
+
4548
+ if (hosted.length === 0) {
4549
+ add(label, 'PASS', `all ${DELPHI_ROLES.length} seats are local-*`);
4550
+ return;
4551
+ }
4552
+ add(label, 'WARN',
4553
+ `hosted (non local-*) seats: ${hosted.map(({ role, model }) => `${role}=${model}`).join(', ')} — `
4554
+ + 'local-only review is the standing rule; run: python scripts/check_delphi_local_models.py --probe');
4555
+ }
4556
+
4557
+ /**
4558
+ * Warn when a project config shadows a global one whose seats differ.
4559
+ *
4560
+ * #541: loaders fall back to the global config only on ENOENT, so this project file
4561
+ * always wins here. If the machine-wide config exists AND its seats differ, the
4562
+ * effective model mix depends on cwd -- the cross-project drift class behind the
4563
+ * 2026-10-03 quota burn. WARN, never FAIL: intentional overrides are legal, and only
4564
+ * the cwd-dependence is the hazard.
4565
+ *
4566
+ * Seat shape is object-keyed OR array in the wild (`delphi-config.ts` accepts both),
4567
+ * so both sides are normalized before comparing.
4568
+ *
4569
+ * @param {{add: Function, cfgPath: string, globalConfigPath: string, models: Array}} p
4570
+ */
4571
+ function reportConfigShadow(p) {
4572
+ const { add, cfgPath, globalConfigPath, models } = p;
4573
+ try {
4574
+ if (!fs.existsSync(globalConfigPath) || path.resolve(globalConfigPath) === path.resolve(cfgPath)) return;
4575
+
4576
+ const gRaw = JSON.parse(fs.readFileSync(globalConfigPath, 'utf8'));
4577
+ const gProfile = gRaw.profiles && gRaw.profiles[gRaw.active_profile || 'default'];
4578
+ const gExperts = (gProfile && gProfile.experts) || {};
4579
+ const pickExpert = (experts, role, idx) => {
4580
+ if (!experts) return null;
4581
+ if (Array.isArray(experts)) {
4582
+ const seat = experts.find((x) => x && x.role === role) || experts[idx];
4583
+ return (seat && seat.model) || null;
4584
+ }
4585
+ return (experts[role] && experts[role].model) || null;
4586
+ };
4587
+ const gModels = DELPHI_ROLES.map((role, i) => pickExpert(gExperts, role, i));
4588
+ // Compare only roles BOTH sides define: a role missing on one side is an
4589
+ // incomplete config (already FAILed above), not drift.
4590
+ const differing = DELPHI_ROLES.filter((role, i) => gModels[i] && models[i] && gModels[i] !== models[i]);
4591
+ if (differing.length === 0) return;
4592
+
4593
+ add('Delphi config shadow (#541)', 'WARN',
4594
+ `project config shadows ${globalConfigPath}; seats differ (${differing.join(', ')}) — `
4595
+ + 'reviews run from other directories will use different models');
4596
+ } catch {
4597
+ // A broken global config is not this check's failure mode; claiming nothing is
4598
+ // better than claiming agreement.
4599
+ }
4600
+ }
4601
+
4602
+ /**
4603
+ * Read the Delphi config and report whether a review can run from it.
4604
+ *
4605
+ * The file that was actually read is always named. With both scopes present a user
4606
+ * cannot otherwise tell which one the review will take, and that ambiguity is what
4607
+ * made #684 hard to see.
4608
+ *
4609
+ * @param {{add: Function, cfgPath: string, cfgLabel: string,
4610
+ * usingGlobalConfig: boolean, globalConfigPath: string}} p
4611
+ */
4612
+ function reportConfigFile(p) {
4613
+ const { add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath } = p;
3626
4614
  if (!fs.existsSync(cfgPath)) {
3627
4615
  add(cfgLabel, 'FAIL',
3628
4616
  `${cfgPath} not found (copy .delphi-config.json.example from the skill directory)`);
@@ -3634,22 +4622,9 @@ async function doctorDelphi(options = {}) {
3634
4622
  if (!profile) {
3635
4623
  add(cfgLabel, 'FAIL', `profile "${profileName}" not found`);
3636
4624
  } else {
3637
- const experts = profile.experts || {};
3638
- const models = roles.map((r) => experts[r] && experts[r].model);
3639
- const providers = profile.providers || {};
3640
- const missingRoles = roles.filter((r, i) => !models[i]);
3641
- const duplicates = models.filter((m, i) => m && models.indexOf(m) !== i);
3642
- const badProviders = roles.filter((r) => {
3643
- const e = experts[r];
3644
- return !e || !providers[e.provider]
3645
- || !providers[e.provider].base_url
3646
- || String(providers[e.provider].base_url).indexOf('http') !== 0;
3647
- });
3648
- if (missingRoles.length > 0 || duplicates.length > 0 || badProviders.length > 0) {
3649
- const problems = [];
3650
- if (missingRoles.length > 0) problems.push(`missing experts: ${missingRoles.join(', ')}`);
3651
- if (duplicates.length > 0) problems.push(`duplicate models: ${[...new Set(duplicates)].join(', ')}`);
3652
- if (badProviders.length > 0) problems.push(`unusable provider binding: ${badProviders.join(', ')}`);
4625
+ const models = DELPHI_ROLES.map((r) => (profile.experts || {})[r] && profile.experts[r].model);
4626
+ const problems = delphiModelProblems(profile);
4627
+ if (problems.length > 0) {
3653
4628
  add(cfgLabel, 'FAIL', problems.join('; '));
3654
4629
  } else {
3655
4630
  // Always name the file that was actually read. Without it a user with
@@ -3667,120 +4642,87 @@ async function doctorDelphi(options = {}) {
3667
4642
  // same allowlist and exit code; doctor reports it here so the guard
3668
4643
  // finally has a caller (`xp-gate doctor delphi`) instead of existing
3669
4644
  // only in its own docstring.
3670
- const hostedSeats = roles.filter((r) => {
3671
- const m = models[roles.indexOf(r)];
3672
- return m && !String(m).toLowerCase().startsWith('local-');
3673
- });
3674
- if (hostedSeats.length > 0) {
3675
- add('Delphi local-model guard (#574)', 'WARN',
3676
- `hosted (non local-*) seats: ${hostedSeats.map((r) => `${r}=${models[roles.indexOf(r)]}`).join(', ')} — `
3677
- + 'local-only review is the standing rule; run: python scripts/check_delphi_local_models.py --probe');
3678
- } else {
3679
- add('Delphi local-model guard (#574)', 'PASS', `all ${roles.length} seats are local-*`);
3680
- }
3681
- }
3682
- // #541 follow-up: shadow detection. Loaders fall back to the global
3683
- // config ONLY on ENOENT, so this project file always wins here. If the
3684
- // machine-wide config exists AND seats differ, the effective model mix
3685
- // depends on cwd — the cross-project drift class behind the 2026-10-03
3686
- // quota burn. Warn (intentional overrides are legal), never fail.
3687
- try {
3688
- if (fs.existsSync(globalConfigPath) && path.resolve(globalConfigPath) !== path.resolve(cfgPath)) {
3689
- const gRaw = JSON.parse(fs.readFileSync(globalConfigPath, 'utf8'));
3690
- const gProfileName = gRaw.active_profile || 'default';
3691
- const gProfile = gRaw.profiles && gRaw.profiles[gProfileName];
3692
- const gExperts = (gProfile && gProfile.experts) || {};
3693
- // Seat shape is object-keyed OR array in the wild (delphi-config.ts
3694
- // accepts both); normalize to a role->model map before comparing.
3695
- const pickExpert = (experts, role, idx) => {
3696
- if (!experts) return null;
3697
- if (Array.isArray(experts)) {
3698
- const e = experts.find((x) => x && x.role === role) || experts[idx];
3699
- return (e && e.model) || null;
3700
- }
3701
- return (experts[role] && experts[role].model) || null;
3702
- };
3703
- const gModels = roles.map((r, i) => pickExpert(gExperts, r, i));
3704
- // Compare only roles BOTH sides define: a role missing on one side
3705
- // is an incomplete config (check 5 already FAILs it), not drift.
3706
- const differing = roles.filter((r, i) => gModels[i] && models[i] && gModels[i] !== models[i]);
3707
- if (differing.length > 0) {
3708
- add('Delphi config shadow (#541)', 'WARN',
3709
- `project config shadows ${globalConfigPath}; seats differ (${differing.join(', ')}) — reviews run from other directories will use different models`);
3710
- }
3711
- }
3712
- } catch {
3713
- // A broken/unreadable global config is not this check's failure mode;
3714
- // silence here must not mask it elsewhere, so nothing is claimed.
4645
+ reportHostedSeats(add, models);
3715
4646
  }
4647
+ reportConfigShadow({ add, cfgPath, globalConfigPath, models });
3716
4648
  }
3717
4649
  } catch (err) {
3718
4650
  add(cfgLabel, 'FAIL', `unparseable: ${err.message}`);
3719
4651
  }
3720
4652
  }
3721
4653
 
3722
- // 6. Version consistency (#414 REQ-6): local files first. The npm-latest
3723
- // probe is opt-in (options.probeNpmLatest) or pre-supplied
3724
- // (options.npmLatest) — the doctor never blocks on the network, which is
3725
- // what an offline CI or restricted shell would otherwise hit (#414 R1 FC-03).
3726
- const localVersion = getCliVersionSafe();
3727
- let versionStatus = 'PASS';
3728
- let versionDetail = `xp-gate ${localVersion}`;
3729
- if (npmLatest === undefined && options.probeNpmLatest === true) {
3730
- try {
3731
- versionDetail += `; npm latest probe: ${execWithTimeout('npm view @boyingliu01/xp-gate version', 8000).trim()}`;
3732
- } catch {
3733
- versionStatus = 'SKIP';
3734
- versionDetail += '; npm latest probe unavailable (offline?) — skipped';
3735
- }
3736
- } else if (typeof npmLatest === 'string' && npmLatest !== localVersion) {
3737
- versionStatus = 'FAIL';
3738
- versionDetail += `; npm latest ${npmLatest} differs from local ${localVersion} — update (npm install -g @boyingliu01/xp-gate@latest) or verify which side is stale`;
3739
- } else if (npmLatest === null || options.probeNpmLatest !== true) {
3740
- versionDetail += '; npm latest probe skipped (pass --npm-check or options.probeNpmLatest to run it)';
3741
- }
3742
- add('Delphi version consistency', versionStatus, versionDetail);
4654
+ }
3743
4655
 
3744
- // 7. DSH native-channel readiness (#443 REQ-6): only meaningful when a DSH
3745
- // home exists. The two-layer switch (preset capability + host setting)
3746
- // defaults to disabled, and a review that assumes native will silently run
3747
- // three same-model seats.
3748
- const dshHome = path.join(HOME_DIR(), '.dsh');
3749
- if (!fs.existsSync(dshHome)) {
3750
- add('DSH subagent model selection', 'SKIP', `no ${dshHome} — not a DSH environment`);
3751
- } else {
3752
- const settingsCandidates = [
3753
- path.join(dshHome, 'settings.json'),
3754
- path.join(dshHome, 'settings', 'settings.json'),
3755
- path.join(dshHome, 'config.json'),
3756
- ];
3757
- const settingsFile = settingsCandidates.find((p) => fs.existsSync(p));
3758
- if (!settingsFile) {
3759
- add('DSH subagent model selection', 'FAIL',
3760
- `${dshHome} exists but no settings file found — subagent model selection defaults to disabled (#443)`);
3761
- } else {
3762
- try {
3763
- const settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
3764
- const selection = settings.subagentModelSelection;
3765
- const allowed = selection && Array.isArray(selection.allowedModels) ? selection.allowedModels : [];
3766
- const ids = allowed.map((m) => (typeof m === 'string' ? m : m && m.id)).filter(Boolean);
3767
- if (selection && selection.enabled === true && new Set(ids).size >= 3) {
3768
- add('DSH subagent model selection', 'PASS', `${settingsFile}: enabled, ${new Set(ids).size} distinct allowed models`);
3769
- } else if (selection && selection.enabled === true) {
3770
- add('DSH subagent model selection', 'FAIL',
3771
- `${settingsFile}: enabled but only ${new Set(ids).size} distinct allowedModels (need ≥3) — native channel unusable`);
3772
- } else {
3773
- // The switch shipping off is the platform default, not a defect:
3774
- // only an operator who explicitly enables it and under-provisions
3775
- // allowedModels has a real misconfiguration (#414 R1 FC-07).
3776
- add('DSH subagent model selection', 'SKIP',
3777
- `${settingsFile}: native model selection disabled (platform default) — the external channel is the contract path (#443)`);
3778
- }
3779
- } catch (err) {
3780
- add('DSH subagent model selection', 'SKIP', `${settingsFile} unparseable: ${err.message}`);
3781
- }
3782
- }
3783
- }
4656
+ async function checkDelphiConfigPing(add, options, globalConfigPath) {
4657
+ const { configPath, npmLatest } = options;
4658
+ // 5. Config ping: parseable, three distinct callable models. A duplicate
4659
+ // model here is a review that will BLOCK later — say so now.
4660
+ //
4661
+ // #684: resolve the SAME way the runner does. A project-local config wins; a
4662
+ // machine-level one under XDG_CONFIG_HOME (or ~/.config) is the documented
4663
+ // fallback, and a review keeps working on it. Checking only `cwd` reported
4664
+ // FAIL on the layout SKILL.md recommends and told the user to copy the example
4665
+ // into the project — manufacturing the drifted duplicate #541 warns about.
4666
+ //
4667
+ // An explicit `configPath` is an ANSWER, not a hint: a caller that names a
4668
+ // file means that file, so it disables the fallback. Otherwise a test (or a
4669
+ // caller) pinning an absent path silently reads the developer's real global
4670
+ // config and reports PASS — the same vacuous-pass shape this batch is fixing.
4671
+ const projectCfgPath = configPath
4672
+ || path.join(options.projectDir || process.cwd(), '.delphi-config.json');
4673
+ const usingGlobalConfig = !configPath
4674
+ && !fs.existsSync(projectCfgPath)
4675
+ && fs.existsSync(globalConfigPath);
4676
+ const cfgPath = usingGlobalConfig ? globalConfigPath : projectCfgPath;
4677
+ const cfgLabel = 'Delphi config (.delphi-config.json)';
4678
+ reportConfigFile({ add, cfgPath, cfgLabel, usingGlobalConfig, globalConfigPath });
4679
+
4680
+ // 6. Version consistency.
4681
+ await checkDelphiVersionConsistency(add, options, npmLatest);
4682
+
4683
+
4684
+ // 7. DSH native-channel readiness.
4685
+ checkDshChannelReadiness(add);
4686
+
4687
+ }
4688
+
4689
+ async function doctorDelphi(options = {}) {
4690
+ const { configPath, npmLatest } = options;
4691
+ // #541: the shadow check needs the loader's global fallback path. It is
4692
+ // injectable for tests; the default mirrors delphi-config.ts /
4693
+ // delphi-external-review.cjs resolution (XDG_CONFIG_HOME honored).
4694
+ const globalConfigPath = options.globalConfigPath
4695
+ || path.join(process.env.XDG_CONFIG_HOME || path.join(require('os').homedir(), '.config'), 'xp-gate', '.delphi-config.json');
4696
+ const checks = [];
4697
+ const add = (name, status, detail) => checks.push({ name, status, detail });
4698
+
4699
+ // 1. Node >= 18: the runner gates on it and exits 1 mid-review otherwise.
4700
+ const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
4701
+ add(`Node.js >= ${MIN_NODE_MAJOR}`, nodeMajor >= MIN_NODE_MAJOR ? 'PASS' : 'FAIL',
4702
+ `current: ${process.versions.node}`);
4703
+
4704
+ // 2. Qoder agent bindings.
4705
+ checkDelphiAgentBindings(add, options);
4706
+
4707
+ // 3. Skill install parity. It also resolves the installed skill dir, which
4708
+ // the runner-locate check below needs.
4709
+ const installedSkillDir = checkSkillInstallParity(add, options);
4710
+
4711
+ // 4. Runner script locate: the runner must be findable from the places a
4712
+ // review actually starts.
4713
+ const runnerCandidates = [
4714
+ ['package bundle', path.join(PKG_DIR, 'scripts', 'delphi-external-review.cjs')],
4715
+ ['project', path.join(process.cwd(), 'scripts', 'delphi-external-review.cjs')],
4716
+ ['installed skill', path.join(installedSkillDir, 'scripts', 'delphi-external-review.cjs')],
4717
+ ];
4718
+ const foundRunner = runnerCandidates.filter(([, p]) => fs.existsSync(p));
4719
+ add('delphi-external-review runner', foundRunner.length > 0 ? 'PASS' : 'FAIL',
4720
+ foundRunner.length > 0
4721
+ ? foundRunner.map(([label, p]) => `${label}: ${p}`).join('; ')
4722
+ : 'not found in package bundle, project, or installed skill');
4723
+
4724
+ // 5. Config ping.
4725
+ await checkDelphiConfigPing(add, options, globalConfigPath);
3784
4726
 
3785
4727
  for (const check of checks) {
3786
4728
  const mark = check.status === 'PASS' ? '✓' : check.status === 'SKIP' ? '○' : check.status === 'WARN' ? '⚠' : '✗';
@@ -3848,6 +4790,33 @@ function platformTag(skillDir) {
3848
4790
  * Files in `skillDir` that are missing or differ from the bundle.
3849
4791
  * @returns {string[]} `rel: reason` entries; empty when the copy is clean
3850
4792
  */
4793
+ /**
4794
+ * Files where an installed skill copy differs from the bundle.
4795
+ *
4796
+ * An unreadable file is reported as `unreadable` rather than skipped: a copy we
4797
+ * cannot check is not a copy we can call matching, and silence here would let a
4798
+ * permissions problem pass as parity.
4799
+ */
4800
+ /**
4801
+ * SHA-256 of a file, or a thrown error naming the path.
4802
+ *
4803
+ * A digest is used to compare two copies; a read failure must not yield a digest
4804
+ * that happens to differ, because "cannot read" and "differs" need different
4805
+ * repairs.
4806
+ *
4807
+ * @param {string} filePath
4808
+ * @returns {string}
4809
+ */
4810
+ function fileSha256(filePath) {
4811
+ let content;
4812
+ try {
4813
+ content = fs.readFileSync(filePath);
4814
+ } catch (err) {
4815
+ throw new Error(`cannot hash ${filePath}: ${err.message}`);
4816
+ }
4817
+ return require('crypto').createHash('sha256').update(content).digest('hex');
4818
+ }
4819
+
3851
4820
  function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
3852
4821
  const drifted = [];
3853
4822
  for (const rel of bundledFiles) {
@@ -3855,15 +4824,22 @@ function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
3855
4824
  const bundledPath = path.join(bundledSkillDir, rel);
3856
4825
  if (!fs.existsSync(installedPath)) {
3857
4826
  drifted.push(`${rel}: missing`);
3858
- } else if (sha256(installedPath) !== sha256(bundledPath)) {
3859
- drifted.push(`${rel}: differs`);
4827
+ continue;
4828
+ }
4829
+ try {
4830
+ if (sha256(installedPath) !== sha256(bundledPath)) drifted.push(`${rel}: differs`);
4831
+ } catch {
4832
+ drifted.push(`${rel}: unreadable`);
3860
4833
  }
3861
4834
  }
3862
4835
  return drifted;
3863
4836
  }
3864
4837
 
3865
4838
  module.exports = {
3866
- doctor, doctorDelphi, isXpGateFile, SIGNATURES, getHookSignatures, isXpGateHookContent,
4839
+ reportUnreadablePath, reportStalePath, reportSyncResult,
4840
+ runHookAndModuleSync, staleSyncEntries,
4841
+ planStaleHookSync, reportBlockedHookSync, refreshSafeHooks,
4842
+ doctor, doctorDelphi, isXpGateFile, diagnoseLanguageTools, diagnoseCliTools, SIGNATURES, getHookSignatures, isXpGateHookContent,
3867
4843
  fixVersionMismatch,
3868
4844
  fixTemplateDirMismatch,
3869
4845
  fixMissingHooks,