@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
@@ -1,1320 +0,0 @@
1
- /**
2
- * @test REQ-2 xp-gate doctor
3
- * @intent Verify doctor correctly diagnoses installation health, handles --fix, and detects partial uninstall
4
- * @covers AC-05, AC-08, AC-10
5
- */
6
- const fs = require('fs');
7
- const path = require('path');
8
- const os = require('os');
9
- const cp = require('child_process');
10
- const util = require('util');
11
-
12
- // Unique ID scoped to this describe block — prevents collisions when
13
- // tests run in parallel across worker threads.
14
- const DESCRIBE_ID = String(Math.random().toString(36).slice(2, 8));
15
-
16
- // Budget for every case in this file. `doctor --fix` walks the whole install
17
- // surface (hooks, adapters, config, version cache) and the default 5 s budget is
18
- // a measurement of an idle machine, not of one running a full suite: under
19
- // concurrent load the same passing case times out, which reads as a doctor
20
- // defect. 30 s keeps real hangs bounded while leaving the CPU contention room.
21
- const DOCTOR_TIMEOUT_MS = 30000;
22
-
23
- describe('doctor', () => {
24
- // Applies to every `it` below (the per-test arg is only needed when overriding).
25
- vi.setConfig({ testTimeout: DOCTOR_TIMEOUT_MS });
26
- let tmpHome;
27
- let tmpProject;
28
- let originalHome;
29
- let originalXpGateCacheDir;
30
- let originalRepoRoot;
31
- let originalDetectDepsTools;
32
- let originalExecSync;
33
- let originalExec;
34
- let originalSpawnSync;
35
- let logSpy;
36
-
37
- beforeAll(() => {
38
- // Snapshot + suppress: Test fixtures don't install real CLI tools.
39
- delete require.cache[require.resolve('../detect-deps.js')];
40
- const detectDeps = require('../detect-deps.js');
41
- if (Array.isArray(detectDeps.GATE_CLI_TOOLS)) {
42
- originalDetectDepsTools = [...detectDeps.GATE_CLI_TOOLS];
43
- detectDeps.GATE_CLI_TOOLS.length = 0;
44
- }
45
- // Mock checkBash to return success by default (tests override as needed)
46
- detectDeps.checkBash = () => ({
47
- ok: true,
48
- path: 'bash',
49
- version: '5.1.16',
50
- });
51
- });
52
-
53
- afterAll(() => {
54
- // Restore the shared global so downstream suite runs are not polluted.
55
- if (originalDetectDepsTools) {
56
- delete require.cache[require.resolve('../detect-deps.js')];
57
- const detectDeps = require('../detect-deps.js');
58
- if (Array.isArray(detectDeps.GATE_CLI_TOOLS)) {
59
- detectDeps.GATE_CLI_TOOLS.length = 0;
60
- detectDeps.GATE_CLI_TOOLS.push(...originalDetectDepsTools);
61
- }
62
- }
63
- });
64
-
65
- beforeEach(() => {
66
- originalHome = process.env.HOME;
67
- originalXpGateCacheDir = process.env.XP_GATE_CACHE_DIR;
68
- originalRepoRoot = process.env.XP_GATE_REPO_ROOT;
69
- originalExecSync = cp.execSync;
70
- originalExec = cp.exec;
71
- originalSpawnSync = cp.spawnSync;
72
- // Unique per-describe + per-test prefixes to avoid parallel collisions.
73
- tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), `xpgate-dr-${DESCRIBE_ID}-`));
74
- tmpProject = fs.mkdtempSync(path.join(os.tmpdir(), `xpgate-dr-proj-${DESCRIBE_ID}-`));
75
- process.env.HOME = tmpHome;
76
- // #451: the hook-drift check reads the canonical githooks/ of *this* repo
77
- // when no override is given. In a fixture whose whole point is "a healthy
78
- // installation", that would compare the real checkout against synthetic
79
- // temp files and always report drift. Point it at an empty dir instead:
80
- // these tests assert installation health, not drift.
81
- process.env.XP_GATE_REPO_ROOT = path.join(tmpProject, 'no-repo-hooks');
82
- vi.resetModules();
83
- // Invalidate all cached modules that load path/environment globals at require-time.
84
- // Do NOT invalidate detect-deps.js — its GATE_CLI_TOOLS was already cleared in beforeAll
85
- // and reloading it would restore the full tool list, breaking the test mock setup.
86
- const modulesToInvalidate = [
87
- '../doctor', '../uninstall', '../init', '../shared-paths',
88
- '../check-version.js', '../doctor-tui', '../language-tools.js',
89
- ];
90
- for (const mod of modulesToInvalidate) {
91
- try { delete require.cache[require.resolve(mod)]; } catch { /* first load */ }
92
- }
93
- // Language-tool and registry probing are not what this file tests, but
94
- // doctor() reaches both on every call:
95
- //
96
- // 1. diagnoseLanguageTools() scans process.cwd() -- and a vitest worker
97
- // cannot be chdir'd ("process.chdir() is not supported in workers"), so
98
- // cwd is always the real xp-gate checkout. That tree is recognised as a
99
- // TypeScript/Shell/... project, so `checkTool()` runs real subprocesses
100
- // (`eslint --version`, `npx --no-install archlint --version`,
101
- // `shellcheck --version`, `pwsh --version`, `terraform --version`, ...).
102
- // 2. diagnoseUpgrade() -> checkUpgrade() issues a real HTTPS request to
103
- // https://registry.npmjs.org/-/package/<pkg>/dist-tags and waits on it.
104
- // Seeding version-cache.json does not prevent the fetch, so every case
105
- // paid the network round trip -- this was the larger half of the cost.
106
- //
107
- // Measured 2026-11-11 on one doctor() call with a config present (i.e. the
108
- // full check suite): 2140 ms / 1064 ms unstubbed versus 239 ms / 248 ms with
109
- // both stubbed (ABBA). XP_GATE_REPO_ROOT already redirects the hook-drift
110
- // check to an empty dir for the same reason; this closes the remaining paths.
111
- //
112
- // Why it is safe: no case in this file asserts anything about language-tool
113
- // detection or upgrade advice -- neither the "Language-Specific Tools"
114
- // section nor the upgrade message is matched in any expectation. Both stubs
115
- // are re-applied on every test because vi.resetModules() above discards
116
- // them, and they must be installed BEFORE require('../doctor') captures its
117
- // destructured imports.
118
- const languageTools = require('../language-tools.js');
119
- languageTools.getToolsForLanguages = () => ({});
120
- languageTools.detectProjectLanguages = () => ({ detected: [], configFiles: {} });
121
- const checkVersion = require('../check-version.js');
122
- checkVersion.checkUpgrade = async () => ({ status: 'current' });
123
- checkVersion.formatUpgradeMsg = () => '';
124
- logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
125
- vi.spyOn(console, 'warn').mockImplementation(() => {});
126
- vi.spyOn(console, 'error').mockImplementation(() => {});
127
- // doctor.js destructures `const { execSync, execFileSync, spawnSync } =
128
- // require('child_process')`, so each reloaded copy captures the function
129
- // objects that exist at require time. Patching cp.spawnSync AFTER the
130
- // reload has no effect on it -- that was tried, and the file did not get
131
- // faster by a single millisecond. The patch therefore goes on the module
132
- // object here, before the next test's `require('../doctor')` runs.
133
- //
134
- // Why it is safe: checkSpawnCapability() exists to warn a user whose sandbox
135
- // forbids sync spawns, and no case in this file asserts its verdict. Every
136
- // real git call here is likewise probing an environment the fixtures have
137
- // deliberately redirected to tmpHome/tmpProject, so "not a git repository"
138
- // is the honest answer rather than a fabricated one. Measured on this
139
- // machine, one doctor() call spent 80% of its samples inside spawnSync.
140
- cp.spawnSync = () => ({ error: null, status: 0, stdout: 'v24.0.0\n', stderr: '' });
141
- });
142
-
143
- afterEach(() => {
144
- process.env.HOME = originalHome;
145
- process.env.XP_GATE_CACHE_DIR = originalXpGateCacheDir;
146
- if (originalRepoRoot === undefined) delete process.env.XP_GATE_REPO_ROOT;
147
- else process.env.XP_GATE_REPO_ROOT = originalRepoRoot;
148
- cp.execSync = originalExecSync;
149
- cp.exec = originalExec;
150
- cp.spawnSync = originalSpawnSync;
151
- if (tmpHome && fs.existsSync(tmpHome)) {
152
- fs.rmSync(tmpHome, { recursive: true, force: true });
153
- }
154
- if (tmpProject && fs.existsSync(tmpProject)) {
155
- fs.rmSync(tmpProject, { recursive: true, force: true });
156
- }
157
- vi.restoreAllMocks();
158
- });
159
-
160
- function configFile() {
161
- return path.join(tmpHome, '.config', 'xp-gate', 'xp-gate.json');
162
- }
163
-
164
- function globalHooksDir() {
165
- return path.join(tmpHome, '.config', 'xp-gate', 'hooks');
166
- }
167
-
168
- function globalAdaptersDir() {
169
- return path.join(tmpHome, '.config', 'xp-gate', 'adapters');
170
- }
171
-
172
- function projectHooksDir() {
173
- return path.join(tmpProject, '.git', 'hooks');
174
- }
175
-
176
- function projectGithooksDir() {
177
- return path.join(tmpProject, 'githooks');
178
- }
179
-
180
- function projectAdaptersDir() {
181
- return path.join(tmpProject, 'githooks', 'adapters');
182
- }
183
-
184
- /**
185
- * Make sure the generated adapters mirror exists under src/npm-package/.
186
- *
187
- * It is gitignored and produced by `scripts/sync-package-content.js` at
188
- * prepack time, so a clean checkout has no source for `--fix` to restore
189
- * from. Runs the real generator (not a copy) so the fixture cannot drift from
190
- * what actually ships.
191
- */
192
- function ensureAdapterSourceGenerated() {
193
- const pkgRoot = path.join(__dirname, '..', '..');
194
- const mirror = path.join(pkgRoot, 'adapters');
195
- if (fs.existsSync(path.join(mirror, 'typescript.sh'))) return;
196
- require('node:child_process').execFileSync(
197
- process.execPath,
198
- [path.join(pkgRoot, 'scripts', 'sync-package-content.js')],
199
- { cwd: pkgRoot, stdio: 'ignore' }
200
- );
201
- }
202
-
203
- function createXpGatePreCommit(dir) {
204
- fs.mkdirSync(dir, { recursive: true });
205
- fs.writeFileSync(
206
- path.join(dir, 'pre-commit'),
207
- '#!/bin/bash\n# OpenCode Quality Gates - Pre-Commit Hook - Test\n'
208
- );
209
- }
210
-
211
- function createXpGatePrePush(dir) {
212
- fs.mkdirSync(dir, { recursive: true });
213
- // Mirror the banner the shipped hook actually carries. The previous fixture used
214
- // '# Pre-push Hook — 8 gates:', which no shipped hook has ever contained -- so
215
- // these "healthy install" cases passed against a fixture while every real
216
- // installation failed (#854). A fixture that disagrees with the product turns
217
- // the test into a check on itself.
218
- fs.writeFileSync(
219
- path.join(dir, 'pre-push'),
220
- '#!/bin/bash\n# Pre-push Hook: Gate 10 (Build Integrity) + M (Mutation)\n'
221
- );
222
- }
223
-
224
- function createXpGatePostMerge(dir) {
225
- fs.mkdirSync(dir, { recursive: true });
226
- fs.writeFileSync(
227
- path.join(dir, 'post-merge'),
228
- '#!/usr/bin/env bash\n# post-merge - XP-Gate VERSION sync hook\n'
229
- );
230
- }
231
-
232
- function createXpGateAdapterCommon(dir) {
233
- fs.mkdirSync(dir, { recursive: true });
234
- fs.writeFileSync(
235
- path.join(dir, 'adapter-common.sh'),
236
- '#!/usr/bin/env bash\n\n# Common adapter functions\ndetect_project_lang() {\n echo "typescript"\n}\n'
237
- );
238
- }
239
-
240
- function createXpGateAdapterScripts(dir) {
241
- fs.mkdirSync(path.join(dir, 'adapters'), { recursive: true });
242
- fs.writeFileSync(
243
- path.join(dir, 'adapters', 'typescript.sh'),
244
- '#!/usr/bin/env bash\necho "ts adapter"\n'
245
- );
246
- fs.writeFileSync(
247
- path.join(dir, 'adapters', 'python.sh'),
248
- '#!/usr/bin/env bash\necho "py adapter"\n'
249
- );
250
- const gateScripts = require('../deploy-manifest.js').GATE_FILES.filter(g => g !== 'gate-registry.sh');
251
- for (const script of gateScripts) {
252
- fs.writeFileSync(path.join(dir, 'adapters', script), `#!/bin/bash\n# ${script}\n`);
253
- }
254
- }
255
-
256
- function tuiJsonPath() {
257
- return path.join(tmpHome, '.config', 'opencode', 'tui.json');
258
- }
259
-
260
- function ensureTuiRegistered() {
261
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
262
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ plugin: ['@boyingliu01/opencode-plugin/tui'] }, null, 2));
263
- }
264
-
265
- function setupLocalInstall() {
266
- createXpGatePreCommit(projectHooksDir());
267
- createXpGatePrePush(projectHooksDir());
268
- createXpGatePostMerge(projectHooksDir());
269
- createXpGateAdapterCommon(projectGithooksDir());
270
- createXpGateAdapterScripts(projectGithooksDir());
271
-
272
- fs.mkdirSync(path.dirname(configFile()), { recursive: true });
273
- fs.writeFileSync(
274
- configFile(),
275
- JSON.stringify({
276
- mode: 'local',
277
- lastInit: new Date().toISOString()
278
- }, null, 2)
279
- );
280
- }
281
-
282
- function setupGlobalInstall() {
283
- createXpGatePreCommit(globalHooksDir());
284
- createXpGatePrePush(globalHooksDir());
285
- createXpGatePostMerge(globalHooksDir());
286
- createXpGateAdapterCommon(globalAdaptersDir());
287
- // For global mode, create adapters directly in globalAdaptersDir (not in a subdirectory)
288
- fs.mkdirSync(globalAdaptersDir(), { recursive: true });
289
- fs.writeFileSync(path.join(globalAdaptersDir(), 'typescript.sh'), '#!/usr/bin/env bash\necho "ts adapter"\n');
290
- fs.writeFileSync(path.join(globalAdaptersDir(), 'python.sh'), '#!/usr/bin/env bash\necho "py adapter"\n');
291
- const gateScripts = require('../deploy-manifest.js').GATE_FILES.filter(g => g !== 'gate-registry.sh');
292
- for (const script of gateScripts) {
293
- fs.writeFileSync(path.join(globalAdaptersDir(), script), `#!/bin/bash\n# ${script}\n`);
294
- }
295
- createXpGatePreCommit(projectHooksDir());
296
- createXpGatePrePush(projectHooksDir());
297
- createXpGateAdapterCommon(projectGithooksDir());
298
- createXpGateAdapterScripts(projectGithooksDir());
299
-
300
- fs.mkdirSync(path.dirname(configFile()), { recursive: true });
301
- fs.writeFileSync(
302
- configFile(),
303
- JSON.stringify({
304
- mode: 'global',
305
- lastInit: new Date().toISOString()
306
- }, null, 2)
307
- );
308
- }
309
-
310
- function mockExecSuccess() {
311
- cp.execSync = (cmd) => {
312
- if (cmd === 'git rev-parse --git-dir') {
313
- return path.join(tmpProject, '.git') + '\n';
314
- }
315
- if (cmd.includes('git config --global core.hooksPath')) {
316
- if (cmd.includes('--unset')) {
317
- return '';
318
- }
319
- return globalHooksDir() + '\n';
320
- }
321
- if (cmd === 'node --version') {
322
- return 'v20.0.0\n';
323
- }
324
- if (cmd === 'git --version') {
325
- return 'git version 2.39.0\n';
326
- }
327
- return '';
328
- };
329
-
330
- // Async exec mock for execWithTimeout (util.promisify(exec) in doctor.js).
331
- // doctor.js destructures as const {stdout, stderr} = await execAsync(...),
332
- // so we MUST set [util.promisify.custom] to return {stdout, stderr} object.
333
- // Default promisify behavior for multi-value callbacks returns an array.
334
- const mockAsyncExec = (cmd, opts, callback) => {
335
- if (typeof opts === 'function') { callback = opts; opts = {}; }
336
- if (cmd === 'git rev-parse --git-dir') {
337
- callback(null, path.join(tmpProject, '.git') + '\n', '');
338
- } else if (cmd.includes('git config --global core.hooksPath')) {
339
- callback(null, cmd.includes('--unset') ? '' : globalHooksDir() + '\n', '');
340
- } else if (cmd === 'node --version') {
341
- callback(null, 'v20.0.0\n', '');
342
- } else if (cmd === 'git --version') {
343
- callback(null, 'git version 2.39.0\n', '');
344
- } else {
345
- callback(null, '', '');
346
- }
347
- };
348
- mockAsyncExec[util.promisify.custom] = (cmd, options) => {
349
- return new Promise((resolve, reject) => {
350
- mockAsyncExec(cmd, options, (err, stdout, stderr) => {
351
- if (err) { err.stdout = stdout || ''; err.stderr = stderr || ''; reject(err); }
352
- else { resolve({ stdout, stderr }); }
353
- });
354
- });
355
- };
356
- cp.exec = mockAsyncExec;
357
- }
358
-
359
- // doctor() calls checkUpgrade() which hits npm registry; seed cache to skip.
360
- // Set XP_GATE_CACHE_DIR so check-version.js resolves to the temp dir,
361
- // avoiding dependency on os.homedir() cross-platform behavior.
362
- function seedVersionCache() {
363
- process.env.XP_GATE_CACHE_DIR = path.join(tmpHome, '.xp-gate');
364
- const cacheDir = process.env.XP_GATE_CACHE_DIR;
365
- fs.mkdirSync(cacheDir, { recursive: true });
366
- fs.writeFileSync(
367
- path.join(cacheDir, 'version-cache.json'),
368
- JSON.stringify({ ts: Date.now(), version: '0.8.12', publishedAt: '' })
369
- );
370
- }
371
-
372
- function mockExecFail() {
373
- cp.execSync = () => {
374
- throw new Error('Command failed');
375
- };
376
- const mockAsyncExec = (cmd, opts, callback) => {
377
- if (typeof opts === 'function') { callback = opts; }
378
- callback(new Error('Command failed'), '', '');
379
- };
380
- mockAsyncExec[util.promisify.custom] = () => {
381
- return Promise.reject(new Error('Command failed'));
382
- };
383
- cp.exec = mockAsyncExec;
384
- }
385
-
386
- // === AC-05: healthy diagnosis ===
387
-
388
- it('AC-05: doctor reports all checks passed for healthy local install', async () => {
389
- setupLocalInstall();
390
- ensureTuiRegistered();
391
- seedVersionCache();
392
- mockExecSuccess();
393
- const { doctor } = require('../doctor');
394
-
395
- const result = await doctor([]);
396
-
397
- expect(result).toBe(0);
398
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Config file'));
399
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Hooks'));
400
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Adapters directory'));
401
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('All checks passed'));
402
- });
403
-
404
- it('AC-05: doctor reports all checks passed for healthy global install', async () => {
405
- setupGlobalInstall();
406
- ensureTuiRegistered();
407
- seedVersionCache();
408
- mockExecSuccess();
409
- const { doctor } = require('../doctor');
410
-
411
- const result = await doctor([]);
412
-
413
- expect(result).toBe(0);
414
- expect(logSpy).toHaveBeenCalledWith(
415
- expect.stringContaining('All checks passed')
416
- );
417
- });
418
-
419
- // === AC-08: partial uninstall detection ===
420
-
421
- it('AC-08: doctor detects missing hooks in partial install', async () => {
422
- setupLocalInstall();
423
- seedVersionCache();
424
- // Remove hooks to simulate partial state
425
- fs.unlinkSync(path.join(projectHooksDir(), 'pre-commit'));
426
- fs.unlinkSync(path.join(projectHooksDir(), 'pre-push'));
427
- mockExecSuccess();
428
- const { doctor } = require('../doctor');
429
-
430
- const result = await doctor([]);
431
-
432
- expect(result).toBe(1);
433
- expect(logSpy).toHaveBeenCalledWith(
434
- expect.stringContaining('Missing')
435
- );
436
- expect(logSpy).toHaveBeenCalledWith(
437
- expect.stringContaining('pre-commit')
438
- );
439
- });
440
-
441
- it('AC-08: doctor detects a missing post-merge hook', async () => {
442
- setupLocalInstall();
443
- seedVersionCache();
444
- fs.unlinkSync(path.join(projectHooksDir(), 'post-merge'));
445
- mockExecSuccess();
446
- const { doctor } = require('../doctor');
447
-
448
- const result = await doctor([]);
449
-
450
- expect(result).toBe(1);
451
- expect(logSpy).toHaveBeenCalledWith(
452
- expect.stringContaining('post-merge')
453
- );
454
- });
455
-
456
- it('AC-08: doctor detects missing config file', async () => {
457
- // No config at all
458
- const { doctor } = require('../doctor');
459
-
460
- const result = await doctor([]);
461
-
462
- expect(result).toBe(1);
463
- expect(logSpy).toHaveBeenCalledWith(
464
- expect.stringContaining('Config file: Not found')
465
- );
466
- });
467
-
468
- it('AC-08: doctor detects corrupt config JSON', async () => {
469
- fs.mkdirSync(path.dirname(configFile()), { recursive: true });
470
- fs.writeFileSync(configFile(), 'this is not json');
471
-
472
- const { doctor } = require('../doctor');
473
-
474
- const result = await doctor([]);
475
-
476
- expect(result).toBe(1);
477
- expect(logSpy).toHaveBeenCalledWith(
478
- expect.stringContaining('Corrupt JSON')
479
- );
480
- });
481
-
482
- it('AC-08: doctor detects missing adapters', async () => {
483
- setupLocalInstall();
484
- seedVersionCache();
485
- // Remove adapters dir
486
- fs.rmSync(projectAdaptersDir(), { recursive: true, force: true });
487
- mockExecSuccess();
488
- const { doctor } = require('../doctor');
489
-
490
- const result = await doctor([]);
491
-
492
- expect(result).toBe(1);
493
- expect(logSpy).toHaveBeenCalledWith(
494
- expect.stringContaining('Missing')
495
- );
496
- expect(logSpy).toHaveBeenCalledWith(
497
- expect.stringContaining('Adapters directory')
498
- );
499
- });
500
-
501
- it('AC-08: doctor detects wrong core.hooksPath in global mode', async () => {
502
- setupGlobalInstall();
503
- seedVersionCache();
504
- // Custom mock: returns wrong hooksPath to trigger detection
505
- cp.execSync = (cmd) => {
506
- if (cmd.includes('git config --global core.hooksPath')) {
507
- if (cmd.includes('--unset')) {
508
- return '';
509
- }
510
- return '/wrong/path\n';
511
- }
512
- if (cmd === 'git rev-parse --git-dir') {
513
- return path.join(tmpProject, '.git') + '\n';
514
- }
515
- if (cmd === 'node --version') {
516
- return 'v20.0.0\n';
517
- }
518
- if (cmd === 'git --version') {
519
- return 'git version 2.39.0\n';
520
- }
521
- return '';
522
- };
523
- // Async mock matching execSync above
524
- const mockAsyncExec = (cmd, opts, callback) => {
525
- if (typeof opts === 'function') { callback = opts; opts = {}; }
526
- if (cmd.includes('git config --global core.hooksPath')) {
527
- callback(null, cmd.includes('--unset') ? '' : '/wrong/path\n', '');
528
- } else if (cmd === 'git rev-parse --git-dir') {
529
- callback(null, path.join(tmpProject, '.git') + '\n', '');
530
- } else if (cmd === 'node --version') {
531
- callback(null, 'v20.0.0\n', '');
532
- } else if (cmd === 'git --version') {
533
- callback(null, 'git version 2.39.0\n', '');
534
- } else {
535
- callback(null, '', '');
536
- }
537
- };
538
- mockAsyncExec[util.promisify.custom] = (cmd, options) => {
539
- return new Promise((resolve, reject) => {
540
- mockAsyncExec(cmd, options, (err, stdout, stderr) => {
541
- if (err) { err.stdout = stdout || ''; err.stderr = stderr || ''; reject(err); }
542
- else { resolve({ stdout, stderr }); }
543
- });
544
- });
545
- };
546
- cp.exec = mockAsyncExec;
547
- const { doctor } = require('../doctor');
548
- const result = await doctor([]);
549
- expect(result).toBe(1);
550
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Expected '));
551
- });
552
-
553
- // === AC-10: --fix only when mode === "active" ===
554
-
555
- it('AC-10: doctor --fix does nothing when mode is uninstalled', async () => {
556
- fs.mkdirSync(path.dirname(configFile()), { recursive: true });
557
- fs.writeFileSync(
558
- configFile(),
559
- JSON.stringify({ mode: 'uninstalled', uninstalled: '2025-01-01' }, null, 2)
560
- );
561
-
562
- const { doctor } = require('../doctor');
563
- const result = await doctor(['--fix']);
564
- expect(result).toBe(0);
565
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('xp-gate is not installed'));
566
- });
567
-
568
- it('AC-10: doctor --fix reinstall hooks when mode is active and hooks missing', async () => {
569
- setupLocalInstall();
570
- seedVersionCache();
571
- // Remove hooks to create a fixable issue
572
- fs.unlinkSync(path.join(projectHooksDir(), 'pre-commit'));
573
- fs.unlinkSync(path.join(projectHooksDir(), 'pre-push'));
574
- mockExecSuccess();
575
- const { doctor } = require('../doctor');
576
- const result = await doctor(['--fix']);
577
- expect(result).toBe(0);
578
- expect(fs.existsSync(path.join(projectHooksDir(), 'pre-commit'))).toBe(true);
579
- expect(fs.existsSync(path.join(projectHooksDir(), 'pre-push'))).toBe(true);
580
- });
581
-
582
- it('AC-10: doctor --fix restores a missing post-merge hook', async () => {
583
- setupLocalInstall();
584
- seedVersionCache();
585
- fs.unlinkSync(path.join(projectHooksDir(), 'post-merge'));
586
- mockExecSuccess();
587
- const { doctor } = require('../doctor');
588
-
589
- const result = await doctor(['--fix']);
590
-
591
- expect(result).toBe(0);
592
- expect(fs.existsSync(path.join(projectHooksDir(), 'post-merge'))).toBe(true);
593
- });
594
-
595
- it('AC-10: doctor --fix reinstall adapters when mode is active and adapters missing', async () => {
596
- setupLocalInstall();
597
- seedVersionCache();
598
- // `src/npm-package/adapters/` is a GENERATED mirror since ccfc22f3 (P1-E): it
599
- // is gitignored, so a fresh CI checkout does not have it. `--fix` restores
600
- // adapters FROM that directory, so without it the restore is impossible,
601
- // the issue survives, and doctor correctly returns 1. Locally the directory
602
- // existed from an earlier build, which is why this only failed on CI.
603
- //
604
- // Generate it through the same prepack step that creates it in production,
605
- // rather than committing copies back or skipping the case.
606
- ensureAdapterSourceGenerated();
607
- // Remove adapters
608
- fs.rmSync(projectAdaptersDir(), { recursive: true, force: true });
609
- mockExecSuccess();
610
- const { doctor } = require('../doctor');
611
- const result = await doctor(['--fix']);
612
- expect(result).toBe(0);
613
- expect(fs.existsSync(projectAdaptersDir())).toBe(true);
614
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'typescript.sh'))).toBe(true);
615
- });
616
-
617
- it('AC-10: doctor --fix corrects core.hooksPath in global mode', async () => {
618
- setupGlobalInstall();
619
- ensureTuiRegistered();
620
- seedVersionCache();
621
- // Mock hooksPath pointing somewhere else
622
- cp.execSync = (cmd) => {
623
- if (cmd.includes('git config --global core.hooksPath')) {
624
- if (cmd.includes('--unset')) {
625
- return '';
626
- }
627
- // Return WRONG path to trigger fix
628
- return '/wrong/path\n';
629
- }
630
- if (cmd === 'git rev-parse --git-dir') {
631
- return path.join(tmpProject, '.git') + '\n';
632
- }
633
- if (cmd === 'node --version') {
634
- return 'v20.0.0\n';
635
- }
636
- if (cmd === 'git --version') {
637
- return 'git version 2.39.0\n';
638
- }
639
- return '';
640
- };
641
- // Async exec mock for execWithTimeout (util.promisify(exec) in doctor.js)
642
- const mockAsyncExec = (cmd, opts, callback) => {
643
- if (typeof opts === 'function') { callback = opts; opts = {}; }
644
- if (cmd === 'git rev-parse --git-dir') {
645
- callback(null, path.join(tmpProject, '.git') + '\n', '');
646
- } else if (cmd.includes('git config --global core.hooksPath')) {
647
- callback(null, cmd.includes('--unset') ? '' : '/wrong/path\n', '');
648
- } else if (cmd === 'node --version') {
649
- callback(null, 'v20.0.0\n', '');
650
- } else if (cmd === 'git --version') {
651
- callback(null, 'git version 2.39.0\n', '');
652
- } else {
653
- callback(null, '', '');
654
- }
655
- };
656
- mockAsyncExec[util.promisify.custom] = (cmd, options) => {
657
- return new Promise((resolve, reject) => {
658
- mockAsyncExec(cmd, options, (err, stdout, stderr) => {
659
- if (err) { err.stdout = stdout || ''; err.stderr = stderr || ''; reject(err); }
660
- else { resolve({ stdout, stderr }); }
661
- });
662
- });
663
- };
664
- cp.exec = mockAsyncExec;
665
- const { doctor } = require('../doctor');
666
-
667
- const result = await doctor(['--fix']);
668
-
669
- // Exit 1 because post-fix diagnosis still sees wrong path (mock returns wrong path)
670
- expect(result).toBe(1);
671
- // Verify fix was attempted — the hook files exist from setupGlobalInstall
672
- expect(fs.existsSync(path.join(globalHooksDir(), 'pre-commit'))).toBe(true);
673
- });
674
-
675
- it('AC-10: doctor --fix does NOT fix corrupt config', async () => {
676
- fs.mkdirSync(path.dirname(configFile()), { recursive: true });
677
- fs.writeFileSync(configFile(), 'not valid json');
678
-
679
- const { doctor } = require('../doctor');
680
-
681
- const result = await doctor(['--fix']);
682
-
683
- expect(result).toBe(1);
684
- // Corrupt config cannot be auto-fixed
685
- expect(logSpy).toHaveBeenCalledWith(
686
- expect.stringContaining('Corrupt JSON')
687
- );
688
- });
689
-
690
- // === Edge cases ===
691
-
692
- it('AC-488: doctor rejects unknown flags instead of silently ignoring them', async () => {
693
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
694
- const { doctor } = require('../doctor');
695
- const result = await doctor(['--syn-hooks', 'extra-arg']);
696
- expect(result).toBe(1);
697
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Unknown flag'));
698
- errorSpy.mockRestore();
699
- });
700
-
701
- it('AC-488: doctor still accepts its documented flags', async () => {
702
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
703
- const { doctor } = require('../doctor');
704
- const result = await doctor(['--fix', '--sync-hooks']);
705
- // Asserted on the RETURN VALUE as well as the absence of flag errors. "No
706
- // error was printed" alone cannot tell "the flags were understood" from "the
707
- // function never got far enough to print anything", which is exactly the
708
- // regression this case exists for: an unrecognised flag makes doctor bail out
709
- // before it reports anything, and silence reads as success.
710
- expect(errorSpy).not.toHaveBeenCalled();
711
- // AC-488 is about flag PARSING, not about this machine being healthy: the exit
712
- // code legitimately varies with the install state, so the assertion is that it
713
- // is a doctor verdict (0/1) rather than a crash or an undefined return.
714
- expect([0, 1]).toContain(result);
715
- errorSpy.mockRestore();
716
- });
717
-
718
- it('reports exit code 1 with unhealthy or missing install', async () => {
719
- const { doctor } = require('../doctor');
720
- const result = await doctor([]);
721
- expect(result).toBe(1);
722
- });
723
-
724
- it('detects missing environment dependencies', async () => {
725
- setupLocalInstall();
726
- seedVersionCache();
727
- // Make checkBash fail for this test (detect-deps module already loaded + mocked in beforeAll)
728
- const detectDeps = require('../detect-deps.js');
729
- const origCheckBash = detectDeps.checkBash;
730
- detectDeps.checkBash = () => ({ ok: false, message: 'Not found' });
731
- mockExecFail();
732
- const { doctor } = require('../doctor');
733
-
734
- const result = await doctor([]);
735
-
736
- expect(result).toBe(1);
737
- expect(logSpy).toHaveBeenCalledWith(
738
- expect.stringContaining('Not found')
739
- );
740
-
741
- // Restore
742
- detectDeps.checkBash = origCheckBash;
743
- });
744
-
745
- // === Issue #186: Version mismatch detection ===
746
-
747
- it('detects version mismatch when config version differs from package version', async () => {
748
- setupLocalInstall();
749
- seedVersionCache();
750
- // Write config with old version
751
- const cfg = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
752
- cfg.version = '0.3.1.1';
753
- fs.writeFileSync(configFile(), JSON.stringify(cfg, null, 2));
754
- mockExecSuccess();
755
- const { doctor } = require('../doctor');
756
-
757
- const result = await doctor([]);
758
-
759
- expect(result).toBe(1);
760
- expect(logSpy).toHaveBeenCalledWith(
761
- expect.stringContaining('Version mismatch')
762
- );
763
- expect(logSpy).toHaveBeenCalledWith(
764
- expect.stringContaining('0.3.1.1')
765
- );
766
- });
767
-
768
- it('passes version check when config version matches package version', async () => {
769
- setupLocalInstall();
770
- ensureTuiRegistered();
771
- seedVersionCache();
772
- // Write config with matching version
773
- const pkg = JSON.parse(fs.readFileSync(
774
- path.join(path.dirname(path.dirname(require.resolve('../doctor'))), 'package.json'), 'utf8'
775
- ));
776
- const cfg = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
777
- cfg.version = pkg.version;
778
- fs.writeFileSync(configFile(), JSON.stringify(cfg, null, 2));
779
- mockExecSuccess();
780
- const { doctor } = require('../doctor');
781
-
782
- const result = await doctor([]);
783
-
784
- expect(result).toBe(0);
785
- expect(logSpy).toHaveBeenCalledWith(
786
- expect.stringContaining('All checks passed')
787
- );
788
- });
789
-
790
- it('passes version check when config has no version field (legacy)', async () => {
791
- setupLocalInstall();
792
- ensureTuiRegistered();
793
- seedVersionCache();
794
- // Config without version field — legacy install, should not fail
795
- mockExecSuccess();
796
- const { doctor } = require('../doctor');
797
-
798
- const result = await doctor([]);
799
-
800
- expect(result).toBe(0);
801
- expect(logSpy).toHaveBeenCalledWith(
802
- expect.stringContaining('All checks passed')
803
- );
804
- });
805
-
806
- // === Issue #188: templateDir validation ===
807
-
808
- it('detects templateDir pointing to wrong platform directory', async () => {
809
- setupLocalInstall();
810
- seedVersionCache();
811
- // Write config with stale opencode templateDir when qoder is active
812
- const cfg = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
813
- cfg.templateDir = path.join(tmpHome, '.config', 'opencode', 'git-hooks-template');
814
- fs.writeFileSync(configFile(), JSON.stringify(cfg, null, 2));
815
-
816
- // Create qoder marker to simulate qoder environment
817
- fs.mkdirSync(path.join(tmpHome, '.qoder', 'skills'), { recursive: true });
818
-
819
- // Need fresh module because shared-paths caches detectPlatform at module load
820
- delete require.cache[require.resolve('../shared-paths')];
821
- delete require.cache[require.resolve('../doctor')];
822
- const { doctor: doc2 } = require('../doctor');
823
- mockExecSuccess();
824
-
825
- const result = await doc2([]);
826
-
827
- expect(result).toBe(1);
828
- expect(logSpy).toHaveBeenCalledWith(
829
- expect.stringContaining('templateDir')
830
- );
831
- expect(logSpy).toHaveBeenCalledWith(
832
- expect.stringContaining('opencode')
833
- );
834
- });
835
-
836
- it('passes templateDir check when templateDir matches current platform', async () => {
837
- setupLocalInstall();
838
- ensureTuiRegistered();
839
- seedVersionCache();
840
- // Write config with correct qoder templateDir
841
- const cfg = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
842
- cfg.templateDir = path.join(tmpHome, '.qoder', 'git-hooks-template');
843
- fs.writeFileSync(configFile(), JSON.stringify(cfg, null, 2));
844
-
845
- // Create qoder marker — must exist BEFORE loading shared-paths
846
- fs.mkdirSync(path.join(tmpHome, '.qoder', 'skills'), { recursive: true });
847
-
848
- // Fresh require so shared-paths detectPlatform() sees .qoder/skills
849
- delete require.cache[require.resolve('../shared-paths')];
850
- delete require.cache[require.resolve('../doctor')];
851
- mockExecSuccess();
852
- const { doctor: doc2 } = require('../doctor');
853
-
854
- const result = await doc2([]);
855
-
856
- expect(result).toBe(0);
857
- expect(logSpy).toHaveBeenCalledWith(
858
- expect.stringContaining('All checks passed')
859
- );
860
- });
861
-
862
- it('passes templateDir check when config has no templateDir field (legacy)', async () => {
863
- setupLocalInstall();
864
- ensureTuiRegistered();
865
- seedVersionCache();
866
- // Config without templateDir — legacy install, should not fail
867
- mockExecSuccess();
868
- const { doctor } = require('../doctor');
869
-
870
- const result = await doctor([]);
871
-
872
- expect(result).toBe(0);
873
- expect(logSpy).toHaveBeenCalledWith(
874
- expect.stringContaining('All checks passed')
875
- );
876
- });
877
-
878
- // === REQ-001-04: doctor 集成版本升级检查 (AC-004-01/02) ===
879
-
880
- it('AC-004-01: doctor shows upgrade prompt at end when outdated', async () => {
881
- setupLocalInstall();
882
- ensureTuiRegistered();
883
- mockExecSuccess();
884
- // Point cache dir to tmpHome and remove cache so checkUpgrade hits the npm registry
885
- process.env.XP_GATE_CACHE_DIR = path.join(tmpHome, '.xp-gate');
886
- const cacheFile = path.join(process.env.XP_GATE_CACHE_DIR, 'version-cache.json');
887
- if (fs.existsSync(cacheFile)) fs.unlinkSync(cacheFile);
888
-
889
- delete require.cache[require.resolve('../doctor')];
890
- delete require.cache[require.resolve('../check-version.js')];
891
- const { doctor } = require('../doctor');
892
-
893
- const result = await doctor([]);
894
-
895
- expect(result).toBe(0);
896
- // Doctor should output upgrade message when outdated
897
- const output = logSpy.mock.calls.map(c => c[0] || '').join('\n');
898
- expect(output).toMatch(/newer version|upgrade|v\d+\.\d+\.\d+/);
899
- }, 30000);
900
-
901
- it('AC-004-02: doctor does NOT show upgrade prompt when up to date', async () => {
902
- setupLocalInstall();
903
- ensureTuiRegistered();
904
- mockExecSuccess();
905
- // Point cache dir to tmpHome and write a cache with an old remote version
906
- // so compareVersions(local='0.12.9.0', remote='0.1.0') → outdated=false
907
- process.env.XP_GATE_CACHE_DIR = path.join(tmpHome, '.xp-gate');
908
- const cacheFile = path.join(process.env.XP_GATE_CACHE_DIR, 'version-cache.json');
909
- fs.mkdirSync(process.env.XP_GATE_CACHE_DIR, { recursive: true });
910
- fs.writeFileSync(cacheFile, JSON.stringify({
911
- ts: Date.now(),
912
- version: '0.1.0',
913
- publishedAt: ''
914
- }));
915
-
916
- delete require.cache[require.resolve('../doctor')];
917
- delete require.cache[require.resolve('../check-version.js')];
918
- const { doctor } = require('../doctor');
919
-
920
- const result = await doctor([]);
921
-
922
- expect(result).toBe(0);
923
- const output = logSpy.mock.calls.map(c => c[0] || '').join('\n');
924
- // Should NOT contain upgrade-related messages
925
- expect(output).not.toMatch(/newer version|upgrade/i);
926
- });
927
-
928
- it('AC-004-03: doctor does NOT fail when version check throws', async () => {
929
- setupLocalInstall();
930
- ensureTuiRegistered();
931
- seedVersionCache();
932
- mockExecSuccess();
933
- // Write corrupt cache to trigger checkUpgrade error path
934
- const cachePath = path.join(tmpHome, '.xp-gate', 'version-cache.json');
935
- fs.writeFileSync(cachePath, 'not json');
936
-
937
- delete require.cache[require.resolve('../doctor')];
938
- delete require.cache[require.resolve('../check-version.js')];
939
- const { doctor } = require('../doctor');
940
-
941
- // Doctor should NOT throw — version check is non-blocking
942
- const result = await doctor([]);
943
- expect(result).toBe(0);
944
- });
945
-
946
- // === Issue #186: --fix syncs global hooks from package source ===
947
-
948
- it('--fix syncs global hooks when they are outdated', async () => {
949
- setupGlobalInstall();
950
- seedVersionCache();
951
- // Write an outdated pre-commit hook (different content)
952
- const oldContent = '#!/bin/bash\n# OpenCode Quality Gates - Pre-Commit Hook - OLD VERSION\n';
953
- fs.writeFileSync(path.join(globalHooksDir(), 'pre-commit'), oldContent);
954
- mockExecSuccess();
955
- const { doctor } = require('../doctor');
956
-
957
- const result = await doctor(['--fix']);
958
-
959
- expect(result).toBe(0);
960
- // Should have restored from package source
961
- const restoredContent = fs.readFileSync(path.join(globalHooksDir(), 'pre-commit'), 'utf8');
962
- expect(restoredContent).not.toBe(oldContent);
963
- expect(logSpy).toHaveBeenCalledWith(
964
- expect.stringContaining('Restored')
965
- );
966
- });
967
-
968
- // === Check 9: TUI auto-registration (tui.json) ===
969
-
970
- it('Check 9: PASS when tui.json has @boyingliu01/opencode-plugin/tui registered', async () => {
971
- setupLocalInstall();
972
- seedVersionCache();
973
- mockExecSuccess();
974
- // Create tui.json with the plugin registered
975
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
976
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ plugin: ['@boyingliu01/opencode-plugin/tui'] }, null, 2));
977
- const { doctor } = require('../doctor');
978
-
979
- const result = await doctor([]);
980
-
981
- expect(result).toBe(0);
982
- expect(logSpy).toHaveBeenCalledWith(
983
- expect.stringContaining('@boyingliu01/opencode-plugin/tui registered')
984
- );
985
- });
986
-
987
- it('Check 9: FAIL when tui.json is missing', async () => {
988
- setupLocalInstall();
989
- seedVersionCache();
990
- mockExecSuccess();
991
- // Ensure no tui.json
992
- if (fs.existsSync(tuiJsonPath())) fs.unlinkSync(tuiJsonPath());
993
- const { doctor } = require('../doctor');
994
-
995
- const result = await doctor([]);
996
-
997
- expect(result).toBe(1);
998
- expect(logSpy).toHaveBeenCalledWith(
999
- expect.stringContaining('TUI registration: Not registered')
1000
- );
1001
- });
1002
-
1003
- it('Check 9: FAIL when tui.json exists without @boyingliu01/opencode-plugin/tui entry', async () => {
1004
- setupLocalInstall();
1005
- seedVersionCache();
1006
- mockExecSuccess();
1007
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
1008
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ plugin: ['some-other-plugin'] }, null, 2));
1009
- const { doctor } = require('../doctor');
1010
-
1011
- const result = await doctor([]);
1012
-
1013
- expect(result).toBe(1);
1014
- expect(logSpy).toHaveBeenCalledWith(
1015
- expect.stringContaining('TUI registration: Not registered')
1016
- );
1017
- });
1018
-
1019
- it('Check 9: WARN when tui.json exists but has no plugin array', async () => {
1020
- setupLocalInstall();
1021
- seedVersionCache();
1022
- mockExecSuccess();
1023
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
1024
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ someKey: 'value' }, null, 2));
1025
- const { doctor } = require('../doctor');
1026
-
1027
- const result = await doctor([]);
1028
-
1029
- expect(result).toBe(1);
1030
- expect(logSpy).toHaveBeenCalledWith(
1031
- expect.stringContaining('TUI registration: Not registered')
1032
- );
1033
- });
1034
-
1035
- it('Check 9: FAIL with backup when tui.json is corrupt JSON', async () => {
1036
- setupLocalInstall();
1037
- seedVersionCache();
1038
- mockExecSuccess();
1039
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
1040
- fs.writeFileSync(tuiJsonPath(), 'this is not { valid json');
1041
- const { doctor } = require('../doctor');
1042
-
1043
- const result = await doctor([]);
1044
-
1045
- expect(result).toBe(1);
1046
- expect(logSpy).toHaveBeenCalledWith(
1047
- expect.stringContaining('TUI registration: Corrupt')
1048
- );
1049
- });
1050
-
1051
- // === --fix TUI registration ===
1052
-
1053
- // 15s, not vitest's 5s default (#588). This case runs the full `doctor(['--fix'])`
1054
- // pipeline over a real temp install: it writes hooks, adapters and tui.json and
1055
- // re-diagnoses. Measured in isolation it takes ~3.8s, which is already 76% of the
1056
- // default budget — so under the full suite (where 200 files share the machine) it
1057
- // crossed 5s and failed with "Test timed out in 5000ms". The work is legitimate;
1058
- // the budget was simply too tight for it. Similar cases in this file take 2-4s.
1059
- it('--fix: diagnoses TUI not registered then re-diagnoses after fix', { timeout: 15000 }, async () => {
1060
- setupLocalInstall();
1061
- seedVersionCache();
1062
- mockExecSuccess();
1063
- // No tui.json
1064
- if (fs.existsSync(path.join(tmpHome, '.config', 'opencode'))) {
1065
- fs.rmSync(path.join(tmpHome, '.config', 'opencode'), { recursive: true, force: true });
1066
- }
1067
- const { doctor } = require('../doctor');
1068
-
1069
- const result = await doctor(['--fix']);
1070
-
1071
- expect(result).toBe(0);
1072
- // After fix, tui.json should exist with the plugin registered
1073
- expect(fs.existsSync(tuiJsonPath())).toBe(true);
1074
- const tui = JSON.parse(fs.readFileSync(tuiJsonPath(), 'utf8'));
1075
- expect(tui.plugin).toContain('@boyingliu01/opencode-plugin/tui');
1076
- });
1077
-
1078
- it('--fix: append to existing tui.json plugin array', async () => {
1079
- setupLocalInstall();
1080
- seedVersionCache();
1081
- mockExecSuccess();
1082
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
1083
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ plugin: ['some-other-plugin'] }, null, 2));
1084
- const { doctor } = require('../doctor');
1085
-
1086
- const result = await doctor(['--fix']);
1087
-
1088
- expect(result).toBe(0);
1089
- const tui = JSON.parse(fs.readFileSync(tuiJsonPath(), 'utf8'));
1090
- expect(tui.plugin).toContain('some-other-plugin');
1091
- expect(tui.plugin).toContain('@boyingliu01/opencode-plugin/tui');
1092
- });
1093
-
1094
- it('--fix: idempotent — does not duplicate entry when already registered', async () => {
1095
- setupLocalInstall();
1096
- seedVersionCache();
1097
- mockExecSuccess();
1098
- fs.mkdirSync(path.dirname(tuiJsonPath()), { recursive: true });
1099
- fs.writeFileSync(tuiJsonPath(), JSON.stringify({ plugin: ['@boyingliu01/opencode-plugin/tui'] }, null, 2));
1100
- const { doctor } = require('../doctor');
1101
-
1102
- const result = await doctor(['--fix']);
1103
-
1104
- expect(result).toBe(0);
1105
- const tui = JSON.parse(fs.readFileSync(tuiJsonPath(), 'utf8'));
1106
- // Should still have exactly one entry
1107
- expect(tui.plugin.filter(p => p === '@boyingliu01/opencode-plugin/tui').length).toBe(1);
1108
- });
1109
-
1110
- // === Issue #263 follow-up: Gate script detection ===
1111
-
1112
- function createGateScripts(dir) {
1113
- fs.mkdirSync(dir, { recursive: true });
1114
- const gateScripts = require('../deploy-manifest.js').GATE_FILES.filter(g => g !== 'gate-registry.sh');
1115
- for (const script of gateScripts) {
1116
- fs.writeFileSync(path.join(dir, script), `#!/bin/bash\n# ${script}\n`);
1117
- }
1118
- }
1119
-
1120
- it('gate scripts: PASS when all expected gate scripts exist', async () => {
1121
- setupLocalInstall();
1122
- ensureTuiRegistered();
1123
- seedVersionCache();
1124
- createGateScripts(projectAdaptersDir());
1125
- mockExecSuccess();
1126
- const { doctor } = require('../doctor');
1127
-
1128
- const result = await doctor([]);
1129
-
1130
- expect(result).toBe(0);
1131
- expect(logSpy).toHaveBeenCalledWith(
1132
- expect.stringContaining('Gate scripts')
1133
- );
1134
- expect(logSpy).toHaveBeenCalledWith(
1135
- expect.stringContaining('gate script(s) present')
1136
- );
1137
- });
1138
-
1139
- it('gate scripts: FAIL when gate scripts are missing', async () => {
1140
- setupLocalInstall();
1141
- seedVersionCache();
1142
- // Clear adapters dir and create with only language adapters, no gate scripts
1143
- fs.rmSync(projectAdaptersDir(), { recursive: true, force: true });
1144
- fs.mkdirSync(projectAdaptersDir(), { recursive: true });
1145
- fs.writeFileSync(path.join(projectAdaptersDir(), 'typescript.sh'), '#!/bin/bash\n');
1146
- mockExecSuccess();
1147
- const { doctor } = require('../doctor');
1148
-
1149
- const result = await doctor([]);
1150
-
1151
- expect(result).toBe(1);
1152
- expect(logSpy).toHaveBeenCalledWith(
1153
- expect.stringContaining('Gate scripts')
1154
- );
1155
- expect(logSpy).toHaveBeenCalledWith(
1156
- expect.stringContaining('Missing')
1157
- );
1158
- });
1159
-
1160
- it('--fix: restores missing gate scripts', async () => {
1161
- setupLocalInstall();
1162
- seedVersionCache();
1163
- // Clear adapters dir and create with only language adapters, no gate scripts
1164
- fs.rmSync(projectAdaptersDir(), { recursive: true, force: true });
1165
- fs.mkdirSync(projectAdaptersDir(), { recursive: true });
1166
- fs.writeFileSync(path.join(projectAdaptersDir(), 'typescript.sh'), '#!/bin/bash\n');
1167
- mockExecSuccess();
1168
- const { doctor } = require('../doctor');
1169
-
1170
- const result = await doctor(['--fix']);
1171
-
1172
- expect(result).toBe(0);
1173
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-3.sh'))).toBe(true);
1174
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-4.sh'))).toBe(true);
1175
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-7.sh'))).toBe(true);
1176
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-8.sh'))).toBe(true);
1177
- // gate-9.sh was deleted (#738/#717). It carried a "DEAD CODE — NOT
1178
- // EXECUTED" banner and no hook sourced it; the SAST gate is gate-10.sh.
1179
- // Restoring it would re-ship a script that cannot run into every consumer
1180
- // repo — which is how a C# SAST fix once landed in a file nothing executes.
1181
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-9.sh'))).toBe(false);
1182
- expect(fs.existsSync(path.join(projectAdaptersDir(), 'gate-10.sh'))).toBe(true);
1183
- expect(logSpy).toHaveBeenCalledWith(
1184
- expect.stringContaining('Restored')
1185
- );
1186
- });
1187
-
1188
- it('--fix: idempotent for gate scripts — does not overwrite existing', async () => {
1189
- setupLocalInstall();
1190
- seedVersionCache();
1191
- createGateScripts(projectAdaptersDir());
1192
- const originalContent = fs.readFileSync(path.join(projectAdaptersDir(), 'gate-3.sh'), 'utf8');
1193
- mockExecSuccess();
1194
- const { doctor } = require('../doctor');
1195
-
1196
- const result = await doctor(['--fix']);
1197
-
1198
- expect(result).toBe(0);
1199
- const currentContent = fs.readFileSync(path.join(projectAdaptersDir(), 'gate-3.sh'), 'utf8');
1200
- expect(currentContent).toBe(originalContent);
1201
- });
1202
-
1203
- it('--format json returns valid JSON with tools field', async () => {
1204
- setupLocalInstall();
1205
- seedVersionCache();
1206
- mockExecSuccess();
1207
- const { doctor } = require('../doctor');
1208
- const { formatDoctorJson } = require('../doctor');
1209
-
1210
- const checks = [
1211
- { name: 'CLI tool: jscpd (Gate 2)', status: 'PASS', detail: 'v0.3.5' },
1212
- { name: 'CLI tool: lizard (Gate 3)', status: 'WARN', detail: 'Not found' },
1213
- ];
1214
- const json = formatDoctorJson(checks, 1);
1215
- expect(json.ok).toBe(false);
1216
- expect(json.issues).toBe(1);
1217
- expect(json.checks).toHaveLength(2);
1218
- expect(json.missing_tools).toBeDefined();
1219
- });
1220
-
1221
- it('--format json returns ok:true when no issues', async () => {
1222
- const { formatDoctorJson } = require('../doctor');
1223
- const checks = [
1224
- { name: 'CLI tool: jscpd (Gate 2)', status: 'PASS', detail: 'v0.3.5' },
1225
- ];
1226
- const json = formatDoctorJson(checks, 0);
1227
- expect(json.ok).toBe(true);
1228
- expect(json.issues).toBe(0);
1229
- });
1230
-
1231
- // AC-488-08: the flag was advertised in the release notes since the version
1232
- // that added doctor, and rejected as an unknown flag until now. Asserting the
1233
- // FORMATTER alone would pass while `doctor --format json` still crashed, so
1234
- // this runs the command and inspects what a script would actually parse.
1235
- it('AC-488-08: doctor --format json emits one parseable document and nothing else', async () => {
1236
- setupLocalInstall();
1237
- seedVersionCache();
1238
- mockExecSuccess();
1239
- const { doctor } = require('../doctor');
1240
- const seen = [];
1241
- const logSpy = vi.spyOn(console, 'log').mockImplementation((msg) => { seen.push(String(msg)); });
1242
-
1243
- let code;
1244
- try {
1245
- code = await doctor(['--format', 'json']);
1246
- } finally {
1247
- logSpy.mockRestore();
1248
- }
1249
-
1250
- expect(seen, `expected exactly one JSON line, got:\n${seen.join('\n')}`).toHaveLength(1);
1251
- const doc = JSON.parse(seen[0]);
1252
- expect(doc.ok).toBe(code === 0);
1253
- expect(Array.isArray(doc.checks)).toBe(true);
1254
- expect(doc.checks.length).toBeGreaterThan(0);
1255
- expect(seen[0]).not.toMatch(/XP-Gate Doctor|Diagnosis Report/);
1256
- });
1257
-
1258
- it('AC-488-08: a machine-readable doctor run cannot also mutate the machine', async () => {
1259
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1260
- const { doctor } = require('../doctor');
1261
-
1262
- expect(await doctor(['--format', 'json', '--fix'])).toBe(1);
1263
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--fix'));
1264
- expect(await doctor(['--json', '--sync-hooks'])).toBe(1);
1265
- errorSpy.mockRestore();
1266
- });
1267
-
1268
- it('AC-488-08: an unknown --format value is rejected instead of silently ignored', async () => {
1269
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1270
- const { doctor } = require('../doctor');
1271
-
1272
- expect(await doctor(['--format', 'yaml'])).toBe(1);
1273
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--format'));
1274
- errorSpy.mockRestore();
1275
- });
1276
-
1277
- // AC-488-09 (#488 Round 4, feasibility): the same class as the original issue —
1278
- // a flag that is accepted and then does nothing. `--format` with no value, and
1279
- // `--force` with no mode that reads it, both looked like they ran.
1280
- it('AC-488-09: a value-less --format is rejected instead of silently dropping the flag', async () => {
1281
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1282
- const { doctor } = require('../doctor');
1283
-
1284
- expect(await doctor(['--format'])).toBe(1);
1285
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--format'));
1286
- errorSpy.mockRestore();
1287
- });
1288
-
1289
- it('AC-488-09: --force is refused when no mode consumes it', () => {
1290
- // Asserted through the pure contract rather than by running the command:
1291
- // the only mode that reads --force is the one that copies files over the
1292
- // installed hooks, so a run-based assertion would mutate this machine.
1293
- const { doctorFlagContract } = require('../doctor');
1294
-
1295
- const bare = doctorFlagContract(['--force']);
1296
- expect(bare.errors).toHaveLength(2);
1297
- expect(bare.errors[0]).toContain('--force');
1298
- expect(bare.errors[0]).toContain('--sync-hooks');
1299
- expect(doctorFlagContract(['--fix', '--force']).errors.length, '--fix does not read --force either').toBeGreaterThan(0);
1300
-
1301
- const synced = doctorFlagContract(['--sync-hooks', '--force']);
1302
- expect(synced.errors, synced.errors.join('\n')).toHaveLength(0);
1303
- expect(synced.force).toBe(true);
1304
- expect(synced.syncHooks).toBe(true);
1305
- });
1306
-
1307
- it('AC-488-09: --install-tools is refused unless --fix is the mode that reads it', () => {
1308
- const { doctorFlagContract } = require('../doctor');
1309
-
1310
- const bare = doctorFlagContract(['--install-tools']);
1311
- expect(bare.errors).toHaveLength(2);
1312
- expect(bare.errors[0]).toContain('--install-tools');
1313
- expect(bare.errors[0]).toContain('--fix');
1314
- expect(doctorFlagContract(['--sync-hooks', '--install-tools']).errors.length).toBeGreaterThan(0);
1315
-
1316
- const fixing = doctorFlagContract(['--fix', '--install-tools']);
1317
- expect(fixing.errors, fixing.errors.join('\n')).toHaveLength(0);
1318
- expect(fixing.installToolsFlag).toBe(true);
1319
- });
1320
- });