@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
@@ -21,9 +21,6 @@ const VALID_MODES = ['design', 'code-walkthrough', 'requirements'];
21
21
  const DEFAULT_TIMEOUT_MS = 30000;
22
22
 
23
23
  // Shared by CLI --timeout-ms and provider timeout_ms validation.
24
- function isValidTimeoutMs(value) {
25
- return Number.isInteger(value) && value >= 1000 && value <= 600000;
26
- }
27
24
 
28
25
  // Flag -> args key. `null` marks flags that take no value. Keeping this as data
29
26
  // means a new flag is one table row instead of one more switch arm (the switch
@@ -39,21 +36,86 @@ const VALUE_FLAGS = {
39
36
  '--other-experts-file': 'otherExpertsFile',
40
37
  };
41
38
  const BOOLEAN_FLAGS = { '--fallback-local': 'fallbackLocal' };
42
- const INTEGER_FLAGS = { '--round': (v) => parseInt(v) };
39
+ /**
40
+ * Integer flags, each rejecting a value that is not an integer.
41
+ *
42
+ * `parseInt('abc')` is NaN, and NaN is falsy -- so the "was it supplied?" checks saw a
43
+ * missing flag and reported THAT, hiding the real problem (the value is not a number)
44
+ * behind the wrong diagnosis (review FC-04).
45
+ */
46
+ const INTEGER_FLAGS = {
47
+ '--round': (v) => {
48
+ const parsed = Number(v);
49
+ if (!Number.isInteger(parsed)) {
50
+ console.error(`[delphi-review] ERROR: --round needs an integer, got ${JSON.stringify(v)}`);
51
+ process.exit(2);
52
+ }
53
+ return parsed;
54
+ },
55
+ };
56
+
57
+ /**
58
+ * Record one flag's value, advancing past it when it consumes the next token.
59
+ *
60
+ * Three shapes, in the order they are tried: `--timeout-ms` is held aside for its own
61
+ * validation, a BOOLEAN flag takes no value, and a VALUE flag takes the next token --
62
+ * converted when an integer parser is registered for it.
63
+ *
64
+ * @returns the index of the last token consumed
65
+ */
66
+ function applyRawFlag(argv, i, args, state) {
67
+ const flag = argv[i];
68
+ if (flag === '--timeout-ms') {
69
+ state.timeoutMsRaw = requireFlagValue(argv, i, flag);
70
+ return i + 1;
71
+ }
72
+ if (BOOLEAN_FLAGS[flag]) {
73
+ args[BOOLEAN_FLAGS[flag]] = true;
74
+ return i;
75
+ }
76
+ const key = VALUE_FLAGS[flag];
77
+ if (!key) {
78
+ // UNKNOWN flag: fail rather than ignore. Silently skipping it means a typo like
79
+ // `--expert` -> `--experts` falls back to the default behaviour instead of the
80
+ // caller's intent, which is the fail-open this gate exists to prevent (review FC-01).
81
+ if (flag.startsWith('-')) {
82
+ console.error(`[delphi-review] ERROR: unknown option ${flag}`);
83
+ process.exit(2);
84
+ }
85
+ return i;
86
+ }
87
+ const value = requireFlagValue(argv, i, flag);
88
+ args[key] = INTEGER_FLAGS[flag] ? INTEGER_FLAGS[flag](value) : value;
89
+ return i + 1;
90
+ }
91
+
92
+ /**
93
+ * The value that follows a flag, or a message naming the flag.
94
+ *
95
+ * Reading `argv[i + 1]` unchecked put `undefined` into the arguments, and the run then
96
+ * failed LATER with a message about something else -- a missing API key, in the case
97
+ * measured -- so the operator fixed the wrong thing (all three seats, same finding).
98
+ */
99
+ function requireFlagValue(argv, i, flag) {
100
+ const value = argv[i + 1];
101
+ // ABSENT only. A leading `--` is NOT treated as "missing": `-1` and a path like
102
+ // `--my-config.json` are legal values, and rejecting them broke working call sites
103
+ // (review CI-01 / FC-03, two seats). A flag whose value was forgotten still fails --
104
+ // at the point where the value is USED, with a message about that value.
105
+ if (value === undefined) {
106
+ console.error(`[delphi-review] ERROR: ${flag} needs a value`);
107
+ process.exit(2);
108
+ }
109
+ return value;
110
+ }
43
111
 
44
112
  function collectRawArgs(argv) {
45
113
  const args = {};
46
- let timeoutMsRaw;
114
+ const state = { timeoutMsRaw: undefined };
47
115
  for (let i = 0; i < argv.length; i++) {
48
- const flag = argv[i];
49
- if (flag === '--timeout-ms') { timeoutMsRaw = argv[++i]; continue; }
50
- if (BOOLEAN_FLAGS[flag]) { args[BOOLEAN_FLAGS[flag]] = true; continue; }
51
- const key = VALUE_FLAGS[flag];
52
- if (!key) continue;
53
- const value = argv[++i];
54
- args[key] = INTEGER_FLAGS[flag] ? INTEGER_FLAGS[flag](value) : value;
116
+ i = applyRawFlag(argv, i, args, state);
55
117
  }
56
- return { args, timeoutMsRaw };
118
+ return { args, timeoutMsRaw: state.timeoutMsRaw };
57
119
  }
58
120
 
59
121
  function fail(message) {
@@ -63,13 +125,27 @@ function fail(message) {
63
125
 
64
126
  // Every rejection path used to inline its own console.error + exit. Collected
65
127
  // here so the rules read as rules and each message stays verbatim.
128
+ /**
129
+ * The arguments a review cannot start without, and how each is satisfied.
130
+ *
131
+ * A table so a new required argument is a row. `--input` has TWO acceptable spellings,
132
+ * which is why the requirement is a predicate rather than a key name: reporting
133
+ * "missing --input" when the caller passed `--input-file` would send them to fix the
134
+ * wrong thing.
135
+ */
136
+ const REQUIRED_ARGS = [
137
+ { satisfied: (a) => Boolean(a.expert), label: '--expert' },
138
+ { satisfied: (a) => Boolean(a.input || a.inputFile), label: '--input or --input-file' },
139
+ // NOT `Boolean(a.round)`: round 0 is a legal value and Boolean(0) is false, so the
140
+ // check reported "--round is missing" for a value that was supplied (review CI-01).
141
+ // Numbers are tested for presence, strings for emptiness.
142
+ { satisfied: (a) => a.round !== undefined && a.round !== null, label: '--round' },
143
+ { satisfied: (a) => Boolean(a.config), label: '--config' },
144
+ ];
145
+
146
+ /** The arguments that are absent, by the label to show the user. */
66
147
  function missingArgumentList(args) {
67
- const missing = [];
68
- if (!args.expert) missing.push('--expert');
69
- if (!args.input && !args.inputFile) missing.push('--input or --input-file');
70
- if (!args.round) missing.push('--round');
71
- if (!args.config) missing.push('--config');
72
- return missing;
148
+ return REQUIRED_ARGS.filter((req) => !req.satisfied(args)).map((req) => req.label);
73
149
  }
74
150
 
75
151
  function applyTimeoutFlag(args, timeoutMsRaw) {
@@ -115,312 +191,41 @@ function parseArgs(argv) {
115
191
  // only surfaced at runtime (a bad timeout_ms fell back to the default). The
116
192
  // whole profile is checked here instead, at the system boundary, naming the
117
193
  // provider so the fix is obvious (#429).
118
- function validateProviders(providers, profileName) {
119
- for (const [name, provider] of Object.entries(providers)) {
120
- const providerPath = `profiles.${profileName}.providers.${name}`;
121
- const fail = (detail) => {
122
- console.error(`[delphi-review] ERROR: ${providerPath} ${detail}`);
123
- process.exit(1);
124
- };
125
-
126
- if (!isPlainObject(provider)) fail('must be an object.');
127
- if (typeof provider.base_url !== 'string' || provider.base_url.trim() === '') fail('must define a non-empty base_url.');
128
- if (typeof provider.api_key !== 'string' || provider.api_key.trim() === '') fail('must define a non-empty api_key.');
129
- if (provider.timeout_ms !== undefined && !isValidTimeoutMs(provider.timeout_ms)) {
130
- fail('timeout_ms must be an integer between 1000 and 600000.');
131
- }
132
- }
133
- }
134
-
135
- function readConfig(configPath, profileOverride) {
136
- // Global fallback: a relative --config that this cwd does not have resolves
137
- // to the machine-wide ~/.config/xp-gate/.delphi-config.json. This is what
138
- // makes `--config .delphi-config.json` work from ANY project without each
139
- // repo carrying its own (drifting, differently-priced) copy — reading a
140
- // foreign project's config used to route calls to expensive models
141
- // (2026-10-03 quota incident). An existing local file always wins.
142
- // Fallback fires ONLY when the project file is genuinely absent: statSync
143
- // distinguishes ENOENT from EACCES/EISDIR, and any other error aborts here
144
- // rather than silently routing this run to another config — matching the
145
- // TS loader's ENOENT-only semantics (walkthrough R10 FC-01).
146
- const missingHere = (() => {
147
- try { fs.statSync(configPath); return false; } catch (e) { return e.code === 'ENOENT'; }
148
- })();
149
- if (missingHere && !path.isAbsolute(configPath)) {
150
- // r16 MA-01 disposition: XDG_CONFIG_HOME is an accepted override for the
151
- // global config location. The CLI lib (shared-paths/doctor) intentionally
152
- // pins ~/.config/xp-gate — overriding only this loader would make the two
153
- // disagree. On Linux, $HOME/.config IS the XDG default, so behaviour there
154
- // is identical; the env var only matters for non-default setups.
155
- // Extracted so all three resolution points share one definition (REQ-636).
156
- const globalPath = globalConfigPath(process.env);
157
- if (fs.existsSync(globalPath)) {
158
- console.error(`[delphi-review] ${configPath} not found here — using global config ${globalPath}`);
159
- configPath = globalPath;
160
- }
161
- }
162
- if (!fs.existsSync(configPath)) {
163
- console.error(`[delphi-review] ERROR: Config file not found: ${configPath}`);
164
- console.error('[delphi-review] Copy .delphi-config.json.example to .delphi-config.json and fill in your API keys.');
165
- process.exit(1);
166
- }
167
-
168
- let raw;
169
- try {
170
- raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
171
- } catch (err) {
172
- console.error(`[delphi-review] ERROR: Failed to parse config: ${err.message}`);
173
- process.exit(1);
174
- }
175
-
176
- const profileName = profileOverride || raw.active_profile || 'default';
177
- const profile = raw.profiles?.[profileName];
178
-
179
- if (!profile) {
180
- console.error(`[delphi-review] ERROR: Profile "${profileName}" not found in config.`);
181
- console.error(`[delphi-review] Available profiles: ${Object.keys(raw.profiles || {}).join(', ')}`);
182
- process.exit(1);
183
- }
184
-
185
- // Resolve ${ENV_VAR} references in provider api_key fields
186
- const providers = profile.providers || {};
187
- validateProviders(providers, profileName);
188
- for (const [name, prov] of Object.entries(providers)) {
189
- if (prov.api_key && prov.api_key.startsWith('${') && prov.api_key.endsWith('}')) {
190
- const envName = prov.api_key.slice(2, -1);
191
- const envVal = process.env[envName];
192
- if (envVal) {
193
- prov.api_key = envVal;
194
- } else {
195
- // A missing variable used to be a WARNING, after which the runner sent the
196
- // literal `Bearer ${NAME}` and reported the 401 as "check API key" — the
197
- // diagnosis pointed at a wrong key while the real cause was the shell.
198
- console.error(`[delphi-review] ERROR: Environment variable ${envName} is not set (profiles.${profileName}.providers.${name}.api_key). Export it or point that provider at a literal key.`);
199
- process.exit(1);
200
- }
201
- }
202
194
 
203
- // (#707) base_url supports ${VAR} for the same reason api_key does: writing a
204
- // gateway address as a placeholder is the natural way to keep an internal
205
- // endpoint out of version control. Without expansion the placeholder is a
206
- // perfectly valid non-empty string, so validation passed and the literal text
207
- // `${PG_GATEWAY}/v1/chat/completions` went out as a URL — failing at the
208
- // NETWORK layer with a DNS/connection error while the config looked correct.
209
- // A caller (whale-sql-audit) had to hardcode its gateway into a distributed
210
- // repo because of this.
211
- //
212
- // Failing here, at config load, names the variable; falling back to the
213
- // literal is exactly what caused the original misdiagnosis, so it does not.
214
- if (typeof prov.base_url === 'string'
215
- && prov.base_url.startsWith('${') && prov.base_url.endsWith('}')) {
216
- const envName = prov.base_url.slice(2, -1);
217
- const envVal = process.env[envName];
218
- if (!envVal) {
219
- console.error(`[delphi-review] ERROR: Environment variable ${envName} is not set (profiles.${profileName}.providers.${name}.base_url). Export it or point that provider at a literal URL.`);
220
- process.exit(1);
221
- }
222
- prov.base_url = envVal;
223
- }
224
- }
225
195
 
226
- const experts = Object.fromEntries(Object.entries(profile.experts || {}).map(([role, expert]) => [
227
- role,
228
- {
229
- ...expert,
230
- model: typeof expert.model === 'string' ? expert.model.trim() : expert.model,
231
- },
232
- ]));
233
- const warnings = [];
234
- if (raw.consensus?.distinct_models_required === false) {
235
- warnings.push('distinct_models_required_forced');
236
- }
237
- const configuredThreshold = raw.consensus?.threshold_percent;
238
- const thresholdPercent = typeof configuredThreshold === 'number' && Number.isFinite(configuredThreshold)
239
- ? Math.max(90, configuredThreshold)
240
- : 90;
241
- if (configuredThreshold !== undefined && configuredThreshold !== thresholdPercent) {
242
- warnings.push('threshold_percent_clamped');
243
- }
244
- const configuredRounds = raw.consensus?.max_review_rounds;
245
- const maxReviewRounds = typeof configuredRounds === 'number' && Number.isFinite(configuredRounds)
246
- ? Math.min(5, Math.max(1, Math.trunc(configuredRounds)))
247
- : 5;
248
- if (configuredRounds !== undefined && configuredRounds !== maxReviewRounds) {
249
- warnings.push('max_review_rounds_clamped');
250
- }
251
-
252
- return {
253
- active_profile: profileName,
254
- providers,
255
- experts,
256
- consensus: {
257
- ...(raw.consensus || {}),
258
- threshold_percent: thresholdPercent,
259
- max_review_rounds: maxReviewRounds,
260
- distinct_models_required: true,
261
- },
262
- warnings,
263
- };
264
- }
265
-
266
- // ── Distinct-model validation ───────────────────────────────────────────
267
- const REQUIRED_EXPERT_ROLES = ['architecture', 'technical', 'feasibility'];
268
-
269
- function isNonEmptyString(value) {
270
- return typeof value === 'string' && value.trim() !== '';
271
- }
272
-
273
- // Roles must be EXACTLY the three required ones: a missing role means the
274
- // review would silently run with two experts, an extra one means the config
275
- // no longer matches the three-model policy. One pass reports both.
276
- function collectModelAssignments(expertMap) {
277
- const assignments = [];
278
- for (const role of REQUIRED_EXPERT_ROLES) {
279
- const expert = expertMap[role];
280
- if (!expert) return { error: `Missing required expert role: ${role}.` };
281
- if (!isNonEmptyString(expert.model)) {
282
- return { error: `Expert ${role} must define a non-empty model.` };
283
- }
284
- assignments.push({ role, model: expert.model.trim() });
285
- }
286
- const unexpectedRole = Object.keys(expertMap).find(role => !REQUIRED_EXPERT_ROLES.includes(role));
287
- if (unexpectedRole) return { error: `Unsupported expert role: ${unexpectedRole}.` };
288
- return { assignments };
289
- }
290
-
291
- function findDuplicateModel(assignments) {
292
- const seen = new Map();
293
- for (const { role, model } of assignments) {
294
- const previousRole = seen.get(model);
295
- if (previousRole) {
296
- return `duplicate model "${model}" assigned to ${previousRole} and ${role}.`;
297
- }
298
- seen.set(model, role);
299
- }
300
- return null;
301
- }
302
-
303
- // Everything an expert's provider must carry to be callable. Returns the
304
- // human-readable reason instead of throwing, so the caller keeps one shape.
305
- function providerConfigError(role, expert, providerMap) {
306
- if (!isNonEmptyString(expert.provider) || expert.provider === 'local') {
307
- return `Expert ${role} must define a non-local callable provider.`;
308
- }
309
- const provider = providerMap[expert.provider];
310
- if (!provider || typeof provider !== 'object' || Array.isArray(provider)) {
311
- return `Expert ${role} provider configuration must be an object.`;
312
- }
313
- if (!isNonEmptyString(provider.base_url)) {
314
- return `Expert ${role} provider must define a non-empty base_url.`;
315
- }
316
- if (!isNonEmptyString(provider.api_key)) {
317
- return `Expert ${role} provider must define a non-empty api_key.`;
318
- }
319
- if (provider.timeout_ms !== undefined && !isValidTimeoutMs(provider.timeout_ms)) {
320
- return `Expert ${role} provider ${expert.provider} timeout_ms must be an integer between 1000 and 600000.`;
321
- }
322
- return null;
323
- }
324
-
325
- function validateDistinctModels(experts, providers, consensus = {}) {
326
- const expertMap = experts && typeof experts === 'object' ? experts : {};
327
- const providerMap = providers && typeof providers === 'object' ? providers : {};
328
-
329
- const collected = collectModelAssignments(expertMap);
330
- if (collected.error) return { valid: false, reason: collected.error };
331
-
332
- const duplicate = findDuplicateModel(collected.assignments);
333
- if (duplicate) return { valid: false, reason: duplicate };
334
-
335
- for (const role of REQUIRED_EXPERT_ROLES) {
336
- const error = providerConfigError(role, expertMap[role], providerMap);
337
- if (error) return { valid: false, reason: error };
338
- }
339
-
340
- if (consensus.cross_provider_required === true) {
341
- return {
342
- valid: true,
343
- warning: 'cross_provider_required_ignored',
344
- };
345
- }
196
+ /**
197
+ * Resolve and parse the config file.
198
+ *
199
+ * Split out of `readConfig`, which had grown past the 50-line bound by holding
200
+ * two jobs: decide WHICH file, then decide what it means. The first job carries
201
+ * a real hazard worth testing on its own -- a relative `--config` that this cwd
202
+ * lacks resolves to the machine-wide config, but only when the project file is
203
+ * genuinely ABSENT. Any other stat error aborts rather than silently routing the
204
+ * run to another config, which once routed calls to expensive models.
205
+ *
206
+ * @param {string} configPath
207
+ * @returns {object} the parsed config
208
+ */
346
209
 
347
- return { valid: true };
348
- }
210
+ const {
211
+ isNonEmptyString,
212
+ collectModelAssignments,
213
+ findDuplicateModel,
214
+ providerConfigError,
215
+ validateDistinctModels,
216
+ isValidTimeoutMs,
217
+ parseExpertVerdict,
218
+ clampConsensusSetting,
219
+ expandEnvPlaceholder,
220
+ } = require('./delphi-model-validation.cjs');
221
+ const { readConfig, globalConfigPath } = require('./delphi-config-read.cjs');
222
+ const { converseWithTools } = require('./delphi-repo-tools.cjs');
349
223
 
350
224
  // ── JSON extraction (4-layer fallback) ─────────────────────────────────
351
- function extractJsonFromResponse(content) {
352
- if (!content || typeof content !== 'string') {
353
- return { parse_error: true, raw_content: String(content || '') };
354
- }
355
-
356
- const trimmed = content.trim();
357
-
358
- // Layer 1: Direct parse
359
- try {
360
- return JSON.parse(trimmed);
361
- } catch { /* continue */ }
362
-
363
- // Layer 2: Strip markdown code block
364
- const codeBlockMatch = trimmed.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
365
- if (codeBlockMatch) {
366
- try {
367
- return JSON.parse(codeBlockMatch[1].trim());
368
- } catch { /* continue */ }
369
- }
370
-
371
- // Layer 3: Extract first JSON object
372
- const jsonMatch = trimmed.match(/\{[\s\S]*\}/);
373
- if (jsonMatch) {
374
- try {
375
- return JSON.parse(jsonMatch[0]);
376
- } catch { /* continue */ }
377
- }
378
-
379
- // Layer 4: Fallback
380
- return { parse_error: true, raw_content: trimmed };
381
- }
225
+ const { extractJsonFromResponse } = require('./delphi-json-extract.cjs');
382
226
 
383
227
  // ── System prompt templates ────────────────────────────────────────────
384
- const SYSTEM_PROMPTS = {
385
- architecture: `你是架构评审专家(Delphi Method - Architecture Expert)。
386
-
387
- 你的评审关注维度:
388
- 1) 需求对齐度 — 设计是否完整覆盖所有需求
389
- 2) 系统一致性 — 与现有架构风格、模式是否一致
390
- 3) 模块边界清晰度 — 职责划分是否明确,耦合度是否合理
391
- 4) 架构演进性 — 是否为未来扩展留有空间
392
- 5) 技术选型合理性 — 技术栈选择是否有充分依据
393
-
394
- 输出要求:返回结构化 JSON,包含 verdict (APPROVED/REQUEST_CHANGES/REJECTED)、confidence (1-10,整数,10 为最高)、summary (字符串)。critical_issues、major_concerns、minor_concerns 必须是字符串数组(string[]),每项是一句自包含的完整描述(可加 "CI-01: " 前缀,但整体必须是字符串,不是对象)。不要把问题写成 {id, title, description} 对象。`,
395
-
396
- technical: `你是技术实现评审专家(Delphi Method - Technical Expert)。
397
-
398
- 你的评审关注维度:
399
- 1) 实现正确性 — 逻辑是否正确,边界条件是否处理
400
- 2) 代码质量和设计模式 — 是否遵循 SOLID 原则,代码是否清晰
401
- 3) 边界情况和错误处理 — 异常路径是否覆盖,错误处理是否健壮
402
- 4) 性能影响 — 是否有性能瓶颈或资源泄漏风险
403
- 5) 可测试性 — 代码是否易于编写单元测试
404
-
405
- 输出要求:返回结构化 JSON,包含 verdict (APPROVED/REQUEST_CHANGES/REJECTED)、confidence (1-10,整数,10 为最高)、summary (字符串)。critical_issues、major_concerns、minor_concerns 必须是字符串数组(string[]),每项是一句自包含的完整描述(可加 "MC-01: " 前缀,但整体必须是字符串,不是对象)。不要把问题写成 {id, title, description} 对象。`,
406
-
407
- feasibility: `你是可行性分析专家(Delphi Method - Feasibility Expert)。
408
-
409
- 你的评审关注维度:
410
- 1) 实际约束(时间/资源/依赖)— 是否在现有约束下可行
411
- 2) 风险识别和缓解 — 主要风险是否已识别,缓解措施是否充分
412
- 3) 执行复杂度 — 实现难度是否被低估,依赖链是否清晰
413
- 4) 替代方案 — 是否有更简单或更可靠的替代方案
414
- 5) 回滚策略 — 如果实施失败,是否有退路
415
-
416
- 输出要求:返回结构化 JSON,包含 verdict (APPROVED/REQUEST_CHANGES/REJECTED)、confidence (1-10,整数,10 为最高)、summary (字符串)。critical_issues、major_concerns、minor_concerns 必须是字符串数组(string[]),每项是一句自包含的完整描述(可加 "FC-01: " 前缀,但整体必须是字符串,不是对象)。不要把问题写成 {id, title, description} 对象。`,
417
- };
418
-
419
- const MODE_FOCUS_PROMPTS = {
420
- design: '',
421
- 'code-walkthrough': '\n\n本次评审聚焦已实现代码的正确性、风险和可验证结果。',
422
- requirements: '\n\n本次评审聚焦需求陈述的完整性、一致性、可验收性和约束清晰度。',
423
- };
228
+ const { SYSTEM_PROMPTS, MODE_FOCUS_PROMPTS } = require('./delphi-prompts.cjs');
424
229
 
425
230
  function buildSystemPrompt(role, mode = 'design') {
426
231
  const rolePrompt = SYSTEM_PROMPTS[role] || SYSTEM_PROMPTS.architecture;
@@ -441,11 +246,18 @@ function buildUserPrompt(reviewContent, otherExpertsJson, round) {
441
246
  // ── Input content resolution ───────────────────────────────────────────
442
247
  function resolveInputContent(args) {
443
248
  if (args.inputFile) {
444
- if (!fs.existsSync(args.inputFile)) {
445
- console.error(`[delphi-review] ERROR: Input file not found: ${args.inputFile}`);
249
+ // One read, not exists-then-read: the check-then-use pair has a window in
250
+ // which the file can vanish, and the ENOENT that follows would surface as an
251
+ // unhandled throw instead of the message below.
252
+ try {
253
+ return fs.readFileSync(args.inputFile, 'utf8');
254
+ } catch (err) {
255
+ console.error(`[delphi-review] ERROR: Cannot read input file ${args.inputFile}: ${err.message}`);
256
+ // `process.exit` does not return. No statement follows it: a `throw` here is
257
+ // unreachable in production AND a live exception under a test that mocks
258
+ // `process.exit`, which is worse than dead code (review CI-02, twice).
446
259
  process.exit(1);
447
260
  }
448
- return fs.readFileSync(args.inputFile, 'utf8');
449
261
  }
450
262
  return args.input || '';
451
263
  }
@@ -463,17 +275,19 @@ function resolveTimeoutMs(args, providerConfig) {
463
275
  // answered normally, a 50 KB one killed the seat with no usable error, and a
464
276
  // dead expert seat blocks the whole review. The ceiling is therefore checked
465
277
  // before the request is made, where the message can say what to narrow.
466
- const DEFAULT_PROMPT_BUDGET_BYTES = 40000;
467
278
 
468
279
  // A seat-level override (`max_prompt_bytes` on the expert entry) exists because
469
280
  // the ceiling is a property of the model behind the seat, not of the runner.
470
281
  // Values that cannot be honoured fall back to the default rather than disabling
471
282
  // the guard -- `max_prompt_bytes: 0` reads as "no limit" and is not.
283
+ /** Whether a configured prompt budget can be honoured. */
284
+ function isUsableBudget(configured) {
285
+ return typeof configured === 'number' && Number.isFinite(configured) && configured > 0;
286
+ }
287
+
472
288
  function resolvePromptBudgetBytes(expertConfig) {
473
289
  const configured = expertConfig && expertConfig.max_prompt_bytes;
474
- if (typeof configured === 'number' && Number.isFinite(configured) && configured > 0) {
475
- return Math.trunc(configured);
476
- }
290
+ if (isUsableBudget(configured)) return Math.trunc(configured);
477
291
  if (configured !== undefined) {
478
292
  // Silently falling back is how a raised ceiling looks like a still-broken
479
293
  // guard: the operator edits the config, the run still refuses, and nothing
@@ -505,113 +319,18 @@ function describePromptBudgetFailure({ bytes, maxBytes, expert }) {
505
319
  }
506
320
 
507
321
  // ── Seat prompt calibration (#481) ─────────────────────────────────────
508
- // The R1-R4 sprint review proved the ceiling is a seat × model route
509
- // property: g-glm-5.3-flash dropped 32-39 KB requests six times with
510
- // "Network error." while the same gateway served 36 KB to a differently
511
- // routed seat, and a ~60 byte smoke probe on the "dead" seat passed in 7s.
512
- // The optional per-seat `prompt_calibration` record carries the measured
513
- // bounds so failures can be classified against evidence instead of guessed.
514
- // A calibration record is only usable when it carries a measured PASS bound
515
- // and, if it also carries a FAIL bound, that bound is strictly larger. Each
516
- // broken shape names itself so the operator knows which field to correct.
517
- const CALIBRATION_SHAPE_HINT = 'needs measured_at and a finite last_pass_bytes > 0 (last_fail_bytes, if present, must be larger)';
518
-
519
- function isPositiveFinite(value) {
520
- return Number.isFinite(value) && value > 0;
521
- }
522
-
523
- function calibrationProblem(raw) {
524
- if (!isPlainObject(raw)) return 'must be an object';
525
- const pass = raw.last_pass_bytes;
526
- const fail = raw.last_fail_bytes;
527
- const failOk = fail === undefined || isPositiveFinite(fail);
528
- if (!isPositiveFinite(pass) || !failOk) return CALIBRATION_SHAPE_HINT;
529
- if (fail !== undefined && !(fail > pass)) return 'has last_fail_bytes <= last_pass_bytes';
530
- if (!isNonEmptyString(raw.measured_at)) return CALIBRATION_SHAPE_HINT;
531
- return null;
532
- }
533
-
534
- function resolveSeatCalibration(expertConfig) {
535
- const raw = expertConfig && expertConfig.prompt_calibration;
536
- if (raw === undefined) return { calibration: null };
537
- const problem = calibrationProblem(raw);
538
- if (problem) {
539
- console.error(`[delphi-review] WARNING: prompt_calibration ${problem}; ignoring the record.`);
540
- return { calibration: null, warning: 'prompt_calibration_malformed' };
541
- }
542
- return {
543
- calibration: {
544
- measured_at: raw.measured_at,
545
- model_id: typeof raw.model_id === 'string' ? raw.model_id : undefined,
546
- gateway: typeof raw.gateway === 'string' ? raw.gateway : undefined,
547
- last_pass_bytes: Math.trunc(raw.last_pass_bytes),
548
- last_fail_bytes: raw.last_fail_bytes !== undefined ? Math.trunc(raw.last_fail_bytes) : undefined,
549
- },
550
- };
551
- }
552
-
553
- // Classify a failed expert call. A drop before any response on a payload above
554
- // the seat's calibrated passing size is a size ceiling, not a transient fault:
555
- // retrying the same payload cannot succeed, and reporting "Network error."
556
- // sends operators chasing a cause that is not there (#481). Everything else
557
- // gets a stable error_type so orchestrators can assert on the class instead of
558
- // parsing prose.
559
- // The calibrated ceiling for a seat, or null when the seat carries no usable
560
- // record. Null is meaningful: it is the "no evidence to reclassify on" branch.
561
- function calibratedCeiling(calibration) {
562
- if (calibration && Number.isFinite(calibration.last_pass_bytes)) return calibration.last_pass_bytes;
563
- return null;
564
- }
565
-
566
- // `error_kind` is the primary signal; the message literal stays as a
567
- // backward-compatible fallback for callers that hand-build results.
568
- function isPreResponseDrop(result) {
569
- return !result.retryable
570
- && (result.error_kind === 'pre_response_drop' || result.message === 'Network error.');
571
- }
572
-
573
- function sizeExceededResult(result, promptBytes, threshold) {
574
- return {
575
- ...result,
576
- error_type: 'SIZE_EXCEEDED',
577
- retryable: false,
578
- bytes: promptBytes,
579
- calibrated_pass_bytes: threshold,
580
- message: `Request dropped before any response: ${promptBytes} bytes exceeds this seat's calibrated passing size `
581
- + `(${threshold} bytes). Classified SIZE_EXCEEDED, not a network fault — trim the payload or recalibrate the seat.`,
582
- };
583
- }
584
-
585
- // No calibration means no evidence to reclassify on — but an uncalibrated
586
- // seat dying on a full-budget payload is exactly how #481 started. Keep the
587
- // class honest (network_error) and point the operator at the protocol.
588
- function uncalibratedBudgetHint(result, promptBytes) {
589
- return {
590
- ...result,
591
- error_type: 'network_error',
592
- bytes: promptBytes,
593
- message: `${result.message} Note: this seat has no prompt_calibration record and the payload is at the `
594
- + 'default budget — this pattern matches an uncalibrated size ceiling. Recalibrate per the #481 protocol.',
595
- };
596
- }
597
-
598
- function classifySeatFailure({ result, promptBytes, calibration }) {
599
- if (!result || !result.error) return result;
600
- if (!isPreResponseDrop(result)) {
601
- return { ...result, error_type: result.retryable ? 'retryable_error' : 'network_error' };
602
- }
603
- const threshold = calibratedCeiling(calibration);
604
- if (!Number.isFinite(promptBytes)) {
605
- return { ...result, error_type: 'network_error' };
606
- }
607
- if (threshold !== null && promptBytes > threshold) {
608
- return sizeExceededResult(result, promptBytes, threshold);
609
- }
610
- if (threshold === null && promptBytes >= DEFAULT_PROMPT_BUDGET_BYTES) {
611
- return uncalibratedBudgetHint(result, promptBytes);
612
- }
613
- return { ...result, error_type: 'network_error' };
614
- }
322
+ const {
323
+ isPlainObject,
324
+ DEFAULT_PROMPT_BUDGET_BYTES,
325
+ isPositiveFinite,
326
+ calibrationProblem,
327
+ resolveSeatCalibration,
328
+ calibratedCeiling,
329
+ isPreResponseDrop,
330
+ sizeExceededResult,
331
+ uncalibratedBudgetHint,
332
+ classifySeatFailure,
333
+ } = require('./delphi-seat-calibration.cjs');
615
334
 
616
335
  // ── Schema retry (#414 REQ-5) ──────────────────────────────────────────
617
336
  // g-qwen3.8-flash occasionally answers in prose or malformed JSON (measured
@@ -711,33 +430,47 @@ async function classifyRateLimitResponse(response) {
711
430
  * previous retryable=true, and an unparseable body keeps the previous behaviour
712
431
  * entirely — reading the body must not change the verdict on its own.
713
432
  */
433
+ /** A provider's error detail, and whether it is a CONTENT-dependent failure. */
434
+ /** The gateway's `error` object, or null when the body has none. */
435
+ function providerErrorOf(body) {
436
+ return body && body.error && typeof body.error === 'object' ? body.error : null;
437
+ }
438
+
439
+ /** A field the error object carries, or '' when it is absent or not a string. */
440
+ function stringField(holder, key) {
441
+ return typeof holder[key] === 'string' ? holder[key] : '';
442
+ }
443
+
444
+ function readProviderError(body) {
445
+ const error = providerErrorOf(body);
446
+ if (!error) return { detail: '', processingError: false };
447
+
448
+ const type = stringField(error, 'type');
449
+ const parts = [type, stringField(error, 'param')].filter(Boolean);
450
+ return {
451
+ detail: parts.length > 0 ? ` Provider reported: ${parts.join('/')}.` : '',
452
+ processingError: type === 'response_processing_error',
453
+ };
454
+ }
455
+
714
456
  async function classifyServerErrorResponse(response) {
715
- let detail = '';
716
- let processingError = false;
457
+ let provider = { detail: '', processingError: false };
717
458
  try {
718
- const body = await response.json();
719
- if (body && body.error && typeof body.error === 'object') {
720
- const type = typeof body.error.type === 'string' ? body.error.type : '';
721
- const param = typeof body.error.param === 'string' ? body.error.param : '';
722
- if (type === 'response_processing_error') {
723
- processingError = true;
724
- }
725
- const parts = [type, param].filter(Boolean);
726
- if (parts.length > 0) {
727
- detail = ` Provider reported: ${parts.join('/')}.`;
728
- }
729
- }
459
+ provider = readProviderError(await response.json());
730
460
  } catch {
731
- // body is not JSON; keep the previous behaviour untouched
461
+ // Body is not JSON; the plain status message is all there is to report.
732
462
  }
733
- if (processingError) {
463
+ // A `response_processing_error` is CONTENT-dependent: the same prompt fails the same
464
+ // way every time, so retrying it only burns three timeouts. That distinction is what
465
+ // makes this retryable-false rather than a generic 5xx retry.
466
+ if (provider.processingError) {
734
467
  return {
735
468
  error: true,
736
469
  retryable: false,
737
- message: `Server error (${response.status}).${detail} This is a content-dependent upstream processing failure, so retrying the same prompt will fail the same way.`,
470
+ message: `Server error (${response.status}).${provider.detail} This is a content-dependent upstream processing failure, so retrying the same prompt will fail the same way.`,
738
471
  };
739
472
  }
740
- return { error: true, retryable: true, message: `Server error (${response.status}).${detail}` };
473
+ return { error: true, retryable: true, message: `Server error (${response.status}).${provider.detail}` };
741
474
  }
742
475
 
743
476
  /**
@@ -748,18 +481,41 @@ async function classifyServerErrorResponse(response) {
748
481
  * model count as a successful expert call (#423). Fail at the source instead,
749
482
  * so the evidence never records an unverifiable expert.
750
483
  */
484
+ /**
485
+ * The text of the first choice, or null when the shape is not what a chat completion
486
+ * looks like.
487
+ *
488
+ * Read defensively at every level: this parses a GATEWAY's response, and a gateway
489
+ * that returns a different shape must produce "invalid response" rather than a
490
+ * TypeError deep in the caller.
491
+ */
492
+ /** The `message` of a chat-completion choice, or null when it has none. */
493
+ function choiceMessage(choice) {
494
+ return isPlainObject(choice) ? choice.message : null;
495
+ }
496
+
497
+ /** The non-empty text of a message, or null. */
498
+ function messageText(message) {
499
+ const content = isPlainObject(message) ? message.content : null;
500
+ if (typeof content !== 'string') return null;
501
+ const trimmed = content.trim();
502
+ return trimmed === '' ? null : trimmed;
503
+ }
504
+
505
+ function firstChoiceContent(data) {
506
+ if (!isPlainObject(data) || !Array.isArray(data.choices)) return null;
507
+ return messageText(choiceMessage(data.choices[0]));
508
+ }
509
+
751
510
  async function readSuccessfulResponse(response) {
752
511
  const data = await response.json();
753
- if (!isPlainObject(data) || !Array.isArray(data.choices)) {
754
- return { error: true, message: 'Invalid response from model.' };
755
- }
756
- const firstChoice = data.choices[0];
757
- const message = isPlainObject(firstChoice) ? firstChoice.message : null;
758
- const content = isPlainObject(message) ? message.content : null;
759
- if (typeof content !== 'string' || content.trim() === '') {
760
- return { error: true, message: 'Invalid response from model.' };
761
- }
512
+ const content = firstChoiceContent(data);
513
+ if (!content) return { error: true, message: 'Invalid response from model.' };
762
514
 
515
+ // The gateway must echo which model actually served the request. Writing `null` here
516
+ // used to be tolerated downstream, which let a run that never resolved a model count
517
+ // as a successful expert call (#423). Fail at the source so the evidence never
518
+ // records an unverifiable expert.
763
519
  const resolvedModel = typeof data.model === 'string' ? data.model.trim() : '';
764
520
  if (resolvedModel === '') {
765
521
  return {
@@ -767,12 +523,7 @@ async function readSuccessfulResponse(response) {
767
523
  message: 'Gateway response did not include a resolved model id; cannot prove which model ran.',
768
524
  };
769
525
  }
770
-
771
- return {
772
- success: true,
773
- content: content.trim(),
774
- resolved_model: resolvedModel,
775
- };
526
+ return { success: true, content, resolved_model: resolvedModel };
776
527
  }
777
528
 
778
529
  /**
@@ -788,10 +539,51 @@ function buildChatBody(model, systemPrompt, userPrompt) {
788
539
  { role: 'user', content: userPrompt },
789
540
  ],
790
541
  temperature: 0.3,
791
- response_format: { type: 'json_object' },
542
+ // The JSON shape is asked for in the SYSTEM PROMPT, not via response_format: a
543
+ // response_format forces the model to answer immediately, which the tool rounds below
544
+ // make impossible (a tool call is not a JSON object).
792
545
  };
793
546
  }
794
547
 
548
+ /**
549
+ * Turn an HTTP response into the runner's result shape.
550
+ *
551
+ * The status ladder lived inline in `callModelAPI` (58 lines, over the bound).
552
+ * It is a policy about which failures are worth retrying and which need the
553
+ * operator -- 401/403 is a key problem the code cannot fix, 429 and 5xx may pass
554
+ * on their own, and anything else is reported without echoing the provider body.
555
+ *
556
+ * @param {Response} response
557
+ * @returns {Promise<object>}
558
+ */
559
+ async function classifyHttpResponse(response) {
560
+ if (response.status === 401 || response.status === 403) {
561
+ return { error: true, message: `Authentication failed (${response.status}). Check API key in .delphi-config.json.` };
562
+ }
563
+ if (response.status === 429) {
564
+ return await classifyRateLimitResponse(response);
565
+ }
566
+ if (response.status >= 500) {
567
+ return await classifyServerErrorResponse(response);
568
+ }
569
+ if (!response.ok) {
570
+ return { error: true, message: `API request failed (${response.status}). Provider response was not included.` };
571
+ }
572
+ return await readSuccessfulResponse(response);
573
+ }
574
+
575
+
576
+
577
+
578
+
579
+ /** The tool conversation, given the same arguments as the single-shot call. */
580
+ function withRepoTools(providerConfig, model, systemPrompt, userPrompt, options) {
581
+ const url = `${providerConfig.base_url.replace(/\/$/, '')}/chat/completions`;
582
+ return converseWithTools(providerConfig, model, systemPrompt, userPrompt, {
583
+ ...options, url, body: buildChatBody(model, systemPrompt, userPrompt),
584
+ });
585
+ }
586
+
795
587
  async function callModelAPI(providerConfig, model, systemPrompt, userPrompt, options = {}) {
796
588
  const url = `${providerConfig.base_url.replace(/\/$/, '')}/chat/completions`;
797
589
  const body = buildChatBody(model, systemPrompt, userPrompt);
@@ -815,23 +607,7 @@ async function callModelAPI(providerConfig, model, systemPrompt, userPrompt, opt
815
607
  });
816
608
  responseReceived = true;
817
609
 
818
- if (response.status === 401 || response.status === 403) {
819
- return { error: true, message: `Authentication failed (${response.status}). Check API key in .delphi-config.json.` };
820
- }
821
-
822
- if (response.status === 429) {
823
- return await classifyRateLimitResponse(response);
824
- }
825
-
826
- if (response.status >= 500) {
827
- return await classifyServerErrorResponse(response);
828
- }
829
-
830
- if (!response.ok) {
831
- return { error: true, message: `API request failed (${response.status}). Provider response was not included.` };
832
- }
833
-
834
- return await readSuccessfulResponse(response);
610
+ return await classifyHttpResponse(response);
835
611
  } catch (err) {
836
612
  if (err instanceof Error && err.name === 'AbortError') {
837
613
  return { error: true, retryable: true, message: `Request timed out (${timeoutMs}ms). Raise --timeout-ms or the provider's timeout_ms.` };
@@ -851,37 +627,8 @@ async function callModelAPI(providerConfig, model, systemPrompt, userPrompt, opt
851
627
  }
852
628
  }
853
629
 
854
- function isPlainObject(value) {
855
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
856
- const prototype = Object.getPrototypeOf(value);
857
- return prototype === Object.prototype || prototype === null;
858
- }
859
630
 
860
- function parseExpertVerdict(value) {
861
- if (!isPlainObject(value)) return { valid: false, message: 'Invalid expert verdict.' };
862
- const verdicts = ['APPROVED', 'REQUEST_CHANGES', 'REJECTED'];
863
- if (!verdicts.includes(value.verdict)) return { valid: false, message: 'Invalid expert verdict.' };
864
- if (!Number.isFinite(value.confidence) || value.confidence < 1 || value.confidence > 10) {
865
- return { valid: false, message: 'Invalid expert verdict.' };
866
- }
867
- for (const field of ['critical_issues', 'major_concerns', 'minor_concerns']) {
868
- if (!Array.isArray(value[field]) || !value[field].every(item => typeof item === 'string')) {
869
- return { valid: false, message: 'Invalid expert verdict.' };
870
- }
871
- }
872
- if (typeof value.summary !== 'string') return { valid: false, message: 'Invalid expert verdict.' };
873
- return {
874
- valid: true,
875
- verdict: {
876
- verdict: value.verdict,
877
- confidence: value.confidence,
878
- critical_issues: value.critical_issues,
879
- major_concerns: value.major_concerns,
880
- minor_concerns: value.minor_concerns,
881
- summary: value.summary,
882
- },
883
- };
884
- }
631
+ /** The verdicts an expert may return. */
885
632
 
886
633
  function buildReviewOutput(verdict, args, provenance) {
887
634
  const parsed = parseExpertVerdict(verdict);
@@ -906,74 +653,175 @@ function buildReviewOutput(verdict, args, provenance) {
906
653
  }
907
654
 
908
655
  // ── Retry logic ────────────────────────────────────────────────────────
656
+ /** The first retry waits this long; each subsequent one doubles it. */
657
+ const RETRY_BASE_DELAY_MS = 1000;
658
+
659
+ /** Wait `ms` without blocking the event loop. */
660
+ function sleep(ms) {
661
+ return new Promise((resolve) => setTimeout(resolve, ms));
662
+ }
663
+
664
+ /**
665
+ * Announce and take the back-off before retry number `attempt`.
666
+ *
667
+ * Exponential from a named base: 1 s, 2 s, 4 s. The wait is ANNOUNCED first, because a
668
+ * silent two-second pause reads as a hang, and the operator's next move (wait, or kill
669
+ * it) depends on knowing a retry is in progress.
670
+ *
671
+ * @param {number} attempt zero-based retry index
672
+ * @param {string} reason why the previous call is being retried
673
+ */
674
+ async function backOffBeforeRetry(attempt, reason) {
675
+ const delay = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);
676
+ console.error(`[delphi-review] Retryable error: ${reason}. Retrying in ${delay}ms...`);
677
+ await sleep(delay);
678
+ }
679
+
680
+ /**
681
+ * Call the model, retrying only the failures worth retrying.
682
+ *
683
+ * `retryable` is the PROVIDER's answer, not ours: a configuration error retried three
684
+ * times just wastes three timeouts, and the caller needs the first failure reported
685
+ * rather than the last one's symptoms.
686
+ */
909
687
  async function callWithRetry(providerConfig, model, systemPrompt, userPrompt, maxRetries = 2, timeoutMs = DEFAULT_TIMEOUT_MS) {
910
688
  let lastResult;
911
689
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
912
- const result = await callModelAPI(providerConfig, model, systemPrompt, userPrompt, { timeoutMs });
690
+ // The repository the reviewer may consult. Passed here rather than inside
691
+ // `callModelAPI` so that function keeps one shape: the tool conversation is a sibling
692
+ // entry point, and adding a branch to the single-shot path pushed its CCN over the
693
+ // ceiling the ratchet records.
694
+ const result = await withRepoTools(providerConfig, model, systemPrompt, userPrompt, {
695
+ timeoutMs,
696
+ repoRoot: process.cwd(),
697
+ });
913
698
 
914
699
  if (result.success) return result;
915
700
  if (!result.retryable) return result;
916
701
 
917
702
  lastResult = result;
918
- if (attempt < maxRetries) {
919
- const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
920
- console.error(`[delphi-review] Retryable error: ${result.message}. Retrying in ${delay}ms...`);
921
- await new Promise(r => setTimeout(r, delay));
922
- }
703
+ if (attempt < maxRetries) await backOffBeforeRetry(attempt, result.message);
923
704
  }
924
705
  return lastResult;
925
706
  }
926
707
 
927
- // ── Main execution ─────────────────────────────────────────────────────
928
- async function main() {
929
- checkNodeVersion();
930
-
931
- const args = parseArgs(process.argv.slice(2));
932
- const config = readConfig(args.config, args.profile);
708
+ /**
709
+ * Read a file if it exists, else return null. Optional context, so a read failure
710
+ * is not fatal -- but it must not throw either.
711
+ *
712
+ * @param {string|undefined} filePath
713
+ * @returns {string|null}
714
+ */
715
+ function readOptionalFile(filePath) {
716
+ if (!filePath) return null;
717
+ try {
718
+ return fs.readFileSync(filePath, 'utf8');
719
+ } catch {
720
+ // The caller asked for optional context; an unreadable file means there is
721
+ // none, not that the review should abort.
722
+ return null;
723
+ }
724
+ }
933
725
 
934
- // Validate the complete expert map before fallback or provider lookup.
726
+ /**
727
+ * Validate the expert map, then hand back the requested seat and its provider.
728
+ *
729
+ * Extracted from `main` (123 lines). The validation runs BEFORE the lookup on
730
+ * purpose: a duplicate-model config should be reported as that, not as "expert
731
+ * not found" because the seat it names happens to be the one that was shadowed.
732
+ *
733
+ * @param {object} config
734
+ * @param {string} expertName
735
+ * @returns {{expertConfig: object, provider: object}}
736
+ */
737
+ /**
738
+ * Validate the config and report its warnings, exiting on an invalid one.
739
+ *
740
+ * Warnings are printed even when the config is valid: they record decisions the operator
741
+ * should see (a raised ceiling that could not be honoured, a setting that was ignored),
742
+ * and swallowing them would make those decisions invisible.
743
+ */
744
+ function assertConfigValid(config) {
935
745
  const validation = validateDistinctModels(config.experts, config.providers, config.consensus);
936
746
  if (!validation.valid) {
937
747
  console.error(`[delphi-review] ERROR: ${validation.reason}`);
938
748
  process.exit(1);
939
749
  }
940
- if (validation.warning) {
941
- console.error(`[delphi-review] WARNING: ${validation.warning}`);
942
- }
750
+ if (validation.warning) console.error(`[delphi-review] WARNING: ${validation.warning}`);
943
751
  for (const warning of config.warnings) {
944
752
  console.error(`[delphi-review] WARNING: ${warning}`);
945
753
  }
754
+ }
946
755
 
947
- // Get expert config
948
- const expertConfig = config.experts[args.expert];
756
+ function resolveSeat(config, expertName) {
757
+ assertConfigValid(config);
758
+
759
+ const expertConfig = config.experts[expertName];
949
760
  if (!expertConfig) {
950
- console.error(`[delphi-review] ERROR: Expert "${args.expert}" not found in config.`);
761
+ console.error(`[delphi-review] ERROR: Expert "${expertName}" not found in config.`);
951
762
  process.exit(1);
952
763
  }
953
-
954
- // Get provider config
955
764
  const provider = config.providers[expertConfig.provider];
956
765
  if (!provider) {
957
766
  console.error(`[delphi-review] ERROR: Provider "${expertConfig.provider}" not found in config.`);
958
767
  process.exit(1);
959
768
  }
769
+ return { expertConfig, provider };
770
+ }
960
771
 
961
- // Resolve input
962
- const reviewContent = resolveInputContent(args);
963
-
964
- // Resolve other experts context
965
- let otherExpertsContent = null;
966
- if (args.otherExpertsFile && fs.existsSync(args.otherExpertsFile)) {
967
- otherExpertsContent = fs.readFileSync(args.otherExpertsFile, 'utf8');
772
+ /**
773
+ * Shape the JSON a failed seat reports.
774
+ *
775
+ * Pure: everything it needs is an argument. The `bytes` fields are attached only
776
+ * when classification produced them, because a null byte count reads as a real
777
+ * measurement of zero.
778
+ *
779
+ * @param {object} outcome
780
+ * @param {string} expertName
781
+ * @param {{bytes: number}} budget
782
+ * @param {object} seatCalibration
783
+ * @returns {object}
784
+ */
785
+ function buildErrorOutput(outcome, expertName, budget, seatCalibration) {
786
+ const classified = classifySeatFailure({
787
+ result: outcome,
788
+ promptBytes: budget.bytes,
789
+ calibration: seatCalibration.calibration,
790
+ });
791
+ const errorOutput = {
792
+ error: true,
793
+ error_type: classified.error_type,
794
+ expert_role: expertName,
795
+ message: classified.message,
796
+ retryable: classified.retryable || false,
797
+ };
798
+ if (classified.bytes !== undefined) {
799
+ errorOutput.bytes = classified.bytes;
800
+ errorOutput.calibrated_pass_bytes = classified.calibrated_pass_bytes;
968
801
  }
802
+ return errorOutput;
803
+ }
804
+
805
+ /**
806
+ * Build the prompts and refuse the call if they exceed the prompt budget.
807
+ *
808
+ * The refusal happens BEFORE the request, not after the gateway kills it, and it
809
+ * writes the same JSON stdout contract as an API failure: an orchestrator reading
810
+ * that stream has to be able to tell "we never asked" from "the model answered
811
+ * wrongly". `resolveSeatCalibration` prints its own warning, so it is not echoed
812
+ * here (#414 R1 MN-03).
813
+ *
814
+ * @param {object} args
815
+ * @param {object} expertConfig
816
+ * @returns {{systemPrompt: string, userPrompt: string, budget: object, seatCalibration: object}}
817
+ */
818
+ function preparePrompt(args, expertConfig) {
819
+ const reviewContent = resolveInputContent(args);
820
+ const otherExpertsContent = readOptionalFile(args.otherExpertsFile);
969
821
 
970
- // Build prompts
971
822
  const systemPrompt = buildSystemPrompt(args.expert, args.mode);
972
823
  const userPrompt = buildUserPrompt(reviewContent, otherExpertsContent, args.round);
973
824
 
974
- // Refuse before the request, not after the gateway kills it.
975
- // resolveSeatCalibration already printed its own warning, if any — do not
976
- // echo it a second time (#414 R1 MN-03).
977
825
  const seatCalibration = resolveSeatCalibration(expertConfig);
978
826
  const budget = checkPromptBudget({
979
827
  systemPrompt,
@@ -983,8 +831,6 @@ async function main() {
983
831
  if (!budget.ok) {
984
832
  const message = describePromptBudgetFailure({ ...budget, expert: args.expert });
985
833
  console.error(`[delphi-review] ERROR: ${message}`);
986
- // Same stdout contract as an API failure: an orchestrator parsing this stream
987
- // must be able to tell "we never asked" from "the model answered wrongly".
988
834
  console.log(JSON.stringify({
989
835
  error: true,
990
836
  error_type: 'prompt_budget_exceeded',
@@ -996,6 +842,19 @@ async function main() {
996
842
  }));
997
843
  process.exit(1);
998
844
  }
845
+ return { systemPrompt, userPrompt, budget, seatCalibration };
846
+ }
847
+
848
+ // ── Main execution ─────────────────────────────────────────────────────
849
+ async function main() {
850
+ checkNodeVersion();
851
+
852
+ const args = parseArgs(process.argv.slice(2));
853
+ const config = readConfig(args.config, args.profile);
854
+
855
+ const { expertConfig, provider } = resolveSeat(config, args.expert);
856
+
857
+ const { systemPrompt, userPrompt, budget, seatCalibration } = preparePrompt(args, expertConfig);
999
858
 
1000
859
  // Call API with retry; one schema-restating retry recovers malformed JSON
1001
860
  // without ever faking a verdict (#414 REQ-5).
@@ -1009,23 +868,7 @@ async function main() {
1009
868
  });
1010
869
 
1011
870
  if (outcome.error) {
1012
- const classified = classifySeatFailure({
1013
- result: outcome,
1014
- promptBytes: budget.bytes,
1015
- calibration: seatCalibration.calibration,
1016
- });
1017
- const errorOutput = {
1018
- error: true,
1019
- error_type: classified.error_type,
1020
- expert_role: args.expert,
1021
- message: classified.message,
1022
- retryable: classified.retryable || false,
1023
- };
1024
- if (classified.bytes !== undefined) {
1025
- errorOutput.bytes = classified.bytes;
1026
- errorOutput.calibrated_pass_bytes = classified.calibrated_pass_bytes;
1027
- }
1028
- console.log(JSON.stringify(errorOutput));
871
+ console.log(JSON.stringify(buildErrorOutput(outcome, args.expert, budget, seatCalibration)));
1029
872
  process.exit(1);
1030
873
  }
1031
874
 
@@ -1054,9 +897,12 @@ if (require.main !== module) {
1054
897
  module.exports = {
1055
898
  parseArgs,
1056
899
  readConfig,
900
+ expandEnvPlaceholder,
901
+ clampConsensusSetting,
1057
902
  globalConfigPath,
1058
903
  validateDistinctModels,
1059
904
  extractJsonFromResponse,
905
+ classifyHttpResponse,
1060
906
  buildSystemPrompt,
1061
907
  buildUserPrompt,
1062
908
  resolveInputContent,
@@ -1083,24 +929,3 @@ if (require.main !== module) {
1083
929
  });
1084
930
  }
1085
931
 
1086
- /**
1087
- * Machine-wide `.delphi-config.json` path: `$XDG_CONFIG_HOME/xp-gate/`, or
1088
- * `~/.config/xp-gate/` when the variable is unset.
1089
- *
1090
- * Exported so the path-parity test can hold this loader, the Gate MW validator
1091
- * and the DSH plugin to one definition instead of three restatements.
1092
- *
1093
- * Deliberately declared at the END of the file. Function declarations hoist, so
1094
- * readConfig above can call it, but placing it here keeps every line before the
1095
- * old EOF byte-identical — which matters because `.ccn-baseline.json` anchors
1096
- * anonymous functions by line number (`file::(anonymous)@657`). Adding these
1097
- * lines near the top shifted that anchor to 676 and Gate 3 then read a
1098
- * pre-existing CCN=24 function as a brand-new violation.
1099
- *
1100
- * @param {NodeJS.ProcessEnv} env
1101
- * @returns {string}
1102
- */
1103
- function globalConfigPath(env) {
1104
- const configHome = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
1105
- return path.join(configHome, 'xp-gate', '.delphi-config.json');
1106
- }