@boyingliu01/xp-gate 0.38.125 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (428) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +45 -1
  3. package/adapters/gate-7.sh +15 -6
  4. package/adapters/python.sh +36 -38
  5. package/bin/xp-gate.js +35 -0
  6. package/build-integrity/gate-10-lines.ts +98 -0
  7. package/build-integrity/gate-10.ts +131 -117
  8. package/build-integrity/quote-masker.ts +17 -3
  9. package/gate-3.sh +45 -1
  10. package/gate-registry.sh +3 -1
  11. package/gates/common-process.ts +116 -34
  12. package/gates/common.ts +51 -15
  13. package/gates/gate-3.ts +166 -61
  14. package/gates/gate-8.ts +76 -24
  15. package/gates/gate-9.ts +276 -82
  16. package/gates/pbt-detect.ts +70 -39
  17. package/gates/python-health.ts +236 -98
  18. package/gates/test-layers.ts +103 -30
  19. package/hooks/deploy-manifest.sh +1 -0
  20. package/hooks/gate-3.sh +45 -1
  21. package/hooks/gate-entries/gate-1-entry.sh +44 -24
  22. package/hooks/gate-entries/gate-5-entry.sh +60 -20
  23. package/hooks/gate-entries/gate-6-entry.sh +15 -6
  24. package/hooks/gate-registry.sh +3 -1
  25. package/hooks/lib/gate-status.sh +164 -0
  26. package/hooks/lib/jscpd-run.sh +9 -1
  27. package/hooks/lib/native-path.sh +54 -0
  28. package/hooks/lib/toolchain-path.sh +38 -0
  29. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  30. package/hooks/pre-commit +52 -0
  31. package/hooks/pre-push +67 -7
  32. package/lib/agent-runtime-journal.js +104 -37
  33. package/lib/arch.js +6 -0
  34. package/lib/baseline.js +329 -201
  35. package/lib/check.js +38 -2
  36. package/lib/deploy-manifest.js +1 -0
  37. package/lib/doctor-constants.js +43 -0
  38. package/lib/doctor-tool-checks.js +129 -0
  39. package/lib/doctor.js +2014 -1038
  40. package/lib/flaky.js +178 -79
  41. package/lib/gate-audit.ts +80 -0
  42. package/lib/gate-runner.js +115 -63
  43. package/lib/init.js +6 -0
  44. package/lib/language-capability-surfaces.js +75 -8
  45. package/lib/language-capability.js +3 -0
  46. package/lib/language-registry.js +608 -0
  47. package/lib/language-tools.js +679 -894
  48. package/lib/phase-transition.js +646 -446
  49. package/lib/prepush-evidence.js +174 -0
  50. package/lib/sprint-audit.js +52 -22
  51. package/lib/sprint-discovery.js +66 -35
  52. package/lib/sprint-format.js +114 -0
  53. package/lib/sprint-init.js +372 -118
  54. package/lib/sprint-status.js +134 -90
  55. package/lib/star-notice.js +346 -0
  56. package/lib/tool-audit.js +729 -0
  57. package/lib/tool-display.js +52 -0
  58. package/lib/tool-install.js +179 -0
  59. package/lib/uninstall.js +331 -188
  60. package/mock-policy/gate-m3.ts +74 -23
  61. package/mock-policy/mock-decision-engine.ts +21 -7
  62. package/mock-policy/scope-scanner.ts +128 -69
  63. package/mutation/detect-ai-test.ts +20 -12
  64. package/mutation/gate-m.ts +6 -2
  65. package/mutation/init-baseline.ts +49 -13
  66. package/mutation/runners/go-mutant-runner.ts +7 -49
  67. package/mutation/runners/gremlins-runner.ts +53 -18
  68. package/mutation/runners/mutmut-runner.ts +455 -163
  69. package/mutation/runners/pitest-runner.ts +85 -131
  70. package/mutation/runners/spawn-with-capture.ts +304 -0
  71. package/mutation/runners/stryker-runner.ts +14 -55
  72. package/mutation/update-baseline.ts +25 -18
  73. package/package.json +20 -8
  74. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  75. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  76. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/claude-code/skills/reinstall-xp-gate/.architecture-skip +8 -0
  79. package/plugins/claude-code/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  80. package/plugins/claude-code/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  81. package/plugins/claude-code/skills/reinstall-xp-gate/LICENSE +21 -0
  82. package/plugins/claude-code/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  83. package/plugins/claude-code/skills/reinstall-xp-gate/README.md +167 -0
  84. package/plugins/claude-code/skills/reinstall-xp-gate/SKILL.md +271 -0
  85. package/plugins/claude-code/skills/reinstall-xp-gate/TODO.md +253 -0
  86. package/plugins/claude-code/skills/reinstall-xp-gate/VERSION +1 -0
  87. package/plugins/claude-code/skills/reinstall-xp-gate/package.json +28 -0
  88. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  89. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  90. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  91. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  92. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  93. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  94. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  95. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  96. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  97. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  98. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  99. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  100. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  101. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  102. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  103. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  104. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  105. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  106. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  107. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  108. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  109. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  110. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  111. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  112. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  113. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  114. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  115. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  116. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  117. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  118. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  119. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  120. package/plugins/claude-code/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  121. package/plugins/claude-code/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  122. package/plugins/claude-code/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  123. package/plugins/claude-code/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  124. package/plugins/claude-code/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  125. package/plugins/claude-code/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  126. package/plugins/claude-code/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  127. package/plugins/claude-code/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  128. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  129. package/plugins/claude-code/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  130. package/plugins/claude-code/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  131. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  132. package/plugins/claude-code/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  133. package/plugins/claude-code/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  134. package/plugins/claude-code/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  135. package/plugins/claude-code/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  136. package/plugins/claude-code/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  137. package/plugins/claude-code/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  138. package/plugins/claude-code/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  139. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  140. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  141. package/plugins/claude-code/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  142. package/plugins/claude-code/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  143. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  144. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  145. package/plugins/dsh/package.json +1 -1
  146. package/plugins/dsh/scripts/prepack.cjs +43 -18
  147. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  148. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  149. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  150. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  151. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  152. package/plugins/dsh/src/skills.test.ts +9 -0
  153. package/plugins/opencode/index.ts +337 -123
  154. package/plugins/opencode/package.json +1 -1
  155. package/plugins/opencode/scripts/prepack.cjs +41 -16
  156. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  157. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  158. package/plugins/opencode/skills/reinstall-xp-gate/.architecture-skip +8 -0
  159. package/plugins/opencode/skills/reinstall-xp-gate/.github/workflows/test.yml +106 -0
  160. package/plugins/opencode/skills/reinstall-xp-gate/CHANGELOG.md +379 -0
  161. package/plugins/opencode/skills/reinstall-xp-gate/LICENSE +21 -0
  162. package/plugins/opencode/skills/reinstall-xp-gate/QUALITY-OVERVIEW.md +173 -0
  163. package/plugins/opencode/skills/reinstall-xp-gate/README.md +167 -0
  164. package/plugins/opencode/skills/reinstall-xp-gate/SKILL.md +271 -0
  165. package/plugins/opencode/skills/reinstall-xp-gate/TODO.md +253 -0
  166. package/plugins/opencode/skills/reinstall-xp-gate/VERSION +1 -0
  167. package/plugins/opencode/skills/reinstall-xp-gate/package.json +28 -0
  168. package/plugins/opencode/skills/reinstall-xp-gate/scripts/audit.mjs +193 -0
  169. package/plugins/opencode/skills/reinstall-xp-gate/scripts/coverage.mjs +140 -0
  170. package/plugins/opencode/skills/reinstall-xp-gate/scripts/hp-gate.mjs +175 -0
  171. package/plugins/opencode/skills/reinstall-xp-gate/scripts/install.mjs +64 -0
  172. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agent-paths.mjs +67 -0
  173. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/agents.mjs +247 -0
  174. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/backups.mjs +96 -0
  175. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/baseline.mjs +101 -0
  176. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/ccn.mjs +124 -0
  177. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/delphi.mjs +61 -0
  178. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/fs-tree.mjs +108 -0
  179. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/gatecheck.mjs +290 -0
  180. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/json-file.mjs +37 -0
  181. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/mutations.mjs +154 -0
  182. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/platform.mjs +92 -0
  183. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/probes.mjs +102 -0
  184. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/proc.mjs +33 -0
  185. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/report.mjs +29 -0
  186. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/residue.mjs +188 -0
  187. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/selfsync.mjs +75 -0
  188. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/skills.mjs +121 -0
  189. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/spawn.mjs +161 -0
  190. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/testreport.mjs +26 -0
  191. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/tools.mjs +238 -0
  192. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/util.mjs +33 -0
  193. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/verdict.mjs +45 -0
  194. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/version.mjs +29 -0
  195. package/plugins/opencode/skills/reinstall-xp-gate/scripts/lib/xp-cli.mjs +66 -0
  196. package/plugins/opencode/skills/reinstall-xp-gate/scripts/mutation.mjs +132 -0
  197. package/plugins/opencode/skills/reinstall-xp-gate/scripts/preflight.mjs +75 -0
  198. package/plugins/opencode/skills/reinstall-xp-gate/scripts/reinstall.mjs +297 -0
  199. package/plugins/opencode/skills/reinstall-xp-gate/scripts/setup-wsl.sh +633 -0
  200. package/plugins/opencode/skills/reinstall-xp-gate/scripts/verify.mjs +222 -0
  201. package/plugins/opencode/skills/reinstall-xp-gate/tests/agents.test.mjs +168 -0
  202. package/plugins/opencode/skills/reinstall-xp-gate/tests/baseline.test.mjs +104 -0
  203. package/plugins/opencode/skills/reinstall-xp-gate/tests/ccn.test.mjs +87 -0
  204. package/plugins/opencode/skills/reinstall-xp-gate/tests/cleanup.test.mjs +128 -0
  205. package/plugins/opencode/skills/reinstall-xp-gate/tests/coverage.test.mjs +69 -0
  206. package/plugins/opencode/skills/reinstall-xp-gate/tests/delphi.test.mjs +78 -0
  207. package/plugins/opencode/skills/reinstall-xp-gate/tests/fixtures.mjs +61 -0
  208. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck-audit.test.mjs +157 -0
  209. package/plugins/opencode/skills/reinstall-xp-gate/tests/gatecheck.test.mjs +57 -0
  210. package/plugins/opencode/skills/reinstall-xp-gate/tests/mutation-anchors.test.mjs +49 -0
  211. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc-contract.test.mjs +58 -0
  212. package/plugins/opencode/skills/reinstall-xp-gate/tests/proc.test.mjs +243 -0
  213. package/plugins/opencode/skills/reinstall-xp-gate/tests/report.test.mjs +66 -0
  214. package/plugins/opencode/skills/reinstall-xp-gate/tests/residue.test.mjs +278 -0
  215. package/plugins/opencode/skills/reinstall-xp-gate/tests/selfsync.test.mjs +70 -0
  216. package/plugins/opencode/skills/reinstall-xp-gate/tests/skills.test.mjs +171 -0
  217. package/plugins/opencode/skills/reinstall-xp-gate/tests/testreport.test.mjs +40 -0
  218. package/plugins/opencode/skills/reinstall-xp-gate/tests/timeout-budgets.test.mjs +38 -0
  219. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-leaf.test.mjs +323 -0
  220. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools-probe.test.mjs +350 -0
  221. package/plugins/opencode/skills/reinstall-xp-gate/tests/tools.test.mjs +131 -0
  222. package/plugins/opencode/skills/reinstall-xp-gate/tests/util.test.mjs +154 -0
  223. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  224. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  225. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  226. package/plugins/qoder/plugin.json +1 -1
  227. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  228. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  229. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  230. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  231. package/plugins/shared/README.md +3 -0
  232. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  233. package/principles/adapters/control-nesting.ts +481 -168
  234. package/principles/adapters/cpp.ts +61 -22
  235. package/principles/adapters/csharp.ts +183 -66
  236. package/principles/adapters/dart.ts +11 -1
  237. package/principles/adapters/duplication.ts +49 -16
  238. package/principles/adapters/import-clause.ts +62 -15
  239. package/principles/adapters/java.ts +199 -70
  240. package/principles/adapters/line-comment.ts +18 -0
  241. package/principles/adapters/member-scan.ts +50 -8
  242. package/principles/adapters/php.ts +232 -103
  243. package/principles/adapters/python.ts +25 -18
  244. package/principles/adapters/quote-state.ts +21 -8
  245. package/principles/adapters/typescript-mask.ts +276 -0
  246. package/principles/adapters/typescript.ts +206 -200
  247. package/principles/analyzer.ts +16 -6
  248. package/principles/baseline-prune.ts +18 -8
  249. package/principles/baseline.ts +28 -11
  250. package/principles/boy-scout-usage.ts +26 -0
  251. package/principles/boy-scout.ts +261 -180
  252. package/principles/config.ts +183 -57
  253. package/principles/direct-execution.ts +24 -12
  254. package/principles/lint-baseline.ts +235 -122
  255. package/principles/rules/arch/dependency.ts +34 -25
  256. package/principles/rules/arch/shared.ts +24 -20
  257. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  258. package/principles/rules/clean-code/god-class.ts +67 -41
  259. package/principles/rules/clean-code/large-file.ts +30 -23
  260. package/principles/rules/clean-code/long-function.ts +51 -37
  261. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  262. package/principles/rules/clean-code/many-exports.ts +46 -29
  263. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  264. package/principles/rules/clean-code/too-many-params.ts +41 -22
  265. package/principles/rules/function-source.ts +62 -0
  266. package/principles/rules/solid/dip.ts +10 -6
  267. package/principles/rules/solid/isp.ts +64 -24
  268. package/principles/rules/solid/lsp.ts +66 -18
  269. package/principles/rules/solid/ocp.ts +29 -13
  270. package/principles/rules/solid/srp.ts +34 -18
  271. package/principles/warnings-count.ts +43 -0
  272. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  273. package/scripts/delphi-config-read.cjs +245 -0
  274. package/scripts/delphi-external-review.cjs +410 -585
  275. package/scripts/delphi-json-extract.cjs +108 -0
  276. package/scripts/delphi-model-validation.cjs +297 -0
  277. package/scripts/delphi-prompts.cjs +55 -0
  278. package/scripts/delphi-repo-tools.cjs +273 -0
  279. package/scripts/delphi-seat-calibration.cjs +204 -0
  280. package/scripts/run-bats-ci.cjs +240 -97
  281. package/scripts/sync-package-content.js +18 -2
  282. package/skills/delphi-review/.delphi-config.json.example +6 -11
  283. package/skills/delphi-review/AGENTS.md +1 -1
  284. package/skills/sprint-flow/AGENTS.md +1 -1
  285. package/skills/test-specification-alignment/AGENTS.md +1 -1
  286. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  287. package/lib/__tests__/arch-config-template.test.js +0 -190
  288. package/lib/__tests__/arch.test.js +0 -424
  289. package/lib/__tests__/assertion-debt.test.js +0 -99
  290. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  291. package/lib/__tests__/audit-log.test.ts +0 -107
  292. package/lib/__tests__/baseline-completeness.test.js +0 -264
  293. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  294. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  295. package/lib/__tests__/baseline.test.js +0 -212
  296. package/lib/__tests__/bootstrap.test.js +0 -60
  297. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  298. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  299. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  300. package/lib/__tests__/check-changed-brief.test.js +0 -63
  301. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  302. package/lib/__tests__/check-single-file.test.js +0 -114
  303. package/lib/__tests__/check-version.test.js +0 -463
  304. package/lib/__tests__/coverage-scope.test.js +0 -140
  305. package/lib/__tests__/coverage-threshold.test.js +0 -80
  306. package/lib/__tests__/crap-cli.test.js +0 -87
  307. package/lib/__tests__/crap.test.js +0 -494
  308. package/lib/__tests__/debt-classify.test.js +0 -78
  309. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  310. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  311. package/lib/__tests__/delphi-channel.test.js +0 -109
  312. package/lib/__tests__/delphi-setup.test.js +0 -203
  313. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  314. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  315. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  316. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  317. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  318. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  319. package/lib/__tests__/deploy-manifest.test.js +0 -97
  320. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  321. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  322. package/lib/__tests__/detect-deps.test.js +0 -655
  323. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  324. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  325. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  326. package/lib/__tests__/doctor-brief.test.js +0 -59
  327. package/lib/__tests__/doctor-delphi.test.js +0 -628
  328. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  329. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  330. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  331. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  332. package/lib/__tests__/doctor-helpers.test.js +0 -139
  333. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  334. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  335. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  336. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  337. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  338. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  339. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  340. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  341. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  342. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  343. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  344. package/lib/__tests__/doctor.test.js +0 -1320
  345. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  346. package/lib/__tests__/flaky.test.js +0 -128
  347. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  348. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  349. package/lib/__tests__/gate-audit.test.ts +0 -440
  350. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  351. package/lib/__tests__/gate-coverage.test.js +0 -204
  352. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  353. package/lib/__tests__/gate-numbering.test.js +0 -79
  354. package/lib/__tests__/gate-rules.test.js +0 -58
  355. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  356. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  357. package/lib/__tests__/gate-runner.test.js +0 -371
  358. package/lib/__tests__/gate2-verdict.test.js +0 -183
  359. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  360. package/lib/__tests__/hook-health-path.test.js +0 -109
  361. package/lib/__tests__/hook-health.test.js +0 -85
  362. package/lib/__tests__/init-gitignore.test.js +0 -204
  363. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  364. package/lib/__tests__/init.test.js +0 -530
  365. package/lib/__tests__/install-cmd.test.js +0 -6
  366. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  367. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  368. package/lib/__tests__/install-skill.test.js +0 -416
  369. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  370. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  371. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  372. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  373. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  374. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  375. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  376. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  377. package/lib/__tests__/language-capability.test.js +0 -291
  378. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  379. package/lib/__tests__/language-tools-detect.test.js +0 -301
  380. package/lib/__tests__/migrate.test.js +0 -232
  381. package/lib/__tests__/mirror-manifest.test.js +0 -64
  382. package/lib/__tests__/mirror-sync.test.js +0 -803
  383. package/lib/__tests__/next-sprint.test.js +0 -231
  384. package/lib/__tests__/npm-package.test.js +0 -140
  385. package/lib/__tests__/phase-transition.test.js +0 -1136
  386. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  387. package/lib/__tests__/principles-directory.test.js +0 -87
  388. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  389. package/lib/__tests__/retro-gate-m.test.js +0 -144
  390. package/lib/__tests__/retro.test.js +0 -131
  391. package/lib/__tests__/rework.test.js +0 -127
  392. package/lib/__tests__/rollback.test.js +0 -183
  393. package/lib/__tests__/runtime-journal.test.js +0 -164
  394. package/lib/__tests__/sastd-client.test.js +0 -514
  395. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  396. package/lib/__tests__/shared-paths.test.js +0 -130
  397. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  398. package/lib/__tests__/shared-utils.test.js +0 -180
  399. package/lib/__tests__/skill-flags.test.js +0 -48
  400. package/lib/__tests__/slo.test.js +0 -89
  401. package/lib/__tests__/sprint-audit.test.js +0 -207
  402. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  403. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  404. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  405. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  406. package/lib/__tests__/sprint-status.test.js +0 -193
  407. package/lib/__tests__/sprint-status.test.ts +0 -213
  408. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  409. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  410. package/lib/__tests__/test-alignment.test.ts +0 -853
  411. package/lib/__tests__/tsconfig.json +0 -8
  412. package/lib/__tests__/tsx-resolution.test.js +0 -89
  413. package/lib/__tests__/ui-detector.test.ts +0 -459
  414. package/lib/__tests__/ui-review.test.ts +0 -132
  415. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  416. package/lib/__tests__/uninstall-skill.test.js +0 -189
  417. package/lib/__tests__/uninstall.test.js +0 -717
  418. package/lib/__tests__/update-hooks.test.js +0 -737
  419. package/lib/__tests__/update-skill-flags.test.js +0 -78
  420. package/lib/__tests__/update-skill.test.js +0 -644
  421. package/lib/__tests__/upgrade-exec.test.js +0 -273
  422. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  423. package/lib/__tests__/upgrade.test.js +0 -78
  424. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  425. package/lib/check-alignment-runner.cjs +0 -97
  426. package/lib/coverage-total.sh +0 -92
  427. package/lib/layer-baseline.cjs +0 -94
  428. package/lib/mattpocock-license-verdict.json +0 -7
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * xp-gate phase-transition — Programmatic sprint phase transition
3
3
  *
4
- * Resolves #338 (dashboard never auto-renders) and #146 (sprint-state enforcement).
4
+ * Resolves #338 (dashboar auto-renders) and #146 (sprint-state enforcement).
5
5
  *
6
6
  * This CLI command is the programmatic entry point for sprint phase transitions.
7
7
  * The sprint-flow SKILL.md MUST instruct the orchestrator to call this command
@@ -23,6 +23,18 @@
23
23
  'use strict';
24
24
 
25
25
  const path = require('path');
26
+ const { statusIcon, formatDuration: formatDurationShared } = require('./sprint-format.js');
27
+
28
+ /**
29
+ * The dashboard renders an unmeasured duration as `-` so the column keeps its width;
30
+ * a blank cell would make the table look ragged.
31
+ *
32
+ * @param {number|null|undefined} seconds
33
+ * @returns {string}
34
+ */
35
+ function formatDuration(seconds) {
36
+ return formatDurationShared(seconds, { empty: '-' });
37
+ }
26
38
  const fs = require('fs');
27
39
  const crypto = require('crypto');
28
40
  const { execFileSync, execSync } = require('child_process');
@@ -32,11 +44,48 @@ const { SprintStateManager } = require('./sprint-state-manager');
32
44
  * Shared phase name lookup — single source of truth.
33
45
  * Used by renderDashboard, sprint-audit, and Layer 1 gate check.
34
46
  */
47
+ const PHASE_PREP = 1;
48
+ const PHASE_DESIGN = 2;
49
+ const PHASE_BUILD = 3;
50
+ const PHASE_VERIFY = 4;
51
+ const PHASE_SHIP = 5;
52
+ const PHASE_CLOSE = 6;
53
+ /** How many phases the pipeline has -- the denominator of the progress bar. */
54
+ const PHASE_COUNT = PHASE_CLOSE - PHASE_PREP + 1;
55
+ /** `YYYY-MM-DDTHH:MM` is 16 characters; the seconds are display noise. */
56
+ const DURATION_COLUMN_WIDTH = 8;
57
+ /**
58
+ * Inner width of the dashboard's ASCII frame.
59
+ *
60
+ * Every `+===+` line is 60 characters wide, so the content area is 58 and a row
61
+ * that starts after `| ` gets 59. These are one design, not three numbers, and
62
+ * naming them is what keeps the frame from going ragged.
63
+ */
64
+ const FRAME_INNER_WIDTH = 58;
65
+ const FRAME_ROW_WIDTH = FRAME_INNER_WIDTH + 1;
66
+ /** `| ` plus one more space before a wrapped field's text. */
67
+ const OUTPUT_ROW_INDENT = 3;
68
+ const TIMESTAMP_MINUTE_LENGTH = 16;
69
+
35
70
  const PHASE_NAMES = {
36
- 1: 'PREP', 2: 'DESIGN', 3: 'BUILD',
37
- 4: 'VERIFY', 5: 'SHIP', 6: 'CLOSE',
71
+ [PHASE_PREP]: 'PREP',
72
+ [PHASE_DESIGN]: 'DESIGN',
73
+ [PHASE_BUILD]: 'BUILD',
74
+ [PHASE_VERIFY]: 'VERIFY',
75
+ [PHASE_SHIP]: 'SHIP',
76
+ [PHASE_CLOSE]: 'CLOSE',
38
77
  };
39
78
 
79
+ /**
80
+ * The review is exactly three experts, and consensus is 90% or better.
81
+ *
82
+ * Both numbers appear in several places and both are policy, not arithmetic: a
83
+ * two-expert "Delphi review" is a different process, and a lower threshold makes
84
+ * the verdict mean something else. Naming them lets the rule be read.
85
+ */
86
+ const DELPHI_EXPERT_COUNT = 3;
87
+ const DELPHI_CONSENSUS_THRESHOLD = 0.9;
88
+
40
89
  /**
41
90
  * Phase-specific evidence file requirements.
42
91
  * Each entry defines the evidence file path, required fields, and a blocking check.
@@ -52,7 +101,7 @@ const EVIDENCE_FILES = {
52
101
  blockingCheck: (data) => data.verdict === 'APPROVED',
53
102
  blockingMessage: 'Requirements review verdict is not APPROVED',
54
103
  },
55
- 4: {
104
+ [PHASE_VERIFY]: {
56
105
  path: '.sprint-state/phase-outputs/test-alignment-report.json',
57
106
  requiredFields: ['alignment_status', 'head_commit', 'spec_hash'],
58
107
  blockingCheck: (data) => data.alignment_status === 'PASS',
@@ -60,21 +109,6 @@ const EVIDENCE_FILES = {
60
109
  },
61
110
  };
62
111
 
63
- const GIT_REPOSITORY_ENV_VARS = [
64
- 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS',
65
- 'GIT_CONFIG_COUNT', 'GIT_OBJECT_DIRECTORY', 'GIT_DIR', 'GIT_WORK_TREE',
66
- 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_INDEX_FILE',
67
- 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_PREFIX',
68
- 'GIT_SHALLOW_FILE', 'GIT_COMMON_DIR',
69
- ];
70
-
71
- function createRepositoryGitEnv() {
72
- const env = { ...process.env };
73
- for (const name of GIT_REPOSITORY_ENV_VARS) {
74
- delete env[name];
75
- }
76
- return env;
77
- }
78
112
 
79
113
  /**
80
114
  * Get current HEAD commit hash from a project directory.
@@ -97,7 +131,7 @@ function getCurrentHeadCommit(projectDir) {
97
131
 
98
132
  function validateRequirementsExpertEvidence(data) {
99
133
  const validationErrors = [];
100
- if (!Array.isArray(data.expert_verdicts) || data.expert_verdicts.length !== 3) {
134
+ if (!Array.isArray(data.expert_verdicts) || data.expert_verdicts.length !== DELPHI_EXPERT_COUNT) {
101
135
  validationErrors.push('expert_verdicts must contain exactly 3 expert results');
102
136
  return validationErrors;
103
137
  }
@@ -129,7 +163,8 @@ function validateRequirementsExpertEvidence(data) {
129
163
  validationErrors.push('requested_model values must be distinct after trimming');
130
164
  }
131
165
 
132
- if (!Number.isFinite(data.consensus_ratio) || data.consensus_ratio < 0.9 || data.consensus_ratio > 1) {
166
+ if (!Number.isFinite(data.consensus_ratio)
167
+ || data.consensus_ratio < DELPHI_CONSENSUS_THRESHOLD || data.consensus_ratio > 1) {
133
168
  validationErrors.push('consensus_ratio must be a finite number from 0.90 through 1');
134
169
  }
135
170
  return validationErrors;
@@ -140,8 +175,24 @@ function validateRequirementsExpertEvidence(data) {
140
175
  * @param {string} filePath
141
176
  * @returns {string} hex digest
142
177
  */
178
+ /**
179
+ * SHA-256 of a file's contents.
180
+ *
181
+ * A read failure must not look like a hash mismatch: "the spec changed" and "I
182
+ * could not read the spec" send the operator to different places. Callers compare
183
+ * this against a recorded hash, so an exception here surfaces as a crash rather
184
+ * than as a silent "changed" verdict -- which is the right direction.
185
+ *
186
+ * @param {string} filePath
187
+ * @returns {string}
188
+ */
143
189
  function computeFileHash(filePath) {
144
- const content = fs.readFileSync(filePath, 'utf8');
190
+ let content;
191
+ try {
192
+ content = fs.readFileSync(filePath, 'utf8');
193
+ } catch (err) {
194
+ throw new Error(`cannot hash ${filePath}: ${err.message}`);
195
+ }
145
196
  return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
146
197
  }
147
198
 
@@ -156,28 +207,38 @@ function parseEvidenceDate(timestamp) {
156
207
  return timestamp.slice(0, 10);
157
208
  }
158
209
 
210
+ /** One message for every way a `context_file_used` path can be unusable. */
211
+ const UNSAFE_CONTEXT_PATH = 'context_file_used must be a safe project-relative regular file path';
212
+
159
213
  function readRequirementsContext(data, projectDir) {
160
214
  const contextFile = data.context_file_used;
161
215
  if (contextFile === null || contextFile === undefined || contextFile === '') {
162
216
  return { content: '' };
163
217
  }
164
218
  if (typeof contextFile !== 'string' || path.isAbsolute(contextFile)) {
165
- return { error: 'context_file_used must be a safe project-relative regular file path' };
219
+ return { error: UNSAFE_CONTEXT_PATH };
166
220
  }
167
221
 
168
- const projectRoot = fs.realpathSync(projectDir);
169
- const candidatePath = path.resolve(projectRoot, contextFile);
170
- const relativeCandidate = path.relative(projectRoot, candidatePath);
171
- if (relativeCandidate.startsWith('..') || path.isAbsolute(relativeCandidate) || !fs.existsSync(candidatePath)) {
172
- return { error: 'context_file_used must be a safe project-relative regular file path' };
173
- }
222
+ // Three stat/read calls can each fail, and every failure means the same thing:
223
+ // the path is not a usable project-relative file. Reporting them as one error
224
+ // keeps the traversal guard's verdict uniform rather than leaking a raw EACCES.
225
+ try {
226
+ const projectRoot = fs.realpathSync(projectDir);
227
+ const candidatePath = path.resolve(projectRoot, contextFile);
228
+ const relativeCandidate = path.relative(projectRoot, candidatePath);
229
+ if (relativeCandidate.startsWith('..') || path.isAbsolute(relativeCandidate) || !fs.existsSync(candidatePath)) {
230
+ return { error: UNSAFE_CONTEXT_PATH };
231
+ }
174
232
 
175
- const realContextPath = fs.realpathSync(candidatePath);
176
- const relativeRealPath = path.relative(projectRoot, realContextPath);
177
- if (relativeRealPath.startsWith('..') || path.isAbsolute(relativeRealPath) || !fs.statSync(realContextPath).isFile()) {
178
- return { error: 'context_file_used must be a safe project-relative regular file path' };
233
+ const realContextPath = fs.realpathSync(candidatePath);
234
+ const relativeRealPath = path.relative(projectRoot, realContextPath);
235
+ if (relativeRealPath.startsWith('..') || path.isAbsolute(relativeRealPath) || !fs.statSync(realContextPath).isFile()) {
236
+ return { error: UNSAFE_CONTEXT_PATH };
237
+ }
238
+ return { content: fs.readFileSync(realContextPath, 'utf8') };
239
+ } catch {
240
+ return { error: UNSAFE_CONTEXT_PATH };
179
241
  }
180
- return { content: fs.readFileSync(realContextPath, 'utf8') };
181
242
  }
182
243
 
183
244
  function computeRequirementsHash(data, projectDir) {
@@ -218,138 +279,179 @@ function computeRequirementsHash(data, projectDir) {
218
279
  * @param {string} projectDir - Project root directory
219
280
  * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
220
281
  */
221
- function validateEvidence(phase, projectDir) {
222
- const evidenceConfig = EVIDENCE_FILES[phase];
223
- if (!evidenceConfig) {
224
- return { ok: true, errors: [], warnings: [] };
282
+ /**
283
+ * Record a validation problem where its severity depends on the sprint's schema.
284
+ *
285
+ * This decision was written out a dozen times inside `validateEvidence`, each copy
286
+ * repeating the same full warning sentence. A sprint created before
287
+ * `evidence_schema_version` 2 gets a WARNING: enforcing a rule the sprint was
288
+ * never created under would block work that is not at fault.
289
+ *
290
+ * Mutates the arrays rather than returning new ones, because every call site
291
+ * keeps pushing into the same `errors`/`warnings` afterwards -- handing back
292
+ * copies silently dropped the later entries (measured: five tests failed).
293
+ *
294
+ * @param {string} msg
295
+ * @param {string[]} errors
296
+ * @param {string[]} warnings
297
+ * @param {boolean} isLegacySprint
298
+ * @returns {boolean} true when the problem was downgraded to a warning
299
+ */
300
+ function recordProblem(msg, errors, warnings, isLegacySprint) {
301
+ if (isLegacySprint) {
302
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
303
+ return true;
225
304
  }
305
+ errors.push(msg);
306
+ return false;
307
+ }
226
308
 
227
- // Read sprint state to determine evidence_schema_version
228
- let evidenceSchemaVersion = 0;
309
+ /**
310
+ * The evidence schema version this sprint was created under, or 0.
311
+ *
312
+ * A sprint predating `evidence_schema_version` is treated as legacy (0), and
313
+ * legacy sprints get WARNINGS where current ones get ERRORS. Unreadable state
314
+ * therefore degrades to "even more lenient", which is the safe direction: a
315
+ * corrupted state file must not start BLOCKING phase transitions that ran fine
316
+ * yesterday.
317
+ *
318
+ * @param {string} projectDir
319
+ * @returns {number}
320
+ */
321
+ function readEvidenceSchemaVersion(projectDir) {
229
322
  try {
230
323
  const manager = new SprintStateManager(projectDir);
231
324
  const state = manager.read();
232
325
  if (state && typeof state.evidence_schema_version === 'number') {
233
- evidenceSchemaVersion = state.evidence_schema_version;
326
+ return state.evidence_schema_version;
234
327
  }
235
328
  } catch {
236
- // If state can't be read, treat as legacy (version 0)
329
+ // Unreadable state is not a versioned sprint.
237
330
  }
331
+ return 0;
332
+ }
238
333
 
239
- const isLegacySprint = evidenceSchemaVersion < 2;
240
- const errors = [];
241
- const warnings = [];
242
-
243
- const evidenceFilePath = path.join(projectDir, evidenceConfig.path);
244
- const fileName = path.basename(evidenceConfig.path);
334
+ /**
335
+ * Read and parse the evidence file, or produce the verdict that ends validation.
336
+ *
337
+ * Three failures share one shape: record the problem, then either pass (legacy
338
+ * sprint, where the rule was not in force) or fail. They differ only in the
339
+ * message and in whether the failing messages list is replaced, which is why the
340
+ * third case reports `errors: [msg]` rather than the accumulated array.
341
+ *
342
+ * Returns `{ verdict }` when validation should stop, `{ data }` otherwise -- a
343
+ * single exit point per outcome, so the caller keeps one shape.
344
+ *
345
+ * @param {string} evidenceFilePath
346
+ * @param {string} configuredPath
347
+ * @param {string[]} errors
348
+ * @param {string[]} warnings
349
+ * @param {boolean} isLegacySprint
350
+ * @returns {{verdict?: object, data?: object}}
351
+ */
352
+ function loadEvidence(evidenceFilePath, configuredPath, errors, warnings, isLegacySprint) {
353
+ const fileName = path.basename(configuredPath);
245
354
 
246
- // Check file existence
247
355
  if (!fs.existsSync(evidenceFilePath)) {
248
- const msg = `Evidence file missing: ${evidenceConfig.path}`;
249
- if (isLegacySprint) {
250
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
251
- return { ok: true, errors: [], warnings };
356
+ const msg = `Evidence file missing: ${configuredPath}`;
357
+ if (recordProblem(msg, errors, warnings, isLegacySprint)) {
358
+ return { verdict: { ok: true, errors: [], warnings } };
252
359
  }
253
- errors.push(msg);
254
- return { ok: false, errors, warnings };
360
+ return { verdict: { ok: false, errors, warnings } };
255
361
  }
256
362
 
257
- // Parse JSON
258
363
  let data;
259
364
  try {
260
- const raw = fs.readFileSync(evidenceFilePath, 'utf8');
261
- data = JSON.parse(raw);
365
+ data = JSON.parse(fs.readFileSync(evidenceFilePath, 'utf8'));
262
366
  } catch {
263
367
  const msg = `${fileName} is malformed JSON`;
264
- if (isLegacySprint) {
265
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
266
- return { ok: true, errors: [], warnings };
368
+ if (recordProblem(msg, errors, warnings, isLegacySprint)) {
369
+ return { verdict: { ok: true, errors: [], warnings } };
267
370
  }
268
- errors.push(msg);
269
- return { ok: false, errors, warnings };
371
+ return { verdict: { ok: false, errors, warnings } };
270
372
  }
271
373
 
272
374
  if (data === null || typeof data !== 'object' || Array.isArray(data)) {
273
375
  const msg = `${fileName} must contain a JSON object`;
274
- if (isLegacySprint) {
275
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
276
- return { ok: true, errors: [], warnings };
376
+ if (recordProblem(msg, errors, warnings, isLegacySprint)) {
377
+ return { verdict: { ok: true, errors: [], warnings } };
277
378
  }
278
- return { ok: false, errors: [msg], warnings };
379
+ return { verdict: { ok: false, errors: [msg], warnings } };
279
380
  }
280
381
 
281
- // Check required fields
282
- for (const field of evidenceConfig.requiredFields) {
283
- if (!(field in data)) {
284
- const msg = `${fileName} is missing required field: ${field}`;
285
- if (isLegacySprint) {
286
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
287
- } else {
288
- errors.push(msg);
289
- }
290
- }
291
- }
292
-
293
- // If any required fields missing for new sprint, block early
294
- if (errors.length > 0) {
295
- return { ok: false, errors, warnings };
296
- }
382
+ return { data };
383
+ }
297
384
 
298
- // Run blocking check
299
- if (!evidenceConfig.blockingCheck(data)) {
300
- const msg = `${fileName}: ${evidenceConfig.blockingMessage}`;
301
- if (isLegacySprint) {
302
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
303
- return { ok: true, errors: [], warnings };
304
- }
305
- errors.push(msg);
306
- return { ok: false, errors, warnings };
385
+ /**
386
+ * The evidence must describe the commit under review.
387
+ *
388
+ * Anti-staleness: a report generated before the last commit says nothing about
389
+ * the code as it now stands. `currentHead === null` is reported separately -- "I
390
+ * could not determine HEAD" and "HEAD moved" need different fixes, and collapsing
391
+ * them would tell an operator to regenerate a report when the repository itself is
392
+ * the problem.
393
+ *
394
+ * @param {string} fileName
395
+ * @param {object} data
396
+ * @param {string} projectDir
397
+ * @param {string[]} errors
398
+ * @param {string[]} warnings
399
+ * @param {boolean} isLegacySprint
400
+ */
401
+ function checkHeadCommit(fileName, data, projectDir, errors, warnings, isLegacySprint) {
402
+ const currentHead = getCurrentHeadCommit(projectDir);
403
+ if (currentHead === null) {
404
+ const msg = `${fileName}: unable to resolve current Git HEAD; evidence identity cannot be verified`;
405
+ recordProblem(msg, errors, warnings, isLegacySprint);
406
+ } else if (data.head_commit !== currentHead) {
407
+ const msg = `${fileName}: head_commit mismatch — report has "${data.head_commit}", current HEAD is "${currentHead}"`;
408
+ recordProblem(msg, errors, warnings, isLegacySprint);
307
409
  }
410
+ }
308
411
 
309
- // Phase-specific anti-staleness checks
310
- if (phase === 2 || phase === 4) {
311
- const currentHead = getCurrentHeadCommit(projectDir);
312
- if (currentHead === null) {
313
- const msg = `${fileName}: unable to resolve current Git HEAD; evidence identity cannot be verified`;
314
- if (isLegacySprint) {
315
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
316
- } else {
317
- errors.push(msg);
318
- }
319
- } else if (data.head_commit !== currentHead) {
320
- const msg = `${fileName}: head_commit mismatch — report has "${data.head_commit}", current HEAD is "${currentHead}"`;
321
- if (isLegacySprint) {
322
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
323
- } else {
324
- errors.push(msg);
325
- }
326
- }
412
+ /**
413
+ * Anti-staleness checks specific to phases 2 and 4.
414
+ *
415
+ * Both phases review artifacts that are expensive to regenerate and cheap to let
416
+ * rot: a spec hash, a requirements hash, the commit the review was written
417
+ * against. Each check records rather than returns, so a report with several
418
+ * staleness problems names all of them in one pass.
419
+ *
420
+ * Phase 2 does NOT re-check head_commit; the shared branch in the caller already
421
+ * does, and it used to be checked twice.
422
+ *
423
+ * @param {number} phase
424
+ * @param {string} fileName
425
+ * @param {object} data
426
+ * @param {string} projectDir
427
+ * @param {string[]} errors
428
+ * @param {string[]} warnings
429
+ * @param {boolean} isLegacySprint
430
+ */
431
+ function checkPhaseSpecificEvidence(phase, fileName, data, projectDir, errors, warnings, isLegacySprint) {
432
+ // Phase-specific anti-staleness checks. Phase 2's head_commit is checked here
433
+ // too, so the branch below must NOT check it again -- it used to, and a phase-2
434
+ // report with a stale HEAD produced TWO warnings for one problem.
435
+ if (phase === PHASE_DESIGN || phase === PHASE_VERIFY) {
436
+ checkHeadCommit(fileName, data, projectDir, errors, warnings, isLegacySprint);
327
437
  }
328
438
 
329
- if (phase === 4) {
439
+ if (phase === PHASE_VERIFY) {
330
440
  // spec_hash check (only if specification.yaml exists)
331
441
  const specPath = path.join(projectDir, 'specification.yaml');
332
442
  if (fs.existsSync(specPath)) {
333
443
  const expectedHash = computeFileHash(specPath);
334
444
  if (data.spec_hash !== expectedHash) {
335
445
  const msg = `${fileName}: spec_hash mismatch — specification.yaml has changed since report was generated`;
336
- if (isLegacySprint) {
337
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
338
- } else {
339
- errors.push(msg);
340
- }
446
+ recordProblem(msg, errors, warnings, isLegacySprint);
341
447
  }
342
448
  }
343
449
  }
344
450
 
345
- if (phase === 2) {
451
+ if (phase === PHASE_DESIGN) {
346
452
  if (typeof data.requirements_hash !== 'string' || !/^[a-fA-F0-9]{64}$/.test(data.requirements_hash)) {
347
453
  const msg = `${fileName}: requirements_hash must be a 64-character hexadecimal SHA-256 digest`;
348
- if (isLegacySprint) {
349
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
350
- } else {
351
- errors.push(msg);
352
- }
454
+ recordProblem(msg, errors, warnings, isLegacySprint);
353
455
  } else {
354
456
  const computedHash = computeRequirementsHash(data, projectDir);
355
457
  const hashError = computedHash.error || (
@@ -359,33 +461,58 @@ function validateEvidence(phase, projectDir) {
359
461
  );
360
462
  if (hashError) {
361
463
  const msg = `${fileName}: ${hashError}`;
362
- if (isLegacySprint) {
363
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
364
- } else {
365
- errors.push(msg);
366
- }
464
+ recordProblem(msg, errors, warnings, isLegacySprint);
367
465
  }
368
466
  }
369
467
  for (const validationError of validateRequirementsExpertEvidence(data)) {
370
468
  const msg = `${fileName}: ${validationError}`;
371
- if (isLegacySprint) {
372
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
373
- } else {
374
- errors.push(msg);
375
- }
469
+ recordProblem(msg, errors, warnings, isLegacySprint);
376
470
  }
377
471
 
378
- const currentHead = getCurrentHeadCommit(projectDir);
379
- if (data.head_commit !== currentHead) {
380
- const msg = `${fileName}: head_commit mismatch — review has "${data.head_commit}", current HEAD is "${currentHead}"; regenerate the requirements review for the current commit`;
381
- if (isLegacySprint) {
382
- warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
383
- } else {
384
- errors.push(msg);
385
- }
472
+ }
473
+ }
474
+
475
+ function validateEvidence(phase, projectDir) {
476
+ const evidenceConfig = EVIDENCE_FILES[phase];
477
+ if (!evidenceConfig) {
478
+ return { ok: true, errors: [], warnings: [] };
479
+ }
480
+
481
+ const isLegacySprint = readEvidenceSchemaVersion(projectDir) < 2;
482
+ const errors = [];
483
+ const warnings = [];
484
+
485
+ const evidenceFilePath = path.join(projectDir, evidenceConfig.path);
486
+ const fileName = path.basename(evidenceConfig.path);
487
+
488
+ const loaded = loadEvidence(evidenceFilePath, evidenceConfig.path, errors, warnings, isLegacySprint);
489
+ if (loaded.verdict) return loaded.verdict;
490
+ const data = loaded.data;
491
+
492
+ // Check required fields
493
+ for (const field of evidenceConfig.requiredFields) {
494
+ if (!(field in data)) {
495
+ const msg = `${fileName} is missing required field: ${field}`;
496
+ recordProblem(msg, errors, warnings, isLegacySprint);
497
+ }
498
+ }
499
+
500
+ // If any required fields missing for new sprint, block early
501
+ if (errors.length > 0) {
502
+ return { ok: false, errors, warnings };
503
+ }
504
+
505
+ // Run blocking check
506
+ if (!evidenceConfig.blockingCheck(data)) {
507
+ const msg = `${fileName}: ${evidenceConfig.blockingMessage}`;
508
+ if (recordProblem(msg, errors, warnings, isLegacySprint)) {
509
+ return { ok: true, errors: [], warnings };
386
510
  }
511
+ return { ok: false, errors, warnings };
387
512
  }
388
513
 
514
+ checkPhaseSpecificEvidence(phase, fileName, data, projectDir, errors, warnings, isLegacySprint);
515
+
389
516
  if (errors.length > 0) {
390
517
  return { ok: false, errors, warnings };
391
518
  }
@@ -399,11 +526,16 @@ function validateEvidence(phase, projectDir) {
399
526
  * @param {number} phase
400
527
  * @param {string} reason
401
528
  */
529
+ /**
530
+ * Record that evidence was skipped, and why.
531
+ *
532
+ * This is the audit trail `--skip-evidence` promises: a bypass that leaves no
533
+ * trace is not an audited bypass. A write failure is reported rather than
534
+ * swallowed -- silently losing the record would defeat the point of asking for a
535
+ * reason.
536
+ */
402
537
  function logEvidenceSkip(projectDir, phase, reason) {
403
538
  const auditDir = path.join(projectDir, '.xp-gate');
404
- if (!fs.existsSync(auditDir)) {
405
- fs.mkdirSync(auditDir, { recursive: true });
406
- }
407
539
  const entry = {
408
540
  timestamp: new Date().toISOString(),
409
541
  event: 'evidence_skipped',
@@ -411,7 +543,14 @@ function logEvidenceSkip(projectDir, phase, reason) {
411
543
  reason,
412
544
  commit_hash: getCurrentHeadCommit(projectDir) ?? 'unknown',
413
545
  };
414
- fs.appendFileSync(path.join(auditDir, 'audit.jsonl'), JSON.stringify(entry) + '\n', 'utf8');
546
+ try {
547
+ if (!fs.existsSync(auditDir)) {
548
+ fs.mkdirSync(auditDir, { recursive: true });
549
+ }
550
+ fs.appendFileSync(path.join(auditDir, 'audit.jsonl'), JSON.stringify(entry) + '\n', 'utf8');
551
+ } catch (err) {
552
+ console.warn(`⚠️ Could not record the evidence skip in .xp-gate/audit.jsonl: ${err.message}`);
553
+ }
415
554
  }
416
555
 
417
556
  /**
@@ -420,92 +559,138 @@ function logEvidenceSkip(projectDir, phase, reason) {
420
559
  * @param {object} state - Sprint state object
421
560
  * @returns {string} Rendered dashboard
422
561
  */
562
+ /**
563
+ * Append the "outputs" block to the dashboard frame.
564
+ *
565
+ * A long value is clipped to the frame's inner width rather than wrapping: the
566
+ * dashboard is scanned as a table, and a wrapped row breaks the columns for every
567
+ * line after it.
568
+ *
569
+ * @param {string[]} lines mutated in place
570
+ * @param {object|undefined} outputs
571
+ */
572
+ function appendOutputsSection(lines, outputs) {
573
+ if (!outputs || Object.keys(outputs).length === 0) return;
574
+ // Every row is `|` + FRAME_INNER_WIDTH + `|`. The content width therefore depends
575
+ // on that row's own lead-in, and computing both from `FRAME_INNER_WIDTH` is what
576
+ // keeps the frame square -- the previous version derived the heading from one
577
+ // subtraction and the rows from another, and produced three different widths.
578
+ const contentWidth = (leadIn) => FRAME_INNER_WIDTH - leadIn.length;
579
+ const heading = ' 输出物: ';
580
+ lines.push(`|${heading}${' '.repeat(contentWidth(heading))}|`);
581
+ for (const [key, val] of Object.entries(outputs)) {
582
+ const leadIn = ' ';
583
+ const body = `${key}: ${val}`.slice(0, contentWidth(leadIn)).padEnd(contentWidth(leadIn));
584
+ lines.push(`|${leadIn}${body}|`);
585
+ }
586
+ lines.push(`+${'='.repeat(FRAME_INNER_WIDTH)}+`);
587
+ }
588
+
589
+ /**
590
+ * Index phase history by phase number, as strings.
591
+ *
592
+ * The keys are strings because they round-trip through JSON; indexing with a
593
+ * number silently misses.
594
+ *
595
+ * @param {Array|undefined} phaseHistory
596
+ * @returns {Object<string, object>}
597
+ */
598
+ function buildHistoryLookup(phaseHistory) {
599
+ const lookup = {};
600
+ if (!Array.isArray(phaseHistory)) return lookup;
601
+ for (const entry of phaseHistory) {
602
+ lookup[String(entry.phase)] = entry;
603
+ }
604
+ return lookup;
605
+ }
606
+
607
+ /**
608
+ * `[███▓░░░] 42%` -- completed, current, and remaining.
609
+ *
610
+ * The current phase gets its own block so "in progress" is visible at a glance;
611
+ * a bar with only completed blocks cannot distinguish phase 3 running from phase
612
+ * 3 not started.
613
+ *
614
+ * @param {Object<string, object>} lookup
615
+ * @param {number} currentPhase
616
+ * @returns {string}
617
+ */
618
+ function buildProgressBar(lookup, currentPhase) {
619
+ const completed = Object.values(lookup).filter((h) => h.status === 'completed').length;
620
+ const pct = Math.round((completed / PHASE_COUNT) * 100);
621
+ const inProgress = currentPhase <= PHASE_CLOSE ? 1 : 0;
622
+ const remaining = Math.max(0, PHASE_COUNT - completed - inProgress);
623
+ return `[${'█'.repeat(completed)}${'▓'.repeat(inProgress)}${'░'.repeat(remaining)}] ${pct}%`;
624
+ }
625
+
626
+
627
+
628
+ /**
629
+ * The dashboard's title block: what this sprint is, and where it stands.
630
+ *
631
+ * Every field is clipped to its column so a long branch name cannot push the
632
+ * closing `|` off the right edge and turn the frame into ragged text.
633
+ *
634
+ * @param {string[]} lines mutated in place
635
+ * @param {{sprintId: string, taskDesc: string, branch: string, overallStatus: string, startedAt: string}} f
636
+ */
637
+ function appendFrameHeader(lines, f) {
638
+ // One width helper for every row. Each row hand-computing its own padding is how
639
+ // the frame went ragged: `rule`, `blank` and `field` each subtracted a different
640
+ // constant from FRAME_INNER_WIDTH and disagreed by several columns.
641
+ const row = (content) => `|${content.slice(0, FRAME_INNER_WIDTH).padEnd(FRAME_INNER_WIDTH)}|`;
642
+ const rule = `+${'='.repeat(FRAME_INNER_WIDTH)}+`;
643
+
644
+ lines.push(rule);
645
+ // The sprint id is right-aligned in the title row; dropping it made a dashboard
646
+ // of several sprints indistinguishable.
647
+ const title = ' SPRINT PROGRESS';
648
+ lines.push(row(title + f.sprintId.padStart(FRAME_INNER_WIDTH - title.length)));
649
+ lines.push(rule);
650
+ lines.push(row(` 需求: ${f.taskDesc}`));
651
+ lines.push(row(` 分支: ${f.branch}`));
652
+ lines.push(row(` 状态: ${f.overallStatus} 启动: ${f.startedAt}`));
653
+ lines.push(rule);
654
+ lines.push(row(''));
655
+ }
656
+
423
657
  function renderDashboard(state) {
424
658
  if (!state) return 'No sprint state found';
425
659
 
426
660
  const PHASE_NAMES_LOCAL = PHASE_NAMES;
427
661
 
428
- function statusIcon(status) {
429
- switch (status) {
430
- case 'completed': return '✅';
431
- case 'in_progress': return '🔄';
432
- case 'skipped': return '⏭️';
433
- case 'failed': return '❌';
434
- case 'paused': return '⏸️';
435
- default: return '⏳';
436
- }
437
- }
438
-
439
- function formatDuration(seconds) {
440
- if (seconds == null || seconds === 0) return '-';
441
- if (seconds < 60) return `${seconds}s`;
442
- const mins = Math.floor(seconds / 60);
443
- if (mins < 60) return `${mins}m`;
444
- const hrs = Math.floor(mins / 60);
445
- if (hrs < 24) return `${hrs}h ${mins % 60}m`;
446
- return `${Math.floor(hrs / 24)}d ${hrs % 24}h`;
447
- }
448
-
449
662
  const branch = state.isolation?.branch || 'unknown';
450
663
  const sprintId = state.id || 'unknown';
451
664
  const taskDesc = state.task_description || state.issue_title || '-';
452
665
  const overallStatus = state.status || 'running';
453
- const startedAt = state.started_at ? state.started_at.slice(0, 16).replace('T', ' ') : '-';
666
+ const startedAt = state.started_at ? state.started_at.slice(0, TIMESTAMP_MINUTE_LENGTH).replace('T', ' ') : '-';
454
667
 
455
- // Build phase history lookup
456
- const historyLookup = {};
457
- if (Array.isArray(state.phase_history)) {
458
- for (const ph of state.phase_history) {
459
- historyLookup[String(ph.phase)] = ph;
460
- }
461
- }
668
+ const historyLookup = buildHistoryLookup(state.phase_history);
462
669
 
463
- const currentPhase = state.phase || 1;
670
+ const currentPhase = state.phase || PHASE_PREP;
464
671
  const currentPhaseName = PHASE_NAMES_LOCAL[String(currentPhase)] || `Phase ${currentPhase}`;
465
-
466
- // Progress bar
467
- const completedCount = Object.values(historyLookup).filter(h => h.status === 'completed').length;
468
- const pct = Math.round((completedCount / 6) * 100);
469
- const filled = '█'.repeat(completedCount);
470
- const current = currentPhase <= 6 ? '▓' : '';
471
- const empty = '░'.repeat(Math.max(0, 6 - completedCount - (current ? 1 : 0)));
472
- const progressBar = `[${filled}${current}${empty}] ${pct}%`;
672
+ const progressBar = buildProgressBar(historyLookup, currentPhase);
473
673
 
474
674
  // Build lines
475
675
  const lines = [];
476
- lines.push('+============================================================+');
477
- lines.push(`| SPRINT PROGRESS ${sprintId.padEnd(20)}|`);
478
- lines.push('+============================================================+');
479
- lines.push(`| 需求: ${(taskDesc).slice(0, 54).padEnd(54)}|`);
480
- lines.push(`| 分支: ${(branch).slice(0, 54).padEnd(54)}|`);
481
- lines.push(`| 状态: ${(overallStatus).slice(0, 15).padEnd(15)} 启动: ${startedAt.slice(0, 19).padEnd(19)}|`);
482
- lines.push('+============================================================+');
483
- lines.push('| |');
676
+ appendFrameHeader(lines, { sprintId, taskDesc, branch, overallStatus, startedAt });
484
677
 
485
- for (let i = 1; i <= 6; i++) {
678
+ for (let i = PHASE_PREP; i <= PHASE_CLOSE; i++) {
486
679
  const entry = historyLookup[String(i)];
487
680
  const icon = statusIcon(entry?.status || (i < currentPhase ? 'completed' : i === currentPhase ? 'in_progress' : 'pending'));
488
681
  const name = (PHASE_NAMES_LOCAL[String(i)] || `Phase ${i}`).padEnd(10);
489
- const dur = formatDuration(entry?.duration_seconds).padEnd(8);
682
+ const dur = formatDuration(entry?.duration_seconds).padEnd(DURATION_COLUMN_WIDTH);
490
683
  lines.push(`| ${icon} Phase ${i}/6 ${name} ${dur} |`);
491
684
  }
492
685
 
493
686
  lines.push('| |');
494
- lines.push(`| ${progressBar.padEnd(58)}|`);
687
+ lines.push(`| ${progressBar.padEnd(FRAME_INNER_WIDTH)}|`);
495
688
  lines.push('+============================================================+');
496
- lines.push(`| > 当前: Phase ${currentPhase}/6 ${currentPhaseName}`.padEnd(59) + '|');
497
- lines.push(`| 状态: ${(entry_status(currentPhase, historyLookup)).padEnd(50)}|`);
689
+ lines.push(`| > 当前: Phase ${currentPhase}/${PHASE_CLOSE} ${currentPhaseName}`.padEnd(FRAME_ROW_WIDTH) + '|');
690
+ lines.push(`| 状态: ${(entry_status(currentPhase, historyLookup)).padEnd(FRAME_INNER_WIDTH - 8)}|`);
498
691
  lines.push('+============================================================+');
499
692
 
500
- // Outputs section
501
- if (state.outputs && Object.keys(state.outputs).length > 0) {
502
- lines.push('| 输出物: |');
503
- for (const [key, val] of Object.entries(state.outputs)) {
504
- lines.push(`| ${(`${key}: ${val}`).slice(0, 55).padEnd(55)}|`);
505
- }
506
- lines.push('+============================================================+');
507
- }
508
-
693
+ appendOutputsSection(lines, state.outputs);
509
694
  return lines.join('\n');
510
695
 
511
696
  function entry_status(phaseNum, lookup) {
@@ -515,12 +700,104 @@ function renderDashboard(state) {
515
700
  }
516
701
 
517
702
  /**
518
- * CLI entry point for phase-transition command.
519
- * @param {string[]} args - CLI arguments
520
- * @returns {Promise<number>} Exit code
703
+ * Parse phase-transition arguments.
704
+ *
705
+ * Extracted from `handlePhaseTransition` (CCN 51), whose first 40 lines were
706
+ * argv parsing before any domain logic ran. Returns `{ error }` instead of
707
+ * printing and returning a code, so the caller keeps one exit path.
708
+ *
709
+ * @param {string[]} args
710
+ * @returns {{phase?: number, status?: string, projectDir?: string, renderFlag?: boolean,
711
+ * outputs?: object, skipEvidence?: boolean, skipEvidenceReason?: string,
712
+ * forceTransition?: boolean, error?: string}}
521
713
  */
522
- async function handlePhaseTransition(args = []) {
523
- if (args.includes('--help')) {
714
+ function parseTransitionArgs(args) {
715
+ if (args.length < 2) {
716
+ return { error: 'Missing required arguments. Usage: xp-gate phase-transition <phase> <status>' };
717
+ }
718
+
719
+ const dirIdx = args.indexOf("--dir");
720
+ const outputsIdx = args.indexOf("--outputs");
721
+ let outputs = {};
722
+ if (outputsIdx >= 0 && args[outputsIdx + 1]) {
723
+ try {
724
+ outputs = JSON.parse(args[outputsIdx + 1]);
725
+ } catch (err) {
726
+ return { error: `Invalid JSON for --outputs: ${err.message}` };
727
+ }
728
+ }
729
+
730
+ const skipEvidenceIdx = args.indexOf("--skip-evidence");
731
+ let skipEvidence = false;
732
+ let skipEvidenceReason = "";
733
+ if (skipEvidenceIdx >= 0) {
734
+ skipEvidence = true;
735
+ const nextArg = args[skipEvidenceIdx + 1];
736
+ // The reason is the next arg when it exists and is not another flag.
737
+ if (nextArg && !nextArg.startsWith('--')) skipEvidenceReason = nextArg;
738
+ }
739
+
740
+ return {
741
+ phase: parseInt(args[0], 10),
742
+ status: args[1],
743
+ projectDir: dirIdx >= 0 ? args[dirIdx + 1] : process.cwd(),
744
+ renderFlag: args.includes("--render"),
745
+ outputs,
746
+ skipEvidence,
747
+ skipEvidenceReason,
748
+ forceTransition: args.includes("--force"),
749
+ };
750
+ }
751
+
752
+ /**
753
+ * Refuse to complete a phase whose predecessor was not completed or skipped.
754
+ *
755
+ * #519 Layer 0. `completed` on phase n requires phase n-1 to be finished first:
756
+ * #507 proved a missed transition is invisible in the state file (the pointer
757
+ * just looks "not yet advanced"), so out-of-order completion must be refused
758
+ * loudly rather than written silently. `--force` overrides for the rare
759
+ * legitimate case (retroactively recording a skipped phase).
760
+ *
761
+ * @param {object} manager SprintStateManager
762
+ * @param {number} phase
763
+ * @param {string} status
764
+ * @param {boolean} forceTransition
765
+ * @returns {boolean} true when the transition may proceed
766
+ */
767
+ function passesSequenceGuard(manager, phase, status, forceTransition) {
768
+ if (status !== 'completed' || phase < PHASE_DESIGN) return true;
769
+ const seqState = manager.read();
770
+ if (!seqState || !Array.isArray(seqState.phase_history)) return true;
771
+
772
+ const prevPhase = phase - 1;
773
+ const prevEntry = seqState.phase_history.find((e) => e.phase === prevPhase);
774
+ const prevOk = prevEntry && (prevEntry.status === 'completed' || prevEntry.status === 'skipped');
775
+ if (prevOk) return true;
776
+
777
+ if (forceTransition) {
778
+ console.warn(`⚠️ [sprint-audit] Sequence guard overridden (--force): phase ${prevPhase} is not completed/skipped.`);
779
+ return true;
780
+ }
781
+
782
+ const summary = seqState.phase_history
783
+ .map((e) => ` ${e.phase}:${e.phase_name || PHASE_NAMES[e.phase] || '?'} = ${e.status}`)
784
+ .join('\n');
785
+ console.error(`❌ [sprint-audit] Cannot complete phase ${phase} (${PHASE_NAMES[phase]}):`);
786
+ console.error(` phase ${prevPhase} (${PHASE_NAMES[prevPhase]}) is not completed/skipped.`);
787
+ console.error(' Current phase history:');
788
+ console.error(summary || ' (empty)');
789
+ console.error(` Advance it first: xp-gate phase-transition ${prevPhase} completed`);
790
+ console.error(' Or override explicitly: --force');
791
+ return false;
792
+ }
793
+
794
+ /**
795
+ * Print the phase-transition usage text.
796
+ *
797
+ * Separated so the command body reads as what it does. The text is the contract
798
+ * users copy from, so it lives in one place.
799
+ */
800
+ function printTransitionUsage() {
524
801
  console.log('Usage: xp-gate phase-transition <phase> <status> [options]');
525
802
  console.log('');
526
803
  console.log('Arguments:');
@@ -540,142 +817,121 @@ async function handlePhaseTransition(args = []) {
540
817
  console.log(' xp-gate phase-transition 2 in_progress --outputs \'{"spec":"path.yaml"}\'');
541
818
  console.log(' xp-gate phase-transition 4 completed --skip-evidence "Emergency hotfix"');
542
819
  console.log(' xp-gate phase-transition 3 completed --force # skip-order override');
543
- return 0;
544
- }
820
+ }
545
821
 
546
- if (args.length < 2) {
547
- console.error('Error: Missing required arguments. Usage: xp-gate phase-transition <phase> <status>');
548
- return 1;
822
+ /**
823
+ * Warn when the phase being entered had an unfinished predecessor.
824
+ *
825
+ * Layer 1 of the #519 guard. Unlike layer 0 it does NOT block: entering a phase
826
+ * whose predecessor was never marked complete is a warning, because the state
827
+ * file is a record of what someone reported, not a source of truth about what
828
+ * happened, and blocking on it would strand a sprint whose history was lost.
829
+ *
830
+ * Extracted so `handlePhaseTransition` loses both its deepest nesting and a
831
+ * dozen lines it does not need to read.
832
+ *
833
+ * @param {object} manager SprintStateManager
834
+ * @param {number} phase
835
+ * @param {string} status
836
+ */
837
+ function warnOnUnfinishedPredecessor(manager, phase, status) {
838
+ if (status !== 'in_progress' || phase < PHASE_DESIGN) return;
839
+
840
+ const preState = manager.read();
841
+ if (!preState || !Array.isArray(preState.phase_history)) return;
842
+
843
+ const prevPhase = phase - 1;
844
+ const prevEntry = preState.phase_history.find((e) => e.phase === prevPhase);
845
+ const prevName = PHASE_NAMES[prevPhase] || `Phase ${prevPhase}`;
846
+ // 'completed' and 'skipped' are both valid predecessor statuses.
847
+ if (!prevEntry || (prevEntry.status !== 'completed' && prevEntry.status !== 'skipped')) {
848
+ console.warn(`⚠️ [sprint-audit] Phase ${prevPhase} (${prevName}) not recorded as 'completed'`);
849
+ console.warn(` Previous phase may have been skipped. Run: xp-gate phase-transition ${prevPhase} completed`);
549
850
  }
851
+ }
550
852
 
551
- const phase = parseInt(args[0], 10);
552
- const status = args[1];
553
- const renderFlag = args.includes('--render');
554
- const dirIdx = args.indexOf('--dir');
555
- const projectDir = dirIdx >= 0 ? args[dirIdx + 1] : process.cwd();
853
+ /**
854
+ * Layer 2 of the #519 guard: completing a phase requires its evidence.
855
+ *
856
+ * `--skip-evidence` is an audited bypass, not a silent one: it demands a reason,
857
+ * records the skip, and warns that a third skip in one sprint raises an alert.
858
+ * The command cannot tell whether a skip was justified, so it makes the skip
859
+ * visible to the retro instead.
860
+ *
861
+ * @param {number} phase
862
+ * @param {string} projectDir
863
+ * @param {string} status
864
+ * @param {boolean} skipEvidence
865
+ * @param {string} skipEvidenceReason
866
+ * @returns {boolean} true when the transition may proceed
867
+ */
868
+ function checkEvidenceGate(phase, projectDir, status, skipEvidence, skipEvidenceReason) {
869
+ if (status !== 'completed' || !EVIDENCE_FILES[phase]) return true;
556
870
 
557
- const outputsIdx = args.indexOf('--outputs');
558
- let outputs = {};
559
- if (outputsIdx >= 0 && args[outputsIdx + 1]) {
560
- try {
561
- outputs = JSON.parse(args[outputsIdx + 1]);
562
- } catch (err) {
563
- console.error(`Error: Invalid JSON for --outputs: ${err.message}`);
564
- return 1;
871
+ if (skipEvidence) {
872
+ if (!skipEvidenceReason) {
873
+ console.error('Error: --skip-evidence requires --reason "<text>" to be provided');
874
+ return false;
565
875
  }
876
+ logEvidenceSkip(projectDir, phase, skipEvidenceReason);
877
+ console.warn('⚠️ Evidence skipped. This will appear in retro reports. Single-sprint limit: >2 skips per sprint will trigger an alert.');
878
+ return true;
566
879
  }
567
880
 
568
- // Parse --skip-evidence flag
569
- const skipEvidenceIdx = args.indexOf('--skip-evidence');
570
- let skipEvidence = false;
571
- let skipEvidenceReason = '';
572
- if (skipEvidenceIdx >= 0) {
573
- skipEvidence = true;
574
- const nextArg = args[skipEvidenceIdx + 1];
575
- // Reason is the next arg if it exists and doesn't start with '--'
576
- if (nextArg && !nextArg.startsWith('--')) {
577
- skipEvidenceReason = nextArg;
578
- }
881
+ const evidence = validateEvidence(phase, projectDir);
882
+ for (const w of evidence.warnings) {
883
+ console.warn(`⚠️ [sprint-audit] ${w}`);
579
884
  }
885
+ if (evidence.ok) return true;
580
886
 
581
- // #519: explicit override for the sequence guard below.
582
- const forceTransition = args.includes('--force');
887
+ for (const e of evidence.errors) {
888
+ console.error(`❌ [sprint-audit] ${e}`);
889
+ }
890
+ console.error(` Phase ${phase} (${PHASE_NAMES[phase]}) cannot transition to 'completed' without valid evidence.`);
891
+ console.error(' Use --skip-evidence "<reason>" to bypass (audited).');
892
+ return false;
893
+ }
583
894
 
584
- // Validate inputs
585
- if (phase < 1 || phase > 6) {
895
+ /** The statuses a phase transition may name. */
896
+ const VALID_TRANSITION_STATUSES = ['in_progress', 'completed', 'skipped', 'failed', 'paused'];
897
+
898
+ /**
899
+ * Reject a phase number or status that cannot apply, naming what IS valid.
900
+ *
901
+ * Pure check-and-report. `parseInt('abc')` is NaN, and NaN fails every comparison
902
+ * silently, so the guard is what keeps a typo from reaching the state file.
903
+ *
904
+ * @param {number} phase
905
+ * @param {string} status
906
+ * @returns {boolean}
907
+ */
908
+ function validateTransitionInput(phase, status) {
909
+ if (!Number.isInteger(phase) || phase < PHASE_PREP || phase > PHASE_CLOSE) {
586
910
  console.error(`Error: Phase must be 1-6, got ${phase}`);
587
- return 1;
911
+ return false;
588
912
  }
589
-
590
- const validStatuses = ['in_progress', 'completed', 'skipped', 'failed', 'paused'];
591
- if (!validStatuses.includes(status)) {
592
- console.error(`Error: Status must be one of: ${validStatuses.join(', ')}`);
593
- return 1;
913
+ if (!VALID_TRANSITION_STATUSES.includes(status)) {
914
+ console.error(`Error: Status must be one of: ${VALID_TRANSITION_STATUSES.join(', ')}`);
915
+ return false;
594
916
  }
917
+ return true;
918
+ }
595
919
 
596
- // Execute transition
597
- try {
598
- const manager = new SprintStateManager(projectDir);
599
-
600
- // ── #519 Layer 0: Sequence guard ──
601
- // `completed` on phase n requires phase n-1 to be completed/skipped first.
602
- // #507 proved that a missed transition is invisible in the state file (the
603
- // pointer just looks "not yet advanced"), so out-of-order completion —
604
- // skipping a phase, or completing from a stale pointer — must be refused
605
- // loudly rather than written silently. `--force` overrides for the rare
606
- // legitimate case (e.g. retroactively recording a skipped phase).
607
- if (status === 'completed' && phase >= 2) {
608
- const seqState = manager.read();
609
- if (seqState && Array.isArray(seqState.phase_history)) {
610
- const prevPhase = phase - 1;
611
- const prevEntry = seqState.phase_history.find(e => e.phase === prevPhase);
612
- const prevOk = prevEntry && (prevEntry.status === 'completed' || prevEntry.status === 'skipped');
613
- if (!prevOk && !forceTransition) {
614
- const summary = seqState.phase_history
615
- .map(e => ` ${e.phase}:${e.phase_name || PHASE_NAMES[e.phase] || '?'} = ${e.status}`)
616
- .join('\n');
617
- console.error(`❌ [sprint-audit] Cannot complete phase ${phase} (${PHASE_NAMES[phase]}):`);
618
- console.error(` phase ${prevPhase} (${PHASE_NAMES[prevPhase]}) is not completed/skipped.`);
619
- console.error(' Current phase history:');
620
- console.error(summary || ' (empty)');
621
- console.error(` Advance it first: xp-gate phase-transition ${prevPhase} completed`);
622
- console.error(' Or override explicitly: --force');
623
- return 1;
624
- }
625
- if (!prevOk && forceTransition) {
626
- console.warn(`⚠️ [sprint-audit] Sequence guard overridden (--force): phase ${prevPhase} is not completed/skipped.`);
627
- }
628
- }
629
- }
630
-
631
- // ── Layer 1: Pre-transition gate check ──
632
- // Check BEFORE transitionPhase() to validate previous phase completion.
633
- // Runs when status === 'in_progress' and phase >= 2.
634
- // No side effects — only outputs WARNING, does not modify state.
635
- if (status === 'in_progress' && phase >= 2) {
636
- const preState = manager.read();
637
- if (preState && Array.isArray(preState.phase_history)) {
638
- const prevPhase = phase - 1;
639
- const prevEntry = preState.phase_history.find(e => e.phase === prevPhase);
640
- const prevName = PHASE_NAMES[prevPhase] || `Phase ${prevPhase}`;
641
- // 'completed' and 'skipped' are both valid predecessor statuses
642
- if (!prevEntry || (prevEntry.status !== 'completed' && prevEntry.status !== 'skipped')) {
643
- console.warn(
644
- `⚠️ [sprint-audit] Phase ${prevPhase} (${prevName}) not recorded as 'completed'`
645
- );
646
- console.warn(
647
- ` Previous phase may have been skipped. Run: xp-gate phase-transition ${prevPhase} completed`
648
- );
649
- }
650
- }
651
- // If no sprint-state.json exists yet, skip check (no previous phase to validate)
652
- }
653
-
654
- // ── Layer 2: Evidence validation (blocks on status === 'completed') ──
655
- if (status === 'completed' && EVIDENCE_FILES[phase]) {
656
- if (skipEvidence) {
657
- if (!skipEvidenceReason) {
658
- console.error('Error: --skip-evidence requires --reason "<text>" to be provided');
659
- return 1;
660
- }
661
- logEvidenceSkip(projectDir, phase, skipEvidenceReason);
662
- console.warn('⚠️ Evidence skipped. This will appear in retro reports. Single-sprint limit: >2 skips per sprint will trigger an alert.');
663
- } else {
664
- const evidence = validateEvidence(phase, projectDir);
665
- for (const w of evidence.warnings) {
666
- console.warn(`⚠️ [sprint-audit] ${w}`);
667
- }
668
- if (!evidence.ok) {
669
- for (const e of evidence.errors) {
670
- console.error(`❌ [sprint-audit] ${e}`);
671
- }
672
- console.error(` Phase ${phase} (${PHASE_NAMES[phase]}) cannot transition to 'completed' without valid evidence.`);
673
- console.error(` Use --skip-evidence "<reason>" to bypass (audited).`);
674
- return 1;
675
- }
676
- }
677
- }
678
-
920
+ /**
921
+ * Apply the transition and echo what changed.
922
+ *
923
+ * The #507 failure mode was "the command either never ran or ran without effect"
924
+ * -- both look identical in a terminal that only prints a success line. Printing
925
+ * the observed state on both sides is what makes the two distinguishable in the
926
+ * output itself, without needing to open the state file.
927
+ *
928
+ * @param {object} manager SprintStateManager
929
+ * @param {number} phase
930
+ * @param {string} status
931
+ * @param {object} outputs
932
+ * @returns {object} the new state
933
+ */
934
+ function applyTransition(manager, phase, status, outputs) {
679
935
  // Capture the before-image for the echo below (#519). Read once here so a
680
936
  // concurrent writer cannot make before/after disagree about their baseline.
681
937
  const beforeSnapshot = (() => {
@@ -704,142 +960,86 @@ async function handlePhaseTransition(args = []) {
704
960
  const newEntryStatus = afterEntry ? afterEntry.status : '(none)';
705
961
  console.log(`✅ Phase ${phase} transitioned to '${status}'`);
706
962
  console.log(` before→after phase/status: ${oldTop} → ${newTop} | phase ${phase} entry: ${oldEntry} → ${newEntryStatus}`);
707
-
708
- // ── Layer 1.5: Auto-trigger Layer 2 reminder on Phase 6 completed ──
709
- if (phase === 6 && status === 'completed') {
710
- console.log('');
711
- console.log('📋 [sprint-audit] Sprint complete — run final coverage audit:');
712
- console.log(' npx xp-gate sprint-audit');
713
- }
714
-
715
- // Auto-render dashboard if --render flag is set
716
- if (renderFlag) {
717
- console.log('');
718
- const dashboard = renderDashboard(newState);
719
- console.log(dashboard);
720
- }
721
-
722
- return 0;
723
- } catch (err) {
724
- console.error(`Error: Phase transition failed: ${err.message}`);
725
- return 1;
726
- }
727
963
  }
728
964
 
729
965
  /**
730
- * Read-only evidence check for a given phase. Validates evidence without modifying sprint state.
731
- * D3 (Unify Evidence Validation): replaces sprint-gate.sh inline JSON parsing.
966
+ * What to print after a successful transition: the closing reminder and the
967
+ * optional dashboard.
732
968
  *
733
- * @param {number} phase - Phase number (1-6)
734
- * @param {string} projectDir - Project root directory
735
- * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
736
- */
737
- function checkEvidence(phase, projectDir) {
738
- return validateEvidence(phase, projectDir);
739
- }
740
-
741
- /**
742
- * Validate .code-walkthrough-result.json for code walkthrough mode.
743
- * Ported from githooks/pre-push Gate MW inline jq logic.
969
+ * Layer 1.5 of the #519 guard: completing CLOSE means the sprint is over, and
970
+ * that is the moment a final audit is worth running -- so the reminder fires
971
+ * there rather than needing to be remembered.
744
972
  *
745
- * @param {string} projectDir - Project root directory
746
- * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
973
+ * @param {number} phase
974
+ * @param {string} status
975
+ * @param {boolean} renderFlag
976
+ * @param {object} newState
747
977
  */
748
- function checkWalkthrough(projectDir) {
749
- const walkthroughFile = path.join(projectDir, '.code-walkthrough-result.json');
750
- const errors = [];
751
- const warnings = [];
752
-
753
- if (!fs.existsSync(walkthroughFile)) {
754
- errors.push('.code-walkthrough-result.json not found — run delphi-review --mode code-walkthrough before push');
755
- return { ok: false, errors, warnings };
978
+ function printTransitionFollowUps(phase, status, renderFlag, newState) {
979
+ if (phase === PHASE_CLOSE && status === 'completed') {
980
+ console.log('');
981
+ console.log('📋 [sprint-audit] Sprint complete — run final coverage audit:');
982
+ console.log(' npx xp-gate sprint-audit');
756
983
  }
757
-
758
- let data;
759
- try {
760
- data = JSON.parse(fs.readFileSync(walkthroughFile, 'utf8'));
761
- } catch {
762
- errors.push('.code-walkthrough-result.json is malformed JSON');
763
- return { ok: false, errors, warnings };
984
+ if (renderFlag) {
985
+ console.log('');
986
+ console.log(renderDashboard(newState));
764
987
  }
988
+ }
765
989
 
766
- // Check verdict
767
- if (data.verdict !== 'APPROVED') {
768
- errors.push(`Code walkthrough verdict is "${data.verdict}" — must be APPROVED`);
769
- return { ok: false, errors, warnings };
990
+ async function handlePhaseTransition(args = []) {
991
+ if (args.includes('--help')) {
992
+ printTransitionUsage();
993
+ return 0;
770
994
  }
771
995
 
772
- if (typeof data.commit !== 'string' || !/^[0-9a-f]{7,64}$/i.test(data.commit)) {
773
- errors.push('Code walkthrough commit must be a hexadecimal Git commit ID');
774
- return { ok: false, errors, warnings };
996
+ const parsed = parseTransitionArgs(args);
997
+ if (parsed.error) {
998
+ console.error(`Error: ${parsed.error}`);
999
+ return 1;
775
1000
  }
1001
+ const { phase, status, projectDir, renderFlag, outputs,
1002
+ skipEvidence, skipEvidenceReason, forceTransition } = parsed;
776
1003
 
1004
+ if (!validateTransitionInput(phase, status)) return 1;
1005
+
1006
+ // Execute transition
777
1007
  try {
778
- const currentCommit = execFileSync('git', ['rev-parse', 'HEAD'], {
779
- cwd: projectDir,
780
- env: createRepositoryGitEnv(),
781
- encoding: 'utf8',
782
- stdio: 'pipe',
783
- }).trim();
784
- if (data.commit !== currentCommit) {
785
- errors.push(`Code walkthrough commit ${data.commit} does not match HEAD ${currentCommit}`);
786
- return { ok: false, errors, warnings };
787
- }
788
- } catch {
789
- errors.push('Unable to resolve the current Git commit for code walkthrough validation');
790
- return { ok: false, errors, warnings };
791
- }
1008
+ const manager = new SprintStateManager(projectDir);
792
1009
 
793
- // Check expiration
794
- if (data.expires) {
795
- const expiry = new Date(data.expires).getTime();
796
- if (Date.now() > expiry) {
797
- errors.push(`Code walkthrough expired at ${data.expires}`);
798
- return { ok: false, errors, warnings };
799
- }
800
- }
1010
+ // ── #519 Layer 0: Sequence guard ──
1011
+ if (!passesSequenceGuard(manager, phase, status, forceTransition)) return 1;
801
1012
 
802
- return { ok: true, errors, warnings };
1013
+ // ── Layer 1: Pre-transition gate check ──
1014
+ warnOnUnfinishedPredecessor(manager, phase, status);
1015
+
1016
+ // ── Layer 2: Evidence validation ──
1017
+ if (!checkEvidenceGate(phase, projectDir, status, skipEvidence, skipEvidenceReason)) return 1;
1018
+
1019
+ const newState = applyTransition(manager, phase, status, outputs);
1020
+
1021
+ printTransitionFollowUps(phase, status, renderFlag, newState);
1022
+
1023
+ return 0;
1024
+ } catch (err) {
1025
+ console.error(`Error: Phase transition failed: ${err.message}`);
1026
+ return 1;
1027
+ }
803
1028
  }
804
1029
 
805
1030
  /**
806
- * D8 Layer 3: Check bypass audit log for any --no-verify bypassed commits on the current branch.
807
- * Blocks phase transition if bypassed commits exist.
1031
+ * Read-only evidence check for a given phase. Validates evidence without modifying sprint state.
1032
+ * D3 (Unify Evidence Validation): replaces sprint-gate.sh inline JSON parsing.
808
1033
  *
1034
+ * @param {number} phase - Phase number (1-6)
809
1035
  * @param {string} projectDir - Project root directory
810
- * @returns {{ ok: boolean, bypassedCommits: string[] }}
1036
+ * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
811
1037
  */
812
- function checkBypassAudit(projectDir) {
813
- const auditFile = path.join(projectDir, '.xp-gate', 'bypass-audit.jsonl');
814
- const bypassedCommits = [];
815
1038
 
816
- if (!fs.existsSync(auditFile)) {
817
- return { ok: true, bypassedCommits };
818
- }
819
-
820
- const lines = fs.readFileSync(auditFile, 'utf8').trim().split('\n').filter(Boolean);
821
- for (const line of lines) {
822
- try {
823
- const entry = JSON.parse(line);
824
- if (entry.type === 'precommit_bypass' && entry.commit) {
825
- // Verify the commit is on the current branch
826
- try {
827
- execFileSync('git', ['merge-base', '--is-ancestor', entry.commit, 'HEAD'], {
828
- cwd: projectDir,
829
- env: createRepositoryGitEnv(),
830
- stdio: 'pipe',
831
- });
832
- bypassedCommits.push(entry.commit);
833
- } catch {
834
- // Commit not on current branch — not relevant
835
- }
836
- }
837
- } catch {
838
- // Skip malformed lines
839
- }
840
- }
841
-
842
- return { ok: bypassedCommits.length === 0, bypassedCommits };
843
- }
1039
+ const {
1040
+ checkEvidence, checkWalkthrough, checkBypassAudit, validateWalkthroughVerdict,
1041
+ loadWalkthroughFile, createRepositoryGitEnv, GIT_REPOSITORY_ENV_VARS,
1042
+ } = require('./prepush-evidence.js');
844
1043
 
845
- module.exports = { handlePhaseTransition, renderDashboard, PHASE_NAMES, validateEvidence, checkEvidence, checkWalkthrough, checkBypassAudit };
1044
+ module.exports = { buildHistoryLookup, buildProgressBar, statusIcon, formatDuration, appendOutputsSection, appendFrameHeader,
1045
+ handlePhaseTransition, renderDashboard, PHASE_NAMES, validateEvidence, checkEvidence, checkWalkthrough, checkBypassAudit };