@boyingliu01/xp-gate 0.38.126 → 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 (421) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +13 -2
  3. package/adapters/python.sh +36 -38
  4. package/bin/xp-gate.js +11 -0
  5. package/build-integrity/gate-10-lines.ts +98 -0
  6. package/build-integrity/gate-10.ts +98 -109
  7. package/build-integrity/quote-masker.ts +17 -3
  8. package/gate-3.sh +13 -2
  9. package/gates/common-process.ts +116 -34
  10. package/gates/common.ts +51 -15
  11. package/gates/gate-3.ts +166 -61
  12. package/gates/gate-8.ts +76 -24
  13. package/gates/gate-9.ts +276 -82
  14. package/gates/pbt-detect.ts +70 -39
  15. package/gates/python-health.ts +236 -98
  16. package/gates/test-layers.ts +103 -30
  17. package/hooks/gate-3.sh +13 -2
  18. package/hooks/gate-entries/gate-1-entry.sh +10 -1
  19. package/hooks/gate-entries/gate-5-entry.sh +5 -1
  20. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  21. package/hooks/pre-commit +52 -0
  22. package/hooks/pre-push +54 -3
  23. package/lib/agent-runtime-journal.js +104 -37
  24. package/lib/arch.js +6 -0
  25. package/lib/baseline.js +329 -201
  26. package/lib/check.js +38 -2
  27. package/lib/doctor-constants.js +43 -0
  28. package/lib/doctor.js +2008 -1001
  29. package/lib/flaky.js +178 -79
  30. package/lib/gate-runner.js +110 -63
  31. package/lib/init.js +6 -0
  32. package/lib/language-capability-surfaces.js +5 -2
  33. package/lib/language-registry.js +608 -0
  34. package/lib/language-tools.js +487 -1018
  35. package/lib/phase-transition.js +646 -446
  36. package/lib/prepush-evidence.js +174 -0
  37. package/lib/sprint-audit.js +52 -22
  38. package/lib/sprint-discovery.js +66 -35
  39. package/lib/sprint-format.js +114 -0
  40. package/lib/sprint-init.js +372 -118
  41. package/lib/sprint-status.js +134 -90
  42. package/lib/star-notice.js +346 -0
  43. package/lib/tool-display.js +52 -0
  44. package/lib/tool-install.js +179 -0
  45. package/lib/uninstall.js +331 -188
  46. package/mock-policy/gate-m3.ts +74 -23
  47. package/mock-policy/mock-decision-engine.ts +21 -7
  48. package/mock-policy/scope-scanner.ts +128 -69
  49. package/mutation/detect-ai-test.ts +20 -12
  50. package/mutation/gate-m.ts +6 -2
  51. package/mutation/init-baseline.ts +49 -13
  52. package/mutation/runners/go-mutant-runner.ts +7 -49
  53. package/mutation/runners/gremlins-runner.ts +53 -18
  54. package/mutation/runners/mutmut-runner.ts +455 -163
  55. package/mutation/runners/pitest-runner.ts +85 -131
  56. package/mutation/runners/spawn-with-capture.ts +304 -0
  57. package/mutation/runners/stryker-runner.ts +14 -55
  58. package/mutation/update-baseline.ts +25 -18
  59. package/package.json +20 -8
  60. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  61. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  62. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  63. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  64. package/plugins/claude-code/skills/reinstall-xp-gate/.architecture-skip +8 -0
  65. package/plugins/claude-code/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  66. package/plugins/claude-code/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  67. package/plugins/claude-code/skills/reinstall-xp-gate/LICENSE +21 -0
  68. package/plugins/claude-code/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  69. package/plugins/claude-code/skills/reinstall-xp-gate/README.md +167 -0
  70. package/plugins/claude-code/skills/reinstall-xp-gate/SKILL.md +271 -0
  71. package/plugins/claude-code/skills/reinstall-xp-gate/TODO.md +253 -0
  72. package/plugins/claude-code/skills/reinstall-xp-gate/VERSION +1 -0
  73. package/plugins/claude-code/skills/reinstall-xp-gate/package.json +28 -0
  74. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  75. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  76. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  77. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  78. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  79. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  80. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  81. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  82. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  83. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  84. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  85. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  86. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  87. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  88. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  89. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  90. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  91. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  92. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  93. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  94. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  95. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  96. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  97. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  98. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  99. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  100. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  101. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  102. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  103. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  104. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  105. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  106. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  107. package/plugins/claude-code/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  108. package/plugins/claude-code/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  109. package/plugins/claude-code/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  110. package/plugins/claude-code/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  111. package/plugins/claude-code/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  112. package/plugins/claude-code/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  113. package/plugins/claude-code/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  114. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  115. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  116. package/plugins/claude-code/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  117. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  118. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  119. package/plugins/claude-code/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  120. package/plugins/claude-code/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  121. package/plugins/claude-code/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  122. package/plugins/claude-code/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  123. package/plugins/claude-code/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  124. package/plugins/claude-code/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  125. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  126. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  127. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  128. package/plugins/claude-code/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  129. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  130. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  131. package/plugins/dsh/package.json +1 -1
  132. package/plugins/dsh/scripts/prepack.cjs +43 -18
  133. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  134. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  135. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  136. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  137. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  138. package/plugins/opencode/index.ts +337 -123
  139. package/plugins/opencode/package.json +1 -1
  140. package/plugins/opencode/scripts/prepack.cjs +41 -16
  141. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  142. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  143. package/plugins/opencode/skills/reinstall-xp-gate/.architecture-skip +8 -0
  144. package/plugins/opencode/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  145. package/plugins/opencode/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  146. package/plugins/opencode/skills/reinstall-xp-gate/LICENSE +21 -0
  147. package/plugins/opencode/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  148. package/plugins/opencode/skills/reinstall-xp-gate/README.md +167 -0
  149. package/plugins/opencode/skills/reinstall-xp-gate/SKILL.md +271 -0
  150. package/plugins/opencode/skills/reinstall-xp-gate/TODO.md +253 -0
  151. package/plugins/opencode/skills/reinstall-xp-gate/VERSION +1 -0
  152. package/plugins/opencode/skills/reinstall-xp-gate/package.json +28 -0
  153. package/plugins/opencode/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  154. package/plugins/opencode/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  155. package/plugins/opencode/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  156. package/plugins/opencode/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  157. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  158. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  159. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  160. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  161. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  162. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  163. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  164. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  165. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  166. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  167. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  168. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  169. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  170. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  171. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  172. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  173. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  174. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  175. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  176. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  177. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  178. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  179. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  180. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  181. package/plugins/opencode/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  182. package/plugins/opencode/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  183. package/plugins/opencode/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  184. package/plugins/opencode/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  185. package/plugins/opencode/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  186. package/plugins/opencode/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  187. package/plugins/opencode/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  188. package/plugins/opencode/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  189. package/plugins/opencode/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  190. package/plugins/opencode/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  191. package/plugins/opencode/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  192. package/plugins/opencode/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  193. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  194. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  195. package/plugins/opencode/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  196. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  197. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  198. package/plugins/opencode/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  199. package/plugins/opencode/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  200. package/plugins/opencode/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  201. package/plugins/opencode/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  202. package/plugins/opencode/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  203. package/plugins/opencode/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  204. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  205. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  206. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  207. package/plugins/opencode/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  208. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  209. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  210. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  211. package/plugins/qoder/plugin.json +1 -1
  212. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  213. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  214. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  215. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  216. package/plugins/shared/README.md +3 -0
  217. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  218. package/principles/adapters/control-nesting.ts +481 -168
  219. package/principles/adapters/cpp.ts +61 -22
  220. package/principles/adapters/csharp.ts +183 -66
  221. package/principles/adapters/dart.ts +11 -1
  222. package/principles/adapters/duplication.ts +49 -16
  223. package/principles/adapters/import-clause.ts +62 -15
  224. package/principles/adapters/java.ts +199 -70
  225. package/principles/adapters/line-comment.ts +18 -0
  226. package/principles/adapters/member-scan.ts +50 -8
  227. package/principles/adapters/php.ts +232 -103
  228. package/principles/adapters/python.ts +25 -18
  229. package/principles/adapters/quote-state.ts +21 -8
  230. package/principles/adapters/typescript-mask.ts +276 -0
  231. package/principles/adapters/typescript.ts +206 -200
  232. package/principles/analyzer.ts +16 -6
  233. package/principles/baseline-prune.ts +18 -8
  234. package/principles/baseline.ts +28 -11
  235. package/principles/boy-scout-usage.ts +26 -0
  236. package/principles/boy-scout.ts +261 -180
  237. package/principles/config.ts +183 -57
  238. package/principles/direct-execution.ts +24 -12
  239. package/principles/lint-baseline.ts +235 -122
  240. package/principles/rules/arch/dependency.ts +34 -25
  241. package/principles/rules/arch/shared.ts +24 -20
  242. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  243. package/principles/rules/clean-code/god-class.ts +67 -41
  244. package/principles/rules/clean-code/large-file.ts +30 -23
  245. package/principles/rules/clean-code/long-function.ts +51 -37
  246. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  247. package/principles/rules/clean-code/many-exports.ts +46 -29
  248. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  249. package/principles/rules/clean-code/too-many-params.ts +41 -22
  250. package/principles/rules/function-source.ts +62 -0
  251. package/principles/rules/solid/dip.ts +10 -6
  252. package/principles/rules/solid/isp.ts +64 -24
  253. package/principles/rules/solid/lsp.ts +66 -18
  254. package/principles/rules/solid/ocp.ts +29 -13
  255. package/principles/rules/solid/srp.ts +34 -18
  256. package/principles/warnings-count.ts +43 -0
  257. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  258. package/scripts/delphi-config-read.cjs +245 -0
  259. package/scripts/delphi-external-review.cjs +410 -585
  260. package/scripts/delphi-json-extract.cjs +108 -0
  261. package/scripts/delphi-model-validation.cjs +297 -0
  262. package/scripts/delphi-prompts.cjs +55 -0
  263. package/scripts/delphi-repo-tools.cjs +273 -0
  264. package/scripts/delphi-seat-calibration.cjs +204 -0
  265. package/scripts/run-bats-ci.cjs +240 -97
  266. package/scripts/sync-package-content.js +18 -2
  267. package/skills/delphi-review/.delphi-config.json.example +6 -11
  268. package/skills/delphi-review/AGENTS.md +1 -1
  269. package/skills/sprint-flow/AGENTS.md +1 -1
  270. package/skills/test-specification-alignment/AGENTS.md +1 -1
  271. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  272. package/lib/__tests__/arch-config-template.test.js +0 -190
  273. package/lib/__tests__/arch.test.js +0 -430
  274. package/lib/__tests__/assertion-debt.test.js +0 -99
  275. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  276. package/lib/__tests__/audit-log.test.ts +0 -107
  277. package/lib/__tests__/audit-skip-reasons.test.ts +0 -143
  278. package/lib/__tests__/baseline-completeness.test.js +0 -264
  279. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  280. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  281. package/lib/__tests__/baseline.test.js +0 -212
  282. package/lib/__tests__/bootstrap.test.js +0 -60
  283. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  284. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  285. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  286. package/lib/__tests__/check-changed-brief.test.js +0 -63
  287. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  288. package/lib/__tests__/check-single-file.test.js +0 -114
  289. package/lib/__tests__/check-tools-list.test.js +0 -155
  290. package/lib/__tests__/check-version.test.js +0 -463
  291. package/lib/__tests__/coverage-scope.test.js +0 -140
  292. package/lib/__tests__/coverage-threshold.test.js +0 -80
  293. package/lib/__tests__/crap-cli.test.js +0 -87
  294. package/lib/__tests__/crap.test.js +0 -494
  295. package/lib/__tests__/debt-classify.test.js +0 -78
  296. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  297. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  298. package/lib/__tests__/delphi-channel.test.js +0 -109
  299. package/lib/__tests__/delphi-setup.test.js +0 -203
  300. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  301. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  302. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  303. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  304. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  305. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  306. package/lib/__tests__/deploy-manifest.test.js +0 -97
  307. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  308. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  309. package/lib/__tests__/detect-deps.test.js +0 -655
  310. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  311. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  312. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  313. package/lib/__tests__/doctor-brief.test.js +0 -59
  314. package/lib/__tests__/doctor-delphi.test.js +0 -628
  315. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  316. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  317. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  318. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  319. package/lib/__tests__/doctor-helpers.test.js +0 -139
  320. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  321. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  322. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  323. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  324. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  325. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  326. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  327. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  328. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  329. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  330. package/lib/__tests__/doctor-tool-delegation.test.js +0 -156
  331. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  332. package/lib/__tests__/doctor.test.js +0 -1320
  333. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  334. package/lib/__tests__/flaky.test.js +0 -128
  335. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  336. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  337. package/lib/__tests__/gate-audit.test.ts +0 -440
  338. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  339. package/lib/__tests__/gate-coverage.test.js +0 -204
  340. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  341. package/lib/__tests__/gate-numbering.test.js +0 -79
  342. package/lib/__tests__/gate-rules.test.js +0 -58
  343. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  344. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  345. package/lib/__tests__/gate-runner.test.js +0 -371
  346. package/lib/__tests__/gate2-verdict.test.js +0 -183
  347. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  348. package/lib/__tests__/hook-health-path.test.js +0 -109
  349. package/lib/__tests__/hook-health.test.js +0 -85
  350. package/lib/__tests__/init-gitignore.test.js +0 -204
  351. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  352. package/lib/__tests__/init.test.js +0 -530
  353. package/lib/__tests__/install-cmd.test.js +0 -6
  354. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  355. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  356. package/lib/__tests__/install-skill.test.js +0 -416
  357. package/lib/__tests__/install-tools-repair.test.js +0 -263
  358. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  359. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  360. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  361. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  362. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  363. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  364. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  365. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  366. package/lib/__tests__/language-capability.test.js +0 -318
  367. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  368. package/lib/__tests__/language-tools-detect.test.js +0 -301
  369. package/lib/__tests__/migrate.test.js +0 -232
  370. package/lib/__tests__/mirror-manifest.test.js +0 -64
  371. package/lib/__tests__/mirror-sync.test.js +0 -803
  372. package/lib/__tests__/next-sprint.test.js +0 -231
  373. package/lib/__tests__/npm-package.test.js +0 -140
  374. package/lib/__tests__/phase-transition.test.js +0 -1136
  375. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  376. package/lib/__tests__/principles-directory.test.js +0 -87
  377. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  378. package/lib/__tests__/retro-gate-m.test.js +0 -144
  379. package/lib/__tests__/retro.test.js +0 -131
  380. package/lib/__tests__/rework.test.js +0 -127
  381. package/lib/__tests__/rollback.test.js +0 -183
  382. package/lib/__tests__/runtime-journal.test.js +0 -164
  383. package/lib/__tests__/sastd-client.test.js +0 -514
  384. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  385. package/lib/__tests__/shared-paths.test.js +0 -130
  386. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  387. package/lib/__tests__/shared-utils.test.js +0 -180
  388. package/lib/__tests__/skill-flags.test.js +0 -48
  389. package/lib/__tests__/slo.test.js +0 -89
  390. package/lib/__tests__/sprint-audit.test.js +0 -207
  391. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  392. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  393. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  394. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  395. package/lib/__tests__/sprint-status.test.js +0 -193
  396. package/lib/__tests__/sprint-status.test.ts +0 -213
  397. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  398. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  399. package/lib/__tests__/test-alignment.test.ts +0 -853
  400. package/lib/__tests__/tool-audit-collect.test.js +0 -184
  401. package/lib/__tests__/tool-audit-fixtures.js +0 -87
  402. package/lib/__tests__/tool-audit-latest.test.js +0 -84
  403. package/lib/__tests__/tool-audit.test.js +0 -428
  404. package/lib/__tests__/tsconfig.json +0 -8
  405. package/lib/__tests__/tsx-resolution.test.js +0 -89
  406. package/lib/__tests__/ui-detector.test.ts +0 -459
  407. package/lib/__tests__/ui-review.test.ts +0 -132
  408. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  409. package/lib/__tests__/uninstall-skill.test.js +0 -189
  410. package/lib/__tests__/uninstall.test.js +0 -717
  411. package/lib/__tests__/update-hooks.test.js +0 -737
  412. package/lib/__tests__/update-skill-flags.test.js +0 -78
  413. package/lib/__tests__/update-skill.test.js +0 -644
  414. package/lib/__tests__/upgrade-exec.test.js +0 -273
  415. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  416. package/lib/__tests__/upgrade.test.js +0 -78
  417. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  418. package/lib/check-alignment-runner.cjs +0 -97
  419. package/lib/coverage-total.sh +0 -92
  420. package/lib/layer-baseline.cjs +0 -94
  421. package/lib/mattpocock-license-verdict.json +0 -7
package/lib/doctor.js CHANGED
@@ -16,10 +16,15 @@ 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');
25
30
  // Doctor's tool section is built from the shared audit, so the validity /
@@ -48,7 +53,6 @@ const {
48
53
  } = require('./doctor-tui.js');
49
54
 
50
55
  // npm package source dir (template hooks/adapters)
51
- const PKG_DIR = path.dirname(__dirname);
52
56
 
53
57
  /**
54
58
  * Read the package version from the installed package.json.
@@ -211,7 +215,7 @@ async function execWithTimeout(cmd, opts = {}) {
211
215
  // tool as exit 1 + "'x' is not recognized"), and re-running it would only
212
216
  // burn time, so that path still returns null immediately.
213
217
  const { attempts, ...execOpts } = opts;
214
- const maxAttempts = process.platform === 'win32' ? (attempts || 3) : 1;
218
+ const maxAttempts = process.platform === 'win32' ? (attempts || WINDOWS_EXEC_ATTEMPTS) : 1;
215
219
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
216
220
  try {
217
221
  const { stdout, stderr } = await execAsync(cmd, {
@@ -224,7 +228,7 @@ async function execWithTimeout(cmd, opts = {}) {
224
228
  // existing null check ("probe produced nothing") applies — an empty
225
229
  // non-null result would read as a present tool with no version.
226
230
  if (attempt + 1 < maxAttempts) {
227
- await new Promise(resolve => setTimeout(resolve, 50));
231
+ await new Promise(resolve => setTimeout(resolve, EXEC_RETRY_DELAY_MS));
228
232
  continue;
229
233
  }
230
234
  return null;
@@ -359,8 +363,19 @@ function getConfig() {
359
363
  }
360
364
  }
361
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
+ */
362
372
  function saveConfig(config) {
363
- 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
+ }
364
379
  }
365
380
 
366
381
  async function getGitDir() {
@@ -674,26 +689,21 @@ const HOOK_SUPPORT_FILES = [
674
689
  * @param {{repoRoot?: string, repoHooks?: string, installedHooks?: string}} [ctx]
675
690
  * @returns {{checks: Array<{name: string, status: string, detail: string}>, issues: number}}
676
691
  */
677
- function diagnoseHookDrift(ctx = {}) {
678
- 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) {
679
706
  let issues = 0;
680
-
681
- // XP_GATE_REPO_ROOT lets a caller (or a test) name the canonical repo
682
- // explicitly instead of inferring it from the process cwd.
683
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
684
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
685
- const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
686
-
687
- // Nothing to compare when the project carries no canonical *hook* source, or
688
- // when no global copy exists at all. Both must stay completely silent.
689
- //
690
- // A `githooks/` directory holding only `adapters/` is NOT a hook source of
691
- // truth -- consumer projects get that layout from `xp-gate init`, and the
692
- // adapters there are unrelated to which hook file executes.
693
- if (!hasCanonicalHooks(repoHooks) || !fs.existsSync(installedHooks)) {
694
- return { checks, issues };
695
- }
696
-
697
707
  for (const name of DRIFT_COMPARED_HOOKS) {
698
708
  const repoFile = path.join(repoHooks, name);
699
709
  const installedFile = path.join(installedHooks, name);
@@ -724,43 +734,81 @@ function diagnoseHookDrift(ctx = {}) {
724
734
  });
725
735
  issues++;
726
736
  }
737
+ return issues;
738
+ }
727
739
 
728
- // lib/ shared libraries: pre-commit sources lib/*.sh at runtime, so a missing
729
- // 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) {
730
752
  const repoLib = path.join(repoHooks, 'lib');
731
753
  const installedLib = path.join(installedHooks, 'lib');
732
- if (fs.existsSync(repoLib) && fs.statSync(repoLib).isDirectory()) {
733
- let libEntries = [];
734
- try {
735
- libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
736
- } catch {
737
- libEntries = [];
738
- }
739
- for (const entry of libEntries) {
740
- if (!entry.isFile()) continue;
741
- const rel = `lib/${entry.name}`;
742
- const repoFile = path.join(repoLib, entry.name);
743
- const installedFile = path.join(installedLib, entry.name);
744
- const label = `Hook drift: ${rel}`;
745
- if (!fs.existsSync(installedFile)) {
746
- checks.push({
747
- name: label,
748
- status: 'FAIL',
749
- detail: 'installed lib/ copy is missing (hooks source lib/ at runtime)',
750
- });
751
- issues++;
752
- } else if (!filesAreIdentical(repoFile, installedFile)) {
753
- checks.push({
754
- name: label,
755
- status: 'FAIL',
756
- detail: 'installed lib/ copy differs from githooks/lib/',
757
- });
758
- issues++;
759
- } else {
760
- checks.push({ name: label, status: 'PASS', detail: 'Installed copy matches githooks/' });
761
- }
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/' });
762
785
  }
763
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);
764
812
 
765
813
  return { checks, issues };
766
814
  }
@@ -915,50 +963,115 @@ function readPair(repoFile, installedFile) {
915
963
  * import the .ts module). Grandfathers everything before AUDIT_LEDGER_SINCE;
916
964
  * only NEW implausible durations or unattributed commits count as issues.
917
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
+
918
981
  const AUDIT_LEDGER_SINCE = '2026-10-30T00:00:00.000Z';
919
- const AUDIT_MAX_PLAUSIBLE_MS = 6 * 60 * 60 * 1000;
982
+ const AUDIT_MAX_PLAUSIBLE_MS = AUDIT_MAX_PLAUSIBLE_HOURS * 60 * 60 * 1000;
920
983
 
921
984
  function diagnoseAuditLedger(ctx = {}) {
922
- const checks = [];
923
- let issues = 0;
924
985
  const repoRoot = ctx.repoRoot || process.cwd();
925
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';
926
1006
  if (!fs.existsSync(logPath)) {
927
- checks.push({ name: 'Audit ledger', status: 'SKIP', detail: 'no .xp-gate/audit.jsonl' });
928
- return { checks, issues };
1007
+ return { verdict: { name, status: 'SKIP', detail: 'no .xp-gate/audit.jsonl' } };
929
1008
  }
930
- let entries;
931
1009
  try {
932
- 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 };
933
1015
  } catch (err) {
934
- checks.push({ name: 'Audit ledger', status: 'WARN', detail: `unreadable: ${err.message}` });
935
- return { checks, issues };
936
- }
937
- let implausible = 0;
938
- let missingCommit = 0;
939
- let considered = 0;
940
- for (const e of entries) {
941
- if (typeof e.timestamp === 'string' && e.timestamp < AUDIT_LEDGER_SINCE) continue;
942
- considered += 1;
943
- if (typeof e.duration_ms === 'number'
944
- && (!Number.isFinite(e.duration_ms) || e.duration_ms < 0 || e.duration_ms > AUDIT_MAX_PLAUSIBLE_MS)) {
945
- implausible += 1;
946
- }
947
- if (!e.commit_hash || e.commit_hash === 'unknown') missingCommit += 1;
948
- }
949
- const total = implausible + missingCommit;
950
- if (total > 0) {
951
- checks.push({
952
- name: 'Audit ledger',
953
- status: 'WARN',
954
- detail: `${total} anomal${total === 1 ? 'y' : 'ies'} since ${AUDIT_LEDGER_SINCE} (${implausible} implausible duration, ${missingCommit} unattributed) — run: xp-gate audit --check`,
955
- });
956
- // WARN, not FAIL: telemetry integrity is not a blocking gate, but it must
957
- // be visible. Kept at 0 issues so it never inflates the FAIL count.
958
- } else {
959
- 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}` } };
960
1017
  }
961
- 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
+ };
962
1075
  }
963
1076
 
964
1077
  /**
@@ -1003,31 +1116,30 @@ function diagnoseFlakyQuarantine(ctx = {}) {
1003
1116
  return { checks, issues };
1004
1117
  }
1005
1118
 
1006
- function diagnoseModuleDrift(ctx = {}) {
1007
- 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) {
1008
1142
  let issues = 0;
1009
-
1010
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
1011
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
1012
-
1013
- // Silent without a canonical repo source to compare against: consumer
1014
- // projects have no `githooks/` root of truth, only what was installed.
1015
- if (!hasCanonicalHooks(repoHooks)) {
1016
- return { checks, issues };
1017
- }
1018
-
1019
- const dirs = resolveExecutedModuleDirs({
1020
- globalAdapterDir: ctx.globalAdapterDir || ctx.installedAdapters,
1021
- projectGithooks: ctx.projectGithooks || repoHooks,
1022
- scriptDir: ctx.scriptDir,
1023
- });
1024
-
1025
- // Copies the hook never resolves to, occupying the lookup positions it does
1026
- // resolve through. They are not drift -- nothing executes them -- but they are
1027
- // how #500 reproduces: the next install order shift, or a move to project
1028
- // mode, promotes one silently. Report with the absolute path so the developer
1029
- // can judge; do not count, because no shipped command removes them (#495 R2).
1030
- const executedFor = new Map();
1031
1143
  for (const name of repoModuleNames(repoHooks)) {
1032
1144
  const source = repoModuleSource(repoHooks, name);
1033
1145
  if (!source) continue;
@@ -1068,6 +1180,36 @@ function diagnoseModuleDrift(ctx = {}) {
1068
1180
  checks.push({ name: label, status: 'FAIL', detail: `${driftDetail}${hint}` });
1069
1181
  issues++;
1070
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);
1071
1213
 
1072
1214
  for (const [name, file] of nonExecutedCopies(dirs, executedFor)) {
1073
1215
  checks.push({
@@ -1209,6 +1351,52 @@ function moduleDriftDetail(repoText, installedText) {
1209
1351
  * @param {{repoRoot?: string, repoHooks?: string, installedAdapters?: string, force?: boolean}} [ctx]
1210
1352
  * @returns {{synced: string[], skipped: string[], refused: Array<{name: string, repoOnly: number, installedOnly: number}>, errors: string[], installedAdapters: string}}
1211
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
+
1212
1400
  function syncModulesFromRepo(ctx = {}) {
1213
1401
  const synced = [];
1214
1402
  const skipped = [];
@@ -1237,37 +1425,7 @@ function syncModulesFromRepo(ctx = {}) {
1237
1425
  const installedAdapters = dirs.globalAdapterDir;
1238
1426
 
1239
1427
  for (const name of repoModuleNames(repoHooks)) {
1240
- const source = repoModuleSource(repoHooks, name);
1241
- if (!source) continue;
1242
- const target = executedModulePath(name, dirs);
1243
- if (!target) continue; // nothing executes this module; residue is not this command's business
1244
- if (pathsEquivalent(source, target)) {
1245
- skipped.push(name);
1246
- continue;
1247
- }
1248
- if (filesAreIdentical(source, target)) {
1249
- skipped.push(name);
1250
- continue;
1251
- }
1252
-
1253
- const decision = copyGuardDecision(source, target, !!ctx.force);
1254
- // Formatting-only: nothing to repair, and rewriting the file would churn it.
1255
- if (!decision.refuse && !decision.forced && decision.repoOnly === 0 && decision.installedOnly === 0) {
1256
- skipped.push(name);
1257
- continue;
1258
- }
1259
- if (decision.refuse) {
1260
- refused.push({ name, repoOnly: decision.repoOnly, installedOnly: decision.installedOnly, unknown: decision.unknown, target });
1261
- continue;
1262
- }
1263
-
1264
- try {
1265
- fs.copyFileSync(source, target);
1266
- fs.chmodSync(target, 0o755);
1267
- synced.push(name);
1268
- } catch (err) {
1269
- errors.push(`${name}: ${err.message}`);
1270
- }
1428
+ syncOneModule({ name, repoHooks, dirs, force: !!ctx.force, synced, skipped, refused, errors });
1271
1429
  }
1272
1430
 
1273
1431
  return { synced, skipped, refused, errors, installedAdapters, dirs, sourceMissing: false };
@@ -1681,160 +1839,216 @@ function appendDeployLogEntry(logPath, entry) {
1681
1839
  *
1682
1840
  * @returns {{synced: string[], skipped: string[], refused: Array<{name: string, repoOnly: number, installedOnly: number}>, errors: string[], installedHooks: string, backups: string[]}}
1683
1841
  */
1684
- function syncGlobalHooksFromRepo(ctx = {}) {
1685
- const repoRoot = ctx.repoRoot || process.env.XP_GATE_REPO_ROOT || process.cwd();
1686
- const repoHooks = ctx.repoHooks || path.join(repoRoot, 'githooks');
1687
- const installedHooks = ctx.installedHooks || GLOBAL_HOOKS_DIR();
1688
- // #583: the version that performs the overwrite is part of the record. Read the
1689
- // repo's VERSION beside the hooks, so the log answers "which release did this"
1690
- // without the caller having to remember to pass it.
1691
- const version = ctx.version
1692
- || readVersionFile(path.join(repoRoot, 'VERSION'))
1693
- || 'unknown';
1694
-
1695
- const synced = [];
1696
- const skipped = [];
1697
- const refused = [];
1698
- const errors = [];
1699
- const backups = [];
1700
- const backupsDir = path.join(installedHooks, 'backups');
1701
- const deployLog = path.join(installedHooks, 'deploy.log');
1702
-
1703
- if (!fs.existsSync(repoHooks)) {
1704
- errors.push(`no githooks/ directory at ${repoHooks}`);
1705
- return { synced, skipped, refused, errors, installedHooks, backups };
1706
- }
1707
-
1708
- if (!hasCanonicalHooks(repoHooks)) {
1709
- errors.push(`no hook files in ${repoHooks} (only adapters?) -- nothing to sync from`);
1710
- return { synced, skipped, refused, errors, installedHooks, backups };
1711
- }
1712
-
1713
- try {
1714
- fs.mkdirSync(installedHooks, { recursive: true });
1715
- } catch (err) {
1716
- errors.push(`cannot create ${installedHooks}: ${err.message}`);
1717
- return { synced, skipped, refused, errors, installedHooks, backups };
1718
- }
1719
-
1720
- for (const name of DRIFT_COMPARED_HOOKS) {
1721
- 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);
1722
1871
  if (!fs.existsSync(source)) {
1723
1872
  skipped.push(name);
1724
1873
  continue;
1725
1874
  }
1726
- const target = path.join(installedHooks, name);
1875
+ const target = path.join(installDir, name);
1727
1876
  try {
1728
1877
  if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1729
1878
  skipped.push(name);
1730
1879
  continue;
1731
1880
  }
1732
- // #566: the previous version is kept, because this overwrite is the moment
1733
- // machine-only work is lost.
1734
1881
  const backup = backupBeforeOverwrite(target, backupsDir);
1735
1882
  if (backup) backups.push(backup);
1736
- // copyFileSync preserves content; the exec bit is re-applied explicitly
1737
- // because a copied hook that is not executable silently never runs.
1883
+ if (createParents) fs.mkdirSync(path.dirname(target), { recursive: true });
1738
1884
  fs.copyFileSync(source, target);
1739
- fs.chmodSync(target, 0o755);
1885
+ if (keepExecBit) fs.chmodSync(target, 0o755);
1740
1886
  // #583: record it, so a downstream can tell an overwrite from a fresh
1741
- // install without having to diff checksums first.
1887
+ // install without diffing checksums first.
1742
1888
  appendDeployLogEntry(deployLog, { file: name, version, backup });
1743
1889
  synced.push(name);
1744
1890
  } catch (err) {
1745
1891
  errors.push(`${name}: ${err.message}`);
1746
1892
  }
1747
1893
  }
1894
+ }
1748
1895
 
1749
- // Hook support files (#505): sourced by the hooks but not Git entry points, so
1750
- // they need the same copy treatment or an upgraded install dies at the source
1751
- // line. Treated like the hooks themselves (always refreshed, no refusal) —
1752
- // they hold no machine-local content.
1753
- for (const name of HOOK_SUPPORT_FILES) {
1754
- const source = path.join(repoHooks, name);
1755
- if (!fs.existsSync(source)) continue;
1756
- const target = path.join(installedHooks, name);
1757
- try {
1758
- if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1759
- skipped.push(name);
1760
- 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;
1761
1939
  }
1762
- const backup = backupBeforeOverwrite(target, backupsDir);
1763
- if (backup) backups.push(backup);
1764
- // #798: support files may live in a subdirectory (gate-entries/*.sh). The
1765
- // install directory has no such subdirectory yet on an upgraded install, and
1766
- // copyFileSync does not create parents -- the entries failed with ENOENT
1767
- // while gate-driver.sh succeeded, leaving a half-synced hook that dies on
1768
- // its first gate instead of before any.
1769
- fs.mkdirSync(path.dirname(target), { recursive: true });
1770
- fs.copyFileSync(source, target);
1771
- appendDeployLogEntry(deployLog, { file: name, version, backup });
1772
- synced.push(name);
1773
- } catch (err) {
1774
- errors.push(`${name}: ${err.message}`);
1775
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}`);
1776
1949
  }
1950
+ }
1777
1951
 
1778
- // lib/ shared libraries: pre-commit sources lib/*.sh, so a synced hook file
1779
- // 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;
1780
1954
  const repoLib = path.join(repoHooks, 'lib');
1781
1955
  const installedLib = path.join(installedHooks, 'lib');
1782
- if (fs.existsSync(repoLib) && fs.statSync(repoLib).isDirectory()) {
1783
- try {
1784
- fs.mkdirSync(installedLib, { recursive: true });
1785
- } catch (err) {
1786
- errors.push(`cannot create ${installedLib}: ${err.message}`);
1787
- return { synced, skipped, refused, errors, installedHooks, backups };
1788
- }
1789
- let libEntries = [];
1790
- try {
1791
- libEntries = fs.readdirSync(repoLib, { withFileTypes: true });
1792
- } catch (err) {
1793
- errors.push(`cannot read ${repoLib}: ${err.message}`);
1794
- return { synced, skipped, refused, errors, installedHooks, backups };
1795
- }
1796
- for (const entry of libEntries) {
1797
- if (!entry.isFile()) continue;
1798
- const rel = `lib/${entry.name}`;
1799
- const source = path.join(repoLib, entry.name);
1800
- const target = path.join(installedLib, entry.name);
1801
- try {
1802
- if (fs.existsSync(target) && filesAreIdentical(source, target)) {
1803
- skipped.push(rel);
1804
- continue;
1805
- }
1806
- // A shared library can carry machine-only hardening just like a gate
1807
- // module does, so it gets the same refusal instead of an unconditional
1808
- // overwrite (#488 Round 2 -- the module guard and the lib guard must not
1809
- // disagree about how destructive a sync is allowed to be). Unreadable
1810
- // content refuses too: unknown is not the same as safe (#495 Round 3).
1811
- if (fs.existsSync(target)) {
1812
- const decision = copyGuardDecision(source, target, !!ctx.force);
1813
- if (decision.refuse) {
1814
- refused.push({
1815
- name: rel,
1816
- repoOnly: decision.repoOnly,
1817
- installedOnly: decision.installedOnly,
1818
- unknown: decision.unknown,
1819
- });
1820
- continue;
1821
- }
1822
- if (decision.forced === false && decision.repoOnly === 0 && decision.installedOnly === 0) {
1823
- skipped.push(rel);
1824
- continue;
1825
- }
1826
- }
1827
- const backup = backupBeforeOverwrite(target, backupsDir);
1828
- if (backup) backups.push(backup);
1829
- fs.copyFileSync(source, target);
1830
- fs.chmodSync(target, 0o755);
1831
- appendDeployLogEntry(deployLog, { file: rel, version, backup });
1832
- synced.push(rel);
1833
- } catch (err) {
1834
- errors.push(`${rel}: ${err.message}`);
1835
- }
1836
- }
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';
1837
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
+ });
1838
2052
 
1839
2053
  return { synced, skipped, refused, errors, installedHooks, backups };
1840
2054
  }
@@ -1919,7 +2133,15 @@ async function checkAdapters(checks, mode, gitDirPromise) {
1919
2133
  checks.push({ name: 'Adapters directory', status: 'FAIL', detail: 'Missing' });
1920
2134
  return 1;
1921
2135
  }
1922
- 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
+ }
1923
2145
  if (adapterFiles.length === 0) {
1924
2146
  checks.push({ name: 'Adapters directory', status: 'FAIL', detail: 'Empty directory' });
1925
2147
  return 1;
@@ -1954,6 +2176,70 @@ async function checkAdapters(checks, mode, gitDirPromise) {
1954
2176
  * D) Env + CLI tools — fully independent, run IN PARALLEL
1955
2177
  * E) TUI + Skills — independent, run IN PARALLEL
1956
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
+
1957
2243
  async function diagnoseAsync(refreshEnv = false, progress = null) {
1958
2244
  // #629: `progress` is a live view of the checks completed so far. The global
1959
2245
  // timeout used to discard everything diagnoseAsync had already produced; with a
@@ -1988,69 +2274,7 @@ async function diagnoseAsync(refreshEnv = false, progress = null) {
1988
2274
  issues += diagnoseTemplateDir(config, checks);
1989
2275
  // (Spawn capability probe already ran at the top of diagnoseAsync — #525.)
1990
2276
 
1991
- // --- Phase 2: Fetch gitDir early (needed by hooks and adapters) ---
1992
- const gitDirPromise = getGitDir();
1993
-
1994
- // --- Phase 3: Run independent groups in parallel ---
1995
- // Group A: Hooks (needs config.mode + gitDir)
1996
- const hooksPromise = (async () => {
1997
- if (config.mode === 'local') {
1998
- return checkLocalHooks(checks);
1999
- }
2000
- return checkGlobalHooks(checks);
2001
- })();
2002
-
2003
- // Group B: Adapters (needs config.mode + gitDir)
2004
- const adaptersPromise = checkAdapters(checks, config.mode, gitDirPromise);
2005
-
2006
- // Group C: Environment checks + CLI tools — fully parallel
2007
- const envPromise = checkEnv(checks);
2008
- // #469: the tool probes run in the hook environment; --refresh-env swaps in
2009
- // the registry PATH so "installed but invisible" separates from "not
2010
- // installed". The staleness check runs always: it is what makes a stale
2011
- // terminal's green verdict honest.
2012
- const cliToolsPromise = diagnoseCliToolsAsync(checks, { refreshEnv });
2013
- const stalenessPromise = diagnosePathStaleness(checks);
2014
-
2015
- // Group D: TUI + Skills (independent)
2016
- const tuiPromise = diagnoseTuiRegistration(checks);
2017
- const skillsPromise = diagnoseInstalledSkills(config, checks);
2018
-
2019
- // Group E: repo-vs-installed hook drift (#451). Independent of config.mode:
2020
- // the drift matters exactly because the installed copy, not githooks/, is
2021
- // what executes. Detect if this is the xp-gate repo itself.
2022
- const driftPromise = Promise.resolve().then(() => {
2023
- const drift = diagnoseHookDrift();
2024
- checks.push(...drift.checks);
2025
- // The gate modules pre-commit sources at runtime drift independently of the
2026
- // hook files and live in a different directory (#495).
2027
- const moduleDrift = diagnoseModuleDrift();
2028
- checks.push(...moduleDrift.checks);
2029
- // Audit-ledger health (P0): telemetry anomalies are not hook drift, but
2030
- // they ride the same repo-scoped group and must be surfaced by doctor.
2031
- const ledger = diagnoseAuditLedger();
2032
- checks.push(...ledger.checks);
2033
- return drift.issues + moduleDrift.issues + ledger.issues;
2034
- });
2035
-
2036
- // Wait for ALL parallel groups
2037
- const results = await Promise.allSettled([
2038
- hooksPromise,
2039
- adaptersPromise,
2040
- envPromise,
2041
- cliToolsPromise,
2042
- stalenessPromise,
2043
- tuiPromise,
2044
- skillsPromise,
2045
- driftPromise,
2046
- ]);
2047
-
2048
- // Collect issue counts from settled promises
2049
- for (const result of results) {
2050
- if (result.status === 'fulfilled' && typeof result.value === 'number') {
2051
- issues += result.value;
2052
- }
2053
- }
2277
+ issues += await runDiagnosticGroups(checks, config, { refreshEnv });
2054
2278
 
2055
2279
  return { checks, issues };
2056
2280
  }
@@ -2213,6 +2437,89 @@ async function readRegistryPath() {
2213
2437
  * be perfectly healthy; only this terminal is stale, and the remedy is a
2214
2438
  * new terminal (or `xp-gate doctor --refresh-env`).
2215
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
+
2216
2523
  async function diagnosePathStaleness(checks, options = {}) {
2217
2524
  if (process.platform !== 'win32') return 0;
2218
2525
  const registry = options.registry || (await readRegistryPath());
@@ -2230,15 +2537,7 @@ async function diagnosePathStaleness(checks, options = {}) {
2230
2537
  let status = 'PASS';
2231
2538
  const parts = [];
2232
2539
  let stale;
2233
- if (usable.length === 0) {
2234
- // Fail closed: no readable hive is not evidence of freshness.
2235
- checks.push({
2236
- name: 'PATH freshness',
2237
- status: 'WARN',
2238
- 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.`,
2239
- });
2240
- return 0;
2241
- }
2540
+ if (usable.length === 0) return reportUnreadablePath(halves, checks);
2242
2541
  stale = [
2243
2542
  ...usable.flatMap((h) => findStalePathEntries(process.env.PATH || '', h.entries)),
2244
2543
  ];
@@ -2259,32 +2558,9 @@ async function diagnosePathStaleness(checks, options = {}) {
2259
2558
  // Which gate tools does THIS terminal lose to staleness? A tool visible in
2260
2559
  // the hook env only under the registry PATH is "installed but invisible" —
2261
2560
  // never "not installed".
2262
- const bash = checkBash();
2263
- const bashPath = bash.ok ? bash.path : null;
2264
2561
  const refreshedPath = buildRefreshedPath(process.env.PATH || '', registry);
2265
- const invisible = [];
2266
- if (bashPath) {
2267
- await Promise.all(GATE_CLI_TOOLS.map(async (entry) => {
2268
- const now = await probeToolInHookEnv(entry.tool, bashPath);
2269
- if (now) return;
2270
- const refreshed = await probeToolInHookEnv(entry.tool, bashPath, {
2271
- ...process.env,
2272
- PATH: refreshedPath,
2273
- });
2274
- if (refreshed) invisible.push(`${entry.tool} → ${refreshed}`);
2275
- }));
2276
- }
2277
- const preview = stale.length <= 3
2278
- ? stale.join(' ; ')
2279
- : `${stale.slice(0, 3).join(' ; ')} ; …+${stale.length - 3} more`;
2280
- parts.unshift(`PATH is stale — ${stale.length} registry entr${stale.length === 1 ? 'y' : 'ies'} invisible to this process (${preview})`);
2281
- checks.push({
2282
- name: 'PATH freshness',
2283
- status: 'WARN',
2284
- detail: parts.join(' — ')
2285
- + '. A tool installed after this terminal opened needs a NEW terminal — or re-run: xp-gate doctor --refresh-env'
2286
- + (invisible.length ? ` — installed-but-invisible gate tools: ${invisible.join(', ')}` : ''),
2287
- });
2562
+ const invisible = await findStaleInvisibleTools(registry, refreshedPath);
2563
+ reportStalePath({ stale, parts, invisible, checks });
2288
2564
  return 0;
2289
2565
  }
2290
2566
 
@@ -2340,49 +2616,116 @@ async function detectCliToolAsync(toolName, isWindows, options = {}) {
2340
2616
  const bashPath = options.bashPath || null;
2341
2617
  const env = options.env || undefined;
2342
2618
 
2343
- if (bashPath) {
2344
- const hookEnvPath = await probeToolInHookEnv(toolName, bashPath, env);
2345
- if (hookEnvPath) {
2346
- const version = await getVersionAsync(hookEnvPath, isWindows, { bashPath, env });
2347
- return { available: true, path: hookEnvPath, version };
2348
- }
2349
- return { available: false };
2350
- }
2351
-
2352
- const shell = isWindows ? 'cmd.exe' : '/bin/sh';
2353
- const execOpts = { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], shell, timeout: EXEC_TIMEOUT_MS, env };
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);
2354
2622
 
2355
- // Step 1: Locate tool via which/where (async, 3s timeout)
2356
- const locator = isWindows ? 'where' : 'which';
2357
- const locatorResult = await execWithTimeout(`${locator} ${toolName}`, execOpts);
2358
- if (locatorResult && locatorResult.stdout) {
2359
- const resolvedPath = locatorResult.stdout.split('\n')[0].trim();
2360
- if (resolvedPath) {
2361
- const version = await getVersionAsync(resolvedPath, isWindows);
2362
- return { available: true, path: resolvedPath, version };
2363
- }
2364
- }
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
+ }
2365
2632
 
2366
- // Step 2: Direct exec fallback (async, 3s timeout)
2367
- const fallbackCmd = isWindows
2368
- ? `${toolName} --version`
2369
- : `${toolName} --version 2>/dev/null || ${toolName} -v 2>/dev/null`;
2370
- const fallbackResult = await execWithTimeout(fallbackCmd, execOpts);
2371
- if (fallbackResult && fallbackResult.stdout) {
2372
- return { available: true, path: toolName, version: fallbackResult.stdout.split('\n')[0] };
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;
2373
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
+ }
2672
+
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
+ }
2682
+
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) {
2690
+ const locator = isWindows ? 'where' : 'which';
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
+ }
2696
+
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
2707
+ ? `${toolName} --version`
2708
+ : `${toolName} --version 2>/dev/null || ${toolName} -v 2>/dev/null`;
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
+ }
2374
2713
 
2375
- // Step 3: Check local fallback paths (sync fs, no exec)
2376
- const localPaths = getLocalFallbackPathsSync(toolName, isWindows);
2377
- 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)) {
2378
2724
  if (!fs.existsSync(localPath)) continue;
2379
2725
  const version = await getVersionAsync(localPath, isWindows);
2380
- if (version) {
2381
- return { available: true, path: localPath, version };
2382
- }
2726
+ if (version) return { available: true, path: localPath, version };
2383
2727
  }
2384
-
2385
- return { available: false };
2728
+ return null;
2386
2729
  }
2387
2730
 
2388
2731
  /**
@@ -2417,30 +2760,38 @@ async function getVersionAsync(execPath, isWindows, options = {}) {
2417
2760
  * Get local fallback paths for CLI tool (sync, no exec).
2418
2761
  * Mirrors getLocalFallbackPaths from detect-deps.js.
2419
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
+
2420
2782
  function getLocalFallbackPathsSync(toolName, isWindows) {
2421
2783
  const os = require('os');
2422
2784
  const home = os.homedir();
2423
2785
  const paths = [path.join(home, '.local', 'bin', toolName)];
2424
2786
 
2425
- if (isWindows) {
2426
- const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
2427
- const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
2428
- paths.push(
2429
- path.join(appData, 'npm', `${toolName}.cmd`),
2430
- path.join(home, '.local', 'bin', `${toolName}.exe`),
2431
- );
2432
- const pythonBase = path.join(localAppData, 'Programs', 'Python');
2433
- if (fs.existsSync(pythonBase)) {
2434
- try {
2435
- for (const entry of fs.readdirSync(pythonBase)) {
2436
- if (entry.startsWith('Python')) {
2437
- paths.push(path.join(pythonBase, entry, 'Scripts', `${toolName}.exe`));
2438
- }
2439
- }
2440
- } catch { /* skip */ }
2441
- }
2442
- }
2787
+ if (!isWindows) return paths;
2443
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
+ );
2444
2795
  return paths;
2445
2796
  }
2446
2797
 
@@ -2489,12 +2840,15 @@ function diagnoseTemplateDir(config, checks) {
2489
2840
  * @param {Array} checks
2490
2841
  * @returns {number} issue count
2491
2842
  */
2492
- function diagnoseCliTools(checks) {
2843
+ function diagnoseCliTools(checks, options = {}) {
2493
2844
  let issues = 0;
2494
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;
2495
2849
 
2496
2850
  for (const entry of GATE_CLI_TOOLS) {
2497
- const { available, version } = checkCliTool(entry.tool);
2851
+ const { available, version } = probe(entry.tool);
2498
2852
  const gateLabels = entry.gates.join(', ');
2499
2853
 
2500
2854
  if (available) {
@@ -2537,12 +2891,22 @@ function printReport(checks) {
2537
2891
  /**
2538
2892
  * Copy a hook file from package source to target, creating parent dir if needed.
2539
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
+ */
2540
2900
  function restoreHook(srcFile, destFile, label) {
2541
2901
  if (!fs.existsSync(srcFile)) return false;
2542
- const destDir = path.dirname(destFile);
2543
- fs.mkdirSync(destDir, { recursive: true });
2544
- fs.copyFileSync(srcFile, destFile);
2545
- 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
+ }
2546
2910
  console.log(` ✓ Restored ${label}`);
2547
2911
  return true;
2548
2912
  }
@@ -2629,19 +2993,38 @@ function fixCoreHooksPath(globalHooksDir) {
2629
2993
  * @returns {boolean} Whether adapters were restored
2630
2994
  */
2631
2995
  function fixMissingAdapters(mode, srcDir, adaptersDir) {
2632
- if (adaptersDir && (!fs.existsSync(adaptersDir) || fs.readdirSync(adaptersDir).filter(f => f.endsWith('.sh')).length === 0)) {
2633
- const pkgAdaptersDir = path.join(srcDir, 'adapters');
2634
- if (fs.existsSync(pkgAdaptersDir)) {
2635
- fs.mkdirSync(adaptersDir, { recursive: true });
2636
- const adapterFiles = fs.readdirSync(pkgAdaptersDir).filter(f => f.endsWith('.sh'));
2637
- for (const f of adapterFiles) {
2638
- fs.copyFileSync(path.join(pkgAdaptersDir, f), path.join(adaptersDir, f));
2639
- }
2640
- console.log(` ✓ Restored ${adapterFiles.length} adapter(s)`);
2641
- 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));
2642
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;
2643
3027
  }
2644
- return false;
2645
3028
  }
2646
3029
 
2647
3030
  /**
@@ -2652,7 +3035,14 @@ function fixMissingAdapters(mode, srcDir, adaptersDir) {
2652
3035
  function fixMissingGateScripts(srcDir, adaptersDir) {
2653
3036
  if (!adaptersDir || !fs.existsSync(adaptersDir)) return false;
2654
3037
 
2655
- 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
+ }
2656
3046
  const missingGates = EXPECTED_GATE_SCRIPTS.filter(g => !existingFiles.includes(g));
2657
3047
 
2658
3048
  if (missingGates.length === 0) return false;
@@ -2661,10 +3051,14 @@ function fixMissingGateScripts(srcDir, adaptersDir) {
2661
3051
  for (const gateScript of missingGates) {
2662
3052
  const srcFile = path.join(srcDir, gateScript);
2663
3053
  const destFile = path.join(adaptersDir, gateScript);
2664
- if (fs.existsSync(srcFile)) {
3054
+ if (!fs.existsSync(srcFile)) continue;
3055
+ try {
2665
3056
  fs.copyFileSync(srcFile, destFile);
2666
3057
  fs.chmodSync(destFile, 0o755);
2667
3058
  restored++;
3059
+ } catch (err) {
3060
+ // One unwritable gate script must not strand the others.
3061
+ console.log(` ✗ Could not restore ${gateScript}: ${err.message}`);
2668
3062
  }
2669
3063
  }
2670
3064
 
@@ -2780,23 +3174,92 @@ function fixHookDriftFromRepo() {
2780
3174
  *
2781
3175
  * @returns {boolean} Whether any hooks were updated
2782
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
+
2783
3254
  function fixStaleHooks(config) {
2784
3255
  try {
2785
3256
  const { detectLocalModifications, getPackageRoot } = require('./update-hooks.js');
2786
3257
  const isGlobal = config.mode === 'global';
2787
3258
  const srcDir = getPackageRoot();
2788
3259
 
2789
- let hooksDestDir, adaptersDestDir;
2790
- if (isGlobal) {
2791
- hooksDestDir = GLOBAL_HOOKS_DIR();
2792
- adaptersDestDir = GLOBAL_ADAPTERS_DIR();
2793
- } else {
2794
- const gitDir = getGitDirSync();
2795
- if (!gitDir) return false;
2796
- const projectRoot = path.dirname(gitDir);
2797
- hooksDestDir = path.join(gitDir, 'hooks');
2798
- adaptersDestDir = path.join(projectRoot, 'githooks');
2799
- }
3260
+ const dest = resolveHookDestinations(isGlobal);
3261
+ if (!dest) return false;
3262
+ const { hooksDestDir, adaptersDestDir } = dest;
2800
3263
 
2801
3264
  // Check if any hook files are stale (differ from package version)
2802
3265
  const modified = detectLocalModifications(srcDir, hooksDestDir, adaptersDestDir);
@@ -2813,38 +3276,9 @@ function fixStaleHooks(config) {
2813
3276
  modified.flatMap((label) => staleSyncEntries(label, srcDir, hooksDestDir, adaptersDestDir)),
2814
3277
  );
2815
3278
 
2816
- if (plan.hasBlocking) {
2817
- console.log(` ⚠️ ${plan.diverged.length + plan.unknown.length} hook/adapter file(s) NOT refreshed —`);
2818
- console.log(' the installed copy carries content the package does not, and overwriting');
2819
- console.log(' it would delete work that exists nowhere else:');
2820
- for (const d of plan.diverged) {
2821
- console.log(` - ${d.name}: install has ${d.installedOnly} unique line(s), package has ${d.repoOnly}`);
2822
- }
2823
- for (const u of plan.unknown) {
2824
- console.log(` - ${u.name}: installed copy could not be read`);
2825
- }
2826
- console.log(' Judge them (fold the hardening into the package, or move the file aside),');
2827
- console.log(' then re-run --fix.');
2828
- console.log(' There is no automatic backup of an overwritten hook/adapter file and nothing');
2829
- console.log(' in this tool can undo one — judge against a copy you kept, not against a rollback.');
2830
- }
2831
-
3279
+ reportBlockedHookSync(plan);
2832
3280
  if (plan.safe.length === 0) return plan.hasBlocking;
2833
-
2834
- console.log(` Refreshing ${plan.safe.length} outdated hook/adapter file(s)...`);
2835
- let refreshed = 0;
2836
- for (const entry of plan.safe) {
2837
- if (!fs.existsSync(entry.source)) continue;
2838
- try {
2839
- fs.mkdirSync(path.dirname(entry.target), { recursive: true });
2840
- fs.copyFileSync(entry.source, entry.target);
2841
- fs.chmodSync(entry.target, 0o755);
2842
- refreshed++;
2843
- } catch (err) {
2844
- console.log(` ✗ Could not refresh ${entry.name}: ${err.message}`);
2845
- }
2846
- }
2847
- return refreshed > 0;
3281
+ return refreshSafeHooks(plan.safe);
2848
3282
  } catch {
2849
3283
  return false;
2850
3284
  }
@@ -2993,12 +3427,22 @@ function diagnoseOpenCodePlugin(checks) {
2993
3427
 
2994
3428
  /**
2995
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]
2996
3437
  * @returns {number} Number of issues found (missing required tools)
2997
3438
  */
2998
- function diagnoseLanguageTools() {
3439
+ function diagnoseLanguageTools(options = {}) {
2999
3440
  try {
3000
- const { detectProjectLanguages, getToolsForLanguages, LANGUAGE_REGISTRY } = require('./language-tools.js');
3001
- 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();
3002
3446
  const { detected } = detectProjectLanguages(projectRoot);
3003
3447
 
3004
3448
  if (detected.length === 0) return 0;
@@ -3054,282 +3498,571 @@ const KNOWN_FLAGS = ['--fix', '--sync-hooks', '--force', '--install-tools', '--j
3054
3498
  *
3055
3499
  * @returns {{errors: string[], fixMode: boolean, syncHooks: boolean, force: boolean, installToolsFlag: boolean, jsonMode: boolean}}
3056
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
+
3057
3593
  function doctorFlagContract(args) {
3058
3594
  const errors = [];
3059
- // `--format json` carries a value; without this the value itself would be
3060
- // reported as an unknown flag and the documented machine-readable mode could
3061
- // never be reached (#304 promised it, nothing ever implemented it).
3062
- const formatValue = args[args.indexOf('--format') + 1] || null;
3063
- const flagTokens = args.filter((a, i) => !(i > 0 && args[i - 1] === '--format'));
3064
- const unknownFlags = flagTokens.filter(a => !KNOWN_FLAGS.includes(a));
3065
- if (unknownFlags.length > 0) {
3066
- errors.push(`Unknown flag(s) for doctor: ${unknownFlags.join(', ')}`);
3067
- errors.push(`Supported flags: ${KNOWN_FLAGS.join(', ')}`);
3068
- }
3069
- const fixMode = args.includes('--fix');
3070
- const syncHooks = args.includes('--sync-hooks');
3071
- // #495: overwriting a module whose installed copy holds lines the repo lacks
3072
- // destroys machine-only hardening, so it needs this explicit opt-in.
3073
- const force = args.includes('--force');
3074
- // Installing a toolchain changes the machine, not the repository, so it is
3075
- // never a side effect of --fix (#502). --fix reports the missing tools.
3076
- const installToolsFlag = args.includes('--install-tools');
3077
- // #469: re-probe CLI tools against the registry PATH (what a freshly opened
3078
- // terminal would see) instead of this process's possibly-stale snapshot.
3079
- // Read-only: it changes the probe environment, never the machine.
3080
- const refreshEnv = args.includes('--refresh-env');
3081
- const jsonMode = args.includes('--json') || (args.includes('--format') && formatValue === 'json');
3082
- if (args.includes('--format') && !['json', 'text'].includes(formatValue)) {
3083
- errors.push(`Unknown --format value: ${formatValue || '(none)'} — expected json or text`);
3084
- }
3085
- if (jsonMode && (fixMode || syncHooks)) {
3086
- // A JSON report is a read; mixing it with the repair surface would put
3087
- // progress prose into the stream a script is parsing.
3088
- errors.push('--json/--format json cannot be combined with --fix or --sync-hooks');
3089
- }
3090
- // Round 4 (feasibility) caught the original #488 defect in a new place:
3091
- // `--force` is read only by the sync path, so `doctor --force` and
3092
- // `doctor --fix --force` were accepted, printed nothing and changed nothing.
3093
- if (force && !syncHooks) {
3094
- errors.push('--force is only read by --sync-hooks, where it overrides the divergence refusal and overwrites without a backup');
3095
- errors.push('Pass --sync-hooks --force, or drop --force');
3096
- }
3097
- // Same class: --install-tools installs only inside the --fix repair surface.
3098
- if (installToolsFlag && !fixMode) {
3099
- errors.push('--install-tools is only read by --fix, and it is the only flag that installs toolchains onto this machine');
3100
- errors.push('Pass --fix --install-tools, or drop --install-tools');
3101
- }
3102
- // #653: --brief exists to collapse a class of exploratory probes (`where gcc`,
3103
- // Test-Path, per-file reads) into one cheap read. It is read-only by contract:
3104
- // users call it often precisely because it is cheap, so a write smuggled in
3105
- // would compound state changes instead of only latency.
3106
- const briefFlag = args.includes('--brief');
3107
- if (briefFlag && (fixMode || syncHooks || installToolsFlag || force)) {
3108
- errors.push('--brief is a read-only fact dump and cannot be combined with --fix, --sync-hooks, --install-tools or --force');
3109
- }
3110
- 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 };
3111
3623
  }
3112
3624
 
3113
- async function doctor(args) {
3114
- const { errors, fixMode, syncHooks, force, installToolsFlag, jsonMode, refreshEnv, briefFlag } = doctorFlagContract(args);
3115
- if (briefFlag && errors.length === 0) {
3116
- // Answers the whole "what is this machine set up like" question in one shot.
3117
- const { buildBriefReport } = require('./doctor-brief');
3118
- const report = buildBriefReport({ cwd: process.cwd() });
3119
- if (jsonMode) {
3120
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
3121
- } else {
3122
- process.stdout.write(`${report.summary}\n`);
3123
- }
3124
- process.exitCode = 0;
3125
- return;
3126
- }
3127
- if (errors.length > 0) {
3128
- 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}`);
3129
3659
  return 1;
3130
3660
  }
3131
-
3132
- if (!jsonMode) {
3133
- console.log('XP-Gate Doctor');
3134
- 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'})`);
3135
3666
  }
3136
-
3137
- // §4.13 (#451 REQ-3): state which hook files actually execute, so "I edited
3138
- // githooks/ but nothing changed" is answerable without reading git config.
3139
- if (!jsonMode) printEffectiveHooks();
3140
- // #495: the same for the gate modules the hook sources at runtime.
3141
- if (!jsonMode) printEffectiveModules();
3142
-
3143
- const config = getConfig();
3144
-
3145
- // §4.8: mode === "uninstalled" → print "xp-gate is not installed"
3146
- if (isUninstalledMode(config)) {
3147
- if (jsonMode) {
3148
- console.log(JSON.stringify(formatDoctorJson([{ name: 'Install', status: 'SKIP', detail: 'xp-gate is not installed' }], 0)));
3149
- return 0;
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}`);
3150
3673
  }
3151
- console.log('xp-gate is not installed.');
3152
- console.log('Run xp-gate init to install.');
3153
- return 0;
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/.');
3154
3676
  }
3677
+ return 0;
3678
+ }
3155
3679
 
3156
- // §4.13 (#451 REQ-2): explicit one-command sync from the repo's githooks/.
3157
- if (syncHooks) {
3158
- const { synced, skipped, refused, errors, installedHooks, backups } = syncGlobalHooksFromRepo({ force });
3159
- if (errors.length > 0) {
3160
- for (const err of errors) console.log(` ✗ ${err}`);
3161
- return 1;
3162
- }
3163
- if (synced.length > 0) {
3164
- console.log(` ✓ Synced ${synced.join(', ')} from githooks/ to ${installedHooks}`);
3165
- console.log(' The updated hooks take effect on the next commit.');
3166
- } else {
3167
- console.log(` ✓ Global hooks already match githooks/ (${skipped.join(', ') || 'nothing to sync'})`);
3168
- }
3169
- // #566: replacing an installed hook discards whatever was in it. Say where
3170
- // the previous version went, so a machine-only fix stays recoverable.
3171
- if (backups.length > 0) {
3172
- console.log(` Previous version(s) saved under ${path.join(installedHooks, 'backups')}/ (${backups.length} file(s)).`);
3173
- }
3174
- if (refused.length > 0) {
3175
- console.log('');
3176
- console.log(` ⚠️ ${refused.length} shared library file(s) NOT synced — the installed copy`);
3177
- console.log(' carries content githooks/ does not, so overwriting would delete work:');
3178
- for (const r of refused) {
3179
- console.log(` - ${r.name}: install has ${r.installedOnly} unique line(s), githooks/ has ${r.repoOnly}`);
3180
- }
3181
- console.log(' Review them, then either fold the hardening into githooks/ or re-run --sync-hooks --force.');
3182
- console.log(' Forcing overwrites the installed file, whose previous version is saved under backups/.');
3183
- }
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
+ }
3184
3712
 
3185
- // #495: the gate modules are what the hook sources for Gates 3/4/7/8/9/10,
3186
- // so syncing only the hook files left the executed surface untouched.
3187
- const moduleSync = syncModulesFromRepo({ force });
3188
- if (moduleSync.errors.length > 0) {
3189
- for (const err of moduleSync.errors) console.log(` ✗ ${err}`);
3190
- return 1;
3191
- }
3192
- if (moduleSync.synced.length > 0) {
3193
- console.log(` ✓ Synced ${moduleSync.synced.length} gate module(s) to ${moduleSync.installedAdapters}`);
3194
- console.log(` ${moduleSync.synced.join(', ')}`);
3195
- }
3196
- if (moduleSync.refused.length > 0) {
3197
- console.log('');
3198
- console.log(` ⚠️ ${moduleSync.refused.length} module(s) NOT synced — the installed copy carries`);
3199
- console.log(' content the repo does not, so overwriting would delete work (#495):');
3200
- for (const r of moduleSync.refused) {
3201
- console.log(` - ${r.name}: install has ${r.installedOnly} unique line(s), githooks/ has ${r.repoOnly}`);
3202
- }
3203
- console.log(' Review them, then either fold the hardening into githooks/ or re-run --sync-hooks --force.');
3204
- console.log(' Forcing overwrites the installed file, whose previous version is saved under backups/.');
3205
- }
3713
+
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`);
3206
3730
  }
3731
+ process.exitCode = 0;
3732
+ }
3207
3733
 
3208
- // §4.13: --fix only when mode === "active"
3209
- if (fixMode && isActiveMode(config)) {
3210
- fixIssues(null, config, installToolsFlag);
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)));
3747
+ return 0;
3211
3748
  }
3749
+ console.log('xp-gate is not installed.');
3750
+ console.log('Run xp-gate init to install.');
3751
+ return 0;
3752
+ }
3212
3753
 
3213
- // Global timeout wrapper — ensures doctor completes within GLOBAL_DIAGNOSIS_TIMEOUT_MS
3214
- // even if network/subprocess checks stack up (fix #348: 43s on Windows).
3215
- // #629: give diagnoseAsync a live sink so a deadline can keep what finished.
3216
- // Without it, `Promise.race` discarded the entire diagnosis -- so the SAME
3217
- // healthy install reported different results run to run, and a timed-out run
3218
- // lost the skills section entirely (scrapers read 0/12 installed skills).
3219
- const progress = { checks: [], getIssues: () => 0 };
3220
- const diagnosisPromise = diagnoseAsync(refreshEnv, progress);
3221
- let diagnosisTimer = null;
3222
- const timeoutPromise = new Promise((resolve) => {
3223
- diagnosisTimer = setTimeout(() => {
3224
- const completed = Array.isArray(progress.checks) ? progress.checks : [];
3225
- const reported = new Set(completed.map((c) => c && c.name));
3226
- // Name the surfaces that did NOT report, so the reader knows exactly which
3227
- // conclusions are missing rather than just "something timed out".
3228
- const pending = ['Hooks', 'Adapters', 'Skills', 'Gate env', 'OpenCode TUI']
3229
- .filter((name) => !reported.has(name));
3230
- resolve(mergeTimedOutDiagnosis(
3231
- { checks: completed, issues: progress.getIssues() },
3232
- pending,
3233
- ));
3234
- }, GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3235
- });
3236
- const { checks, issues: diagnosedIssues, timedOut } = await Promise.race([
3237
- diagnosisPromise.then(r => ({ ...r, timedOut: false })),
3238
- timeoutPromise,
3239
- ]);
3240
- clearTimeout(diagnosisTimer);
3241
- let issues = diagnosedIssues;
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;
3242
3772
 
3243
- // A timeout discards every check that had not reported yet, including the
3244
- // drift surface, so the raced result must never be allowed to read as clean
3245
- // (#495 Round 2 -- this is the "stale modules, doctor green" outcome itself).
3246
3773
  if (timedOut) {
3247
- issues = Math.max(issues, 1);
3248
3774
  const hookDrift = diagnoseHookDrift();
3249
3775
  const moduleDrift = diagnoseModuleDrift();
3250
3776
  checks.push(...hookDrift.checks, ...moduleDrift.checks);
3251
- issues += hookDrift.issues + moduleDrift.issues;
3777
+ added += hookDrift.issues + moduleDrift.issues;
3252
3778
  }
3253
3779
 
3254
- // Flaky-test quarantine expiry (#603). A WARN, not a FAIL: an overdue ledger
3255
- // breaks nothing at runtime, it only means an intentional gap outlived its
3256
- // intent -- doctor's business, not a gate's.
3257
3780
  try {
3258
3781
  const flaky = diagnoseFlakyQuarantine({ repoRoot: process.cwd() });
3259
3782
  checks.push(...flaky.checks);
3260
- issues += flaky.issues;
3783
+ added += flaky.issues;
3261
3784
  } catch (err) {
3262
- // Surface the cause: a bare "could not be read" hid the real error and made
3263
- // this look like a missing file rather than a bug in the check itself.
3264
- checks.push({ name: 'Flaky quarantine', status: 'SKIP', detail: `ledger check failed: ${err && err.message ? err.message : String(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}` });
3265
3789
  }
3266
3790
 
3267
- let langIssues = 0;
3268
- // Upgrade + plugin + language-tool status, kept as one callable because a
3269
- // --format json run still has to execute all of it (#488).
3270
- const collectTrailingChecks = async () => {
3271
- try {
3272
- const upgradePromise = diagnoseUpgrade();
3273
- const upgradeTimeout = new Promise((resolve) => setTimeout(() => resolve(), 3000));
3274
- await Promise.race([upgradePromise, upgradeTimeout]);
3275
- } catch { /* non-blocking */ }
3276
- const trailing = diagnoseOpenCodePlugin(checks);
3277
- langIssues = diagnoseLanguageTools();
3278
- return trailing + langIssues;
3279
- };
3791
+ return added;
3792
+ }
3280
3793
 
3281
- if (jsonMode) {
3282
- // Machine-readable output means EXACTLY one JSON document on stdout, so the
3283
- // human report and the trailing checks' chatter are silenced while their
3284
- // results are still collected into `checks`.
3285
- const say = console.log;
3286
- console.log = () => {};
3287
- try {
3288
- issues += await collectTrailingChecks();
3289
- } finally {
3290
- console.log = say;
3291
- }
3292
- console.log(JSON.stringify(formatDoctorJson(checks, issues)));
3293
- return issues > 0 ? 1 : 0;
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.
3294
3815
  }
3816
+ const trailing = diagnoseOpenCodePlugin(checks);
3817
+ const langIssues = diagnoseLanguageTools();
3818
+ return { issues: trailing + langIssues, langIssues };
3819
+ }
3295
3820
 
3296
- printReport(checks);
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;
3297
3837
 
3298
- issues += await collectTrailingChecks();
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
+ }
3299
3843
 
3300
- // In --fix mode, auto-install missing language tools — only on explicit
3301
- // --install-tools (#502: a diagnosis command must not run package managers).
3302
- if (fixMode && installToolsFlag && langIssues > 0) {
3303
- try {
3304
- const { detectProjectLanguages, getToolsForLanguages, installTool, generateProjectConfig, LANGUAGE_REGISTRY } = require('./language-tools.js');
3305
- const projectRoot = process.cwd();
3306
- const { detected } = detectProjectLanguages(projectRoot);
3307
- if (detected.length > 0) {
3308
- const toolStatus = getToolsForLanguages(detected);
3309
- let installed = 0;
3310
- for (const [lang, tools] of Object.entries(toolStatus)) {
3311
- for (const t of tools) {
3312
- if (t.status === 'missing') {
3313
- const result = installTool(t.tool);
3314
- if (result.success) {
3315
- console.log(` \u2713 ${t.tool.name} (${lang}) installed`);
3316
- installed++;
3317
- }
3318
- }
3319
- }
3320
- }
3321
- if (installed > 0) {
3322
- console.log(` ${installed} language tool(s) installed.`);
3323
- generateProjectConfig(projectRoot, detected, toolStatus);
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++;
3324
3857
  }
3325
3858
  }
3326
- } catch { /* non-blocking */ }
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.
3327
3866
  }
3867
+ }
3328
3868
 
3329
- if (fixMode && !installToolsFlag && langIssues > 0) {
3330
- console.log(`\n ${langIssues} language tool(s) are missing. --fix did not install them —`);
3331
- console.log(' installing a toolchain changes the machine, so opt in with --install-tools (#502).');
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) {
3887
+ const progress = { checks: [], getIssues: () => 0 };
3888
+ const diagnosisPromise = diagnoseAsync(refreshEnv, progress);
3889
+
3890
+ let timer = null;
3891
+ const timeoutPromise = new Promise((resolve) => {
3892
+ timer = setTimeout(() => {
3893
+ const completed = Array.isArray(progress.checks) ? progress.checks : [];
3894
+ const reported = new Set(completed.map((c) => c && c.name));
3895
+ const pending = ['Hooks', 'Adapters', 'Skills', 'Gate env', 'OpenCode TUI']
3896
+ .filter((name) => !reported.has(name));
3897
+ resolve(mergeTimedOutDiagnosis(
3898
+ { checks: completed, issues: progress.getIssues() },
3899
+ pending,
3900
+ ));
3901
+ }, GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3902
+ });
3903
+
3904
+ const result = await Promise.race([
3905
+ diagnosisPromise.then((r) => ({ ...r, timedOut: false })),
3906
+ timeoutPromise,
3907
+ ]);
3908
+ clearTimeout(timer);
3909
+ return { checks: result.checks, issues: result.issues, timedOut: result.timedOut };
3910
+ }
3911
+
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
+ }
3926
+
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 = () => {};
3944
+ try {
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;
3949
+ }
3950
+ console.log(JSON.stringify(formatDoctorJson(checks, issues)));
3951
+ return issues > 0 ? 1 : 0;
3952
+ }
3953
+
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
+ });
3979
+
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);
3332
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);
4058
+
4059
+ printReport(checks);
4060
+
4061
+ const trailing = await collectTrailing(checks);
4062
+ issues += trailing.issues;
4063
+ reportLanguageToolRepairs({ fixMode, installToolsFlag, langIssues: trailing.langIssues });
4064
+
4065
+
3333
4066
 
3334
4067
  if (issues === 0) {
3335
4068
  console.log('\n✓ All checks passed');
@@ -3338,30 +4071,7 @@ async function doctor(args) {
3338
4071
 
3339
4072
  console.log(`\n✗ ${issues} issue(s) found`);
3340
4073
 
3341
- // Re-run diagnosis after fix to report updated status
3342
- if (fixMode && isActiveMode(config)) {
3343
- console.log('\nRe-running diagnosis after fix...');
3344
- const postDiagPromise = diagnoseAsync();
3345
- let postTimer = null;
3346
- const postTimeout = new Promise((resolve) => {
3347
- postTimer = setTimeout(() => resolve({
3348
- checks: [{ name: 'Post-fix diagnosis', status: 'WARN', detail: `Timed out after ${GLOBAL_DIAGNOSIS_TIMEOUT_MS / 1000}s — the fix result is unconfirmed, not clean` }],
3349
- issues: 1,
3350
- timedOut: true,
3351
- }), GLOBAL_DIAGNOSIS_TIMEOUT_MS);
3352
- });
3353
- const { checks: postChecks, timedOut: postTimedOut } = await Promise.race([
3354
- postDiagPromise.then(r => ({ ...r, timedOut: false })),
3355
- postTimeout,
3356
- ]);
3357
- clearTimeout(postTimer);
3358
- // Symmetry with the pre-fix race above: a timeout here discards the drift
3359
- // surface too, so the post-fix report must not read as "all clear".
3360
- if (postTimedOut) {
3361
- postChecks.push(...diagnoseHookDrift().checks, ...diagnoseModuleDrift().checks);
3362
- }
3363
- printReport(postChecks);
3364
- }
4074
+ if (fixMode && isActiveMode(config)) await reportPostFixDiagnosis();
3365
4075
 
3366
4076
  return issues > 0 ? 1 : 0;
3367
4077
  }
@@ -3386,21 +4096,105 @@ function formatDoctorJson(checks, issues) {
3386
4096
  // real failure was silent: drifted agent bindings looked like a working setup
3387
4097
  // (B2), a stale skill copy made reinstall = downgrade (B4), and a missing
3388
4098
  // runner script surfaced only as a failed review (B3).
3389
- async function doctorDelphi(options = {}) {
3390
- const { configPath, npmLatest } = options;
3391
- // #541: the shadow check needs the loader's global fallback path. It is
3392
- // injectable for tests; the default mirrors delphi-config.ts /
3393
- // delphi-external-review.cjs resolution (XDG_CONFIG_HOME honored).
3394
- const globalConfigPath = options.globalConfigPath
3395
- || path.join(process.env.XDG_CONFIG_HOME || path.join(require('os').homedir(), '.config'), 'xp-gate', '.delphi-config.json');
3396
- const checks = [];
3397
- 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. */
3398
4112
 
3399
- // 1. Node >= 18: the runner gates on it and exits 1 mid-review otherwise.
3400
- const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
3401
- add('Node.js >= 18', nodeMajor >= 18 ? 'PASS' : 'FAIL',
3402
- `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
+ }
3403
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
+ }
4196
+
4197
+ function checkDelphiAgentBindings(add, options) {
3404
4198
  // 2. Qoder agent bindings: present, parseable, three distinct ids, matching
3405
4199
  // what this version ships. A stale binding is a repair, not an error to
3406
4200
  // retype: the detail names delphi-setup. Project-level agents (from
@@ -3412,29 +4206,10 @@ async function doctorDelphi(options = {}) {
3412
4206
  // users their working setup was broken and pointed them at a repair command that
3413
4207
  // reinstalls the thing they just removed. SKIP carries the reason so the line can
3414
4208
  // never be read as green either -- the same rule every other gate follows.
3415
- const delphiChannel = require('./delphi-channel.js');
3416
- // Pass the directory that CONTAINS `.config`, not the `.config` dir itself:
3417
- // resolveChannels() appends `<home>/.config/xp-gate/...`, so handing it `.config`
3418
- // would look in `.config/.config/xp-gate` and never find the file.
3419
- const channelHome = process.env.XDG_CONFIG_HOME
3420
- ? path.dirname(process.env.XDG_CONFIG_HOME)
3421
- : undefined;
3422
- const channelResolution = delphiChannel.resolveChannels({ home: channelHome });
3423
- const nativeDisabled = !channelResolution.nativeEnabled;
4209
+ const { nativeDisabled, channelResolution, agentsDir, agentsSource, agentDetails } = resolveAgentTarget(options);
3424
4210
  const { readQoderModelId } = require('./init.js');
3425
- const roles = ['architecture', 'technical', 'feasibility'];
3426
- const homeAgentsDir = path.join(HOME_DIR(), '.qoder', 'agents');
3427
- // Injectable for tests; defaults to the cwd the doctor runs from.
3428
- const projectAgentsDir = path.join(options.projectDir || process.cwd(), '.qoder', 'agents');
3429
- const homeComplete = roles.every((r) => fs.existsSync(path.join(homeAgentsDir, `delphi-${r}.md`)));
3430
- const projectComplete = roles.every((r) => fs.existsSync(path.join(projectAgentsDir, `delphi-${r}.md`)));
3431
- const agentsDir = projectComplete ? projectAgentsDir : homeAgentsDir;
3432
- const agentsSource = projectComplete
3433
- ? `project-level ${agentsDir}`
3434
- : `user-level ${agentsDir}`;
3435
4211
  const agentIds = [];
3436
4212
  let agentsStatus = 'PASS';
3437
- const agentDetails = [agentsSource];
3438
4213
  // #646: skip the whole native binding check when the machine is external-only.
3439
4214
  // The check exists to keep the native path healthy; when that path is switched off
3440
4215
  // by configuration there is nothing to keep healthy, and reporting its absence as
@@ -3444,33 +4219,11 @@ async function doctorDelphi(options = {}) {
3444
4219
  `native channel disabled (channels=${channelResolution.channels.join(',')} via ${channelResolution.source}) — `
3445
4220
  + 'Delphi review runs through the external provider');
3446
4221
  }
3447
- for (const role of nativeDisabled ? [] : roles) {
3448
- const agentPath = path.join(agentsDir, `delphi-${role}.md`);
3449
- if (!fs.existsSync(agentPath)) {
3450
- agentsStatus = 'FAIL';
3451
- agentDetails.push(`delphi-${role}.md missing (run: xp-gate init --global, or delphi-setup --local --project for project scope)`);
3452
- continue;
3453
- }
3454
- const id = readQoderModelId(agentPath);
3455
- if (id === null) {
3456
- agentsStatus = 'FAIL';
3457
- agentDetails.push(`delphi-${role}.md has no quoted model binding (repair: xp-gate delphi-setup)`);
3458
- continue;
3459
- }
3460
- const bundledId = readQoderModelId(path.join(PKG_DIR, 'plugins', 'qoder', 'agents', `delphi-${role}.md`));
3461
- if (bundledId === null) {
3462
- // A bundle without a parseable template is install corruption: skipping
3463
- // the comparison would hide it behind a healthy-looking id (#414 R1 FC-08).
3464
- agentsStatus = 'FAIL';
3465
- agentDetails.push(`delphi-${role}: bundled template missing/unreadable — reinstall xp-gate`);
3466
- continue;
3467
- }
3468
- if (bundledId !== id) {
3469
- agentDetails.push(`delphi-${role}: ${id} (this version ships ${bundledId} — repair: xp-gate delphi-setup)`);
3470
- } else {
3471
- agentDetails.push(`delphi-${role}: ${id}`);
3472
- }
3473
- 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);
3474
4227
  }
3475
4228
  // Report every problem class independently: missing files, unparseable
3476
4229
  // bindings and duplicates can coexist, and each has a different remedy
@@ -3480,14 +4233,88 @@ async function doctorDelphi(options = {}) {
3480
4233
  // empty agentIds (the disabled path) would compute `0 !== 3` and re-report the very
3481
4234
  // FAIL the SKIP above just replaced.
3482
4235
  if (!nativeDisabled) {
3483
- if (agentIds.length !== roles.length) agentsStatus = 'FAIL';
4236
+ if (agentIds.length !== DELPHI_ROLES.length) agentsStatus = 'FAIL';
3484
4237
  if (new Set(agentIds).size !== agentIds.length) {
3485
4238
  agentsStatus = 'FAIL';
3486
4239
  agentDetails.push('duplicate model binding across experts — three DISTINCT ids are required');
3487
4240
  }
3488
4241
  add('Qoder Delphi agent bindings', agentsStatus, agentDetails.join('; ') || 'all three bound');
3489
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
+ }
3490
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) {
3491
4318
  // 3. Skill install parity: a drifted installed copy is how "reinstall from
3492
4319
  // an old local repo" became a downgrade (#414 B4). Every bundled file is
3493
4320
  // compared, not just SKILL.md — the install script copies *.json and
@@ -3505,16 +4332,9 @@ async function doctorDelphi(options = {}) {
3505
4332
  // Injectable for tests (#414 R3 FC-01/FC-02): the empty-bundle branch is a
3506
4333
  // real failure mode and must be drivable without mutating the package.
3507
4334
  const bundledSkillDir = options.bundledSkillDir || path.join(PKG_DIR, 'skills', 'delphi-review');
3508
- const sha256 = (p) => require('crypto').createHash('sha256').update(fs.readFileSync(p)).digest('hex');
3509
- const listBundledSkillFiles = (dir, base = dir, out = []) => {
3510
- if (!fs.existsSync(dir)) return out;
3511
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
3512
- const p = path.join(dir, entry.name);
3513
- if (entry.isDirectory()) listBundledSkillFiles(p, base, out);
3514
- else out.push(path.relative(base, p));
3515
- }
3516
- return out;
3517
- };
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.
3518
4338
  // #725 follow-up: decide "installed anywhere?" from the full platform set, not
3519
4339
  // just the directory `detectPlatform()` selects — a dsh-only machine has no
3520
4340
  // marker detectPlatform() keys on, so the opencode fallback directory never
@@ -3535,63 +4355,262 @@ async function doctorDelphi(options = {}) {
3535
4355
  add('Delphi skill install parity', 'FAIL',
3536
4356
  `bundled skill directory missing or empty: ${bundledSkillDir} — reinstall xp-gate`);
3537
4357
  } else {
3538
- // #725: check every platform that has the skill deployed, not only the one
3539
- // `detectPlatform()` selects. On a machine with both Qoder and OpenCode the
3540
- // OpenCode copy was frozen at an old version and this check reported PASS,
3541
- // because it never looked there -- the drifted copy was invisible to both
3542
- // `update-skill` and `doctor`.
3543
- const drifted = [];
3544
- for (const dir of deployedDirs) {
3545
- const dirDrift = collectSkillDrift(dir, bundledFiles, bundledSkillDir, sha256);
3546
- if (dirDrift.length > 0) {
3547
- drifted.push(`${platformTag(dir)}: ${dirDrift.join(', ')}`);
3548
- }
3549
- }
3550
- if (drifted.length > 0) {
3551
- add('Delphi skill install parity', 'FAIL',
3552
- `installed copy differs from the ${getCliVersionSafe()} bundle — `
3553
- + `${drifted.slice(0, 3).join('; ')}${drifted.length > 3 ? '; ...' : ''} `
3554
- + '(reinstall: xp-gate install-skill delphi-review --force)');
3555
- } else {
3556
- add('Delphi skill install parity', 'PASS',
3557
- `${bundledFiles.length} file(s) match the bundle across ${deployedDirs.length} platform(s)`);
3558
- }
4358
+ reportSkillParity(add, deployedDirs, bundledFiles, bundledSkillDir, sha256);
3559
4359
  }
3560
4360
  }
4361
+ return installedSkillDir;
4362
+ }
3561
4363
 
3562
- // 4. Runner script locate: the runner must be findable from the places a
3563
- // review actually starts.
3564
- const runnerCandidates = [
3565
- ['package bundle', path.join(PKG_DIR, 'scripts', 'delphi-external-review.cjs')],
3566
- ['project', path.join(process.cwd(), 'scripts', 'delphi-external-review.cjs')],
3567
- ['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'),
3568
4485
  ];
3569
- const foundRunner = runnerCandidates.filter(([, p]) => fs.existsSync(p));
3570
- add('delphi-external-review runner', foundRunner.length > 0 ? 'PASS' : 'FAIL',
3571
- foundRunner.length > 0
3572
- ? foundRunner.map(([label, p]) => `${label}: ${p}`).join('; ')
3573
- : '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
+ }
3574
4492
 
3575
- // 5. Config ping: parseable, three distinct callable models. A duplicate
3576
- // model here is a review that will BLOCK later — say so now.
3577
- //
3578
- // #684: resolve the SAME way the runner does. A project-local config wins; a
3579
- // machine-level one under XDG_CONFIG_HOME (or ~/.config) is the documented
3580
- // fallback, and a review keeps working on it. Checking only `cwd` reported
3581
- // FAIL on the layout SKILL.md recommends and told the user to copy the example
3582
- // into the project — manufacturing the drifted duplicate #541 warns about.
3583
- //
3584
- // An explicit `configPath` is an ANSWER, not a hint: a caller that names a
3585
- // file means that file, so it disables the fallback. Otherwise a test (or a
3586
- // caller) pinning an absent path silently reads the developer's real global
3587
- // config and reports PASS — the same vacuous-pass shape this batch is fixing.
3588
- const projectCfgPath = configPath
3589
- || path.join(options.projectDir || process.cwd(), '.delphi-config.json');
3590
- const usingGlobalConfig = !configPath
3591
- && !fs.existsSync(projectCfgPath)
3592
- && fs.existsSync(globalConfigPath);
3593
- const cfgPath = usingGlobalConfig ? globalConfigPath : projectCfgPath;
3594
- 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;
3595
4614
  if (!fs.existsSync(cfgPath)) {
3596
4615
  add(cfgLabel, 'FAIL',
3597
4616
  `${cfgPath} not found (copy .delphi-config.json.example from the skill directory)`);
@@ -3603,22 +4622,9 @@ async function doctorDelphi(options = {}) {
3603
4622
  if (!profile) {
3604
4623
  add(cfgLabel, 'FAIL', `profile "${profileName}" not found`);
3605
4624
  } else {
3606
- const experts = profile.experts || {};
3607
- const models = roles.map((r) => experts[r] && experts[r].model);
3608
- const providers = profile.providers || {};
3609
- const missingRoles = roles.filter((r, i) => !models[i]);
3610
- const duplicates = models.filter((m, i) => m && models.indexOf(m) !== i);
3611
- const badProviders = roles.filter((r) => {
3612
- const e = experts[r];
3613
- return !e || !providers[e.provider]
3614
- || !providers[e.provider].base_url
3615
- || String(providers[e.provider].base_url).indexOf('http') !== 0;
3616
- });
3617
- if (missingRoles.length > 0 || duplicates.length > 0 || badProviders.length > 0) {
3618
- const problems = [];
3619
- if (missingRoles.length > 0) problems.push(`missing experts: ${missingRoles.join(', ')}`);
3620
- if (duplicates.length > 0) problems.push(`duplicate models: ${[...new Set(duplicates)].join(', ')}`);
3621
- 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) {
3622
4628
  add(cfgLabel, 'FAIL', problems.join('; '));
3623
4629
  } else {
3624
4630
  // Always name the file that was actually read. Without it a user with
@@ -3636,120 +4642,87 @@ async function doctorDelphi(options = {}) {
3636
4642
  // same allowlist and exit code; doctor reports it here so the guard
3637
4643
  // finally has a caller (`xp-gate doctor delphi`) instead of existing
3638
4644
  // only in its own docstring.
3639
- const hostedSeats = roles.filter((r) => {
3640
- const m = models[roles.indexOf(r)];
3641
- return m && !String(m).toLowerCase().startsWith('local-');
3642
- });
3643
- if (hostedSeats.length > 0) {
3644
- add('Delphi local-model guard (#574)', 'WARN',
3645
- `hosted (non local-*) seats: ${hostedSeats.map((r) => `${r}=${models[roles.indexOf(r)]}`).join(', ')} — `
3646
- + 'local-only review is the standing rule; run: python scripts/check_delphi_local_models.py --probe');
3647
- } else {
3648
- add('Delphi local-model guard (#574)', 'PASS', `all ${roles.length} seats are local-*`);
3649
- }
3650
- }
3651
- // #541 follow-up: shadow detection. Loaders fall back to the global
3652
- // config ONLY on ENOENT, so this project file always wins here. If the
3653
- // machine-wide config exists AND seats differ, the effective model mix
3654
- // depends on cwd — the cross-project drift class behind the 2026-10-03
3655
- // quota burn. Warn (intentional overrides are legal), never fail.
3656
- try {
3657
- if (fs.existsSync(globalConfigPath) && path.resolve(globalConfigPath) !== path.resolve(cfgPath)) {
3658
- const gRaw = JSON.parse(fs.readFileSync(globalConfigPath, 'utf8'));
3659
- const gProfileName = gRaw.active_profile || 'default';
3660
- const gProfile = gRaw.profiles && gRaw.profiles[gProfileName];
3661
- const gExperts = (gProfile && gProfile.experts) || {};
3662
- // Seat shape is object-keyed OR array in the wild (delphi-config.ts
3663
- // accepts both); normalize to a role->model map before comparing.
3664
- const pickExpert = (experts, role, idx) => {
3665
- if (!experts) return null;
3666
- if (Array.isArray(experts)) {
3667
- const e = experts.find((x) => x && x.role === role) || experts[idx];
3668
- return (e && e.model) || null;
3669
- }
3670
- return (experts[role] && experts[role].model) || null;
3671
- };
3672
- const gModels = roles.map((r, i) => pickExpert(gExperts, r, i));
3673
- // Compare only roles BOTH sides define: a role missing on one side
3674
- // is an incomplete config (check 5 already FAILs it), not drift.
3675
- const differing = roles.filter((r, i) => gModels[i] && models[i] && gModels[i] !== models[i]);
3676
- if (differing.length > 0) {
3677
- add('Delphi config shadow (#541)', 'WARN',
3678
- `project config shadows ${globalConfigPath}; seats differ (${differing.join(', ')}) — reviews run from other directories will use different models`);
3679
- }
3680
- }
3681
- } catch {
3682
- // A broken/unreadable global config is not this check's failure mode;
3683
- // silence here must not mask it elsewhere, so nothing is claimed.
4645
+ reportHostedSeats(add, models);
3684
4646
  }
4647
+ reportConfigShadow({ add, cfgPath, globalConfigPath, models });
3685
4648
  }
3686
4649
  } catch (err) {
3687
4650
  add(cfgLabel, 'FAIL', `unparseable: ${err.message}`);
3688
4651
  }
3689
4652
  }
3690
4653
 
3691
- // 6. Version consistency (#414 REQ-6): local files first. The npm-latest
3692
- // probe is opt-in (options.probeNpmLatest) or pre-supplied
3693
- // (options.npmLatest) — the doctor never blocks on the network, which is
3694
- // what an offline CI or restricted shell would otherwise hit (#414 R1 FC-03).
3695
- const localVersion = getCliVersionSafe();
3696
- let versionStatus = 'PASS';
3697
- let versionDetail = `xp-gate ${localVersion}`;
3698
- if (npmLatest === undefined && options.probeNpmLatest === true) {
3699
- try {
3700
- versionDetail += `; npm latest probe: ${execWithTimeout('npm view @boyingliu01/xp-gate version', 8000).trim()}`;
3701
- } catch {
3702
- versionStatus = 'SKIP';
3703
- versionDetail += '; npm latest probe unavailable (offline?) — skipped';
3704
- }
3705
- } else if (typeof npmLatest === 'string' && npmLatest !== localVersion) {
3706
- versionStatus = 'FAIL';
3707
- versionDetail += `; npm latest ${npmLatest} differs from local ${localVersion} — update (npm install -g @boyingliu01/xp-gate@latest) or verify which side is stale`;
3708
- } else if (npmLatest === null || options.probeNpmLatest !== true) {
3709
- versionDetail += '; npm latest probe skipped (pass --npm-check or options.probeNpmLatest to run it)';
3710
- }
3711
- add('Delphi version consistency', versionStatus, versionDetail);
4654
+ }
3712
4655
 
3713
- // 7. DSH native-channel readiness (#443 REQ-6): only meaningful when a DSH
3714
- // home exists. The two-layer switch (preset capability + host setting)
3715
- // defaults to disabled, and a review that assumes native will silently run
3716
- // three same-model seats.
3717
- const dshHome = path.join(HOME_DIR(), '.dsh');
3718
- if (!fs.existsSync(dshHome)) {
3719
- add('DSH subagent model selection', 'SKIP', `no ${dshHome} — not a DSH environment`);
3720
- } else {
3721
- const settingsCandidates = [
3722
- path.join(dshHome, 'settings.json'),
3723
- path.join(dshHome, 'settings', 'settings.json'),
3724
- path.join(dshHome, 'config.json'),
3725
- ];
3726
- const settingsFile = settingsCandidates.find((p) => fs.existsSync(p));
3727
- if (!settingsFile) {
3728
- add('DSH subagent model selection', 'FAIL',
3729
- `${dshHome} exists but no settings file found — subagent model selection defaults to disabled (#443)`);
3730
- } else {
3731
- try {
3732
- const settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
3733
- const selection = settings.subagentModelSelection;
3734
- const allowed = selection && Array.isArray(selection.allowedModels) ? selection.allowedModels : [];
3735
- const ids = allowed.map((m) => (typeof m === 'string' ? m : m && m.id)).filter(Boolean);
3736
- if (selection && selection.enabled === true && new Set(ids).size >= 3) {
3737
- add('DSH subagent model selection', 'PASS', `${settingsFile}: enabled, ${new Set(ids).size} distinct allowed models`);
3738
- } else if (selection && selection.enabled === true) {
3739
- add('DSH subagent model selection', 'FAIL',
3740
- `${settingsFile}: enabled but only ${new Set(ids).size} distinct allowedModels (need ≥3) — native channel unusable`);
3741
- } else {
3742
- // The switch shipping off is the platform default, not a defect:
3743
- // only an operator who explicitly enables it and under-provisions
3744
- // allowedModels has a real misconfiguration (#414 R1 FC-07).
3745
- add('DSH subagent model selection', 'SKIP',
3746
- `${settingsFile}: native model selection disabled (platform default) — the external channel is the contract path (#443)`);
3747
- }
3748
- } catch (err) {
3749
- add('DSH subagent model selection', 'SKIP', `${settingsFile} unparseable: ${err.message}`);
3750
- }
3751
- }
3752
- }
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);
3753
4726
 
3754
4727
  for (const check of checks) {
3755
4728
  const mark = check.status === 'PASS' ? '✓' : check.status === 'SKIP' ? '○' : check.status === 'WARN' ? '⚠' : '✗';
@@ -3817,6 +4790,33 @@ function platformTag(skillDir) {
3817
4790
  * Files in `skillDir` that are missing or differ from the bundle.
3818
4791
  * @returns {string[]} `rel: reason` entries; empty when the copy is clean
3819
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
+
3820
4820
  function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
3821
4821
  const drifted = [];
3822
4822
  for (const rel of bundledFiles) {
@@ -3824,15 +4824,22 @@ function collectSkillDrift(skillDir, bundledFiles, bundledSkillDir, sha256) {
3824
4824
  const bundledPath = path.join(bundledSkillDir, rel);
3825
4825
  if (!fs.existsSync(installedPath)) {
3826
4826
  drifted.push(`${rel}: missing`);
3827
- } else if (sha256(installedPath) !== sha256(bundledPath)) {
3828
- 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`);
3829
4833
  }
3830
4834
  }
3831
4835
  return drifted;
3832
4836
  }
3833
4837
 
3834
4838
  module.exports = {
3835
- 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,
3836
4843
  fixVersionMismatch,
3837
4844
  fixTemplateDirMismatch,
3838
4845
  fixMissingHooks,