@boyingliu01/xp-gate 0.38.126 → 0.39.1

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 (291) 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/sprint-flow/AGENTS.md +1 -1
  65. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  66. package/plugins/dsh/package.json +1 -1
  67. package/plugins/dsh/scripts/prepack.cjs +43 -18
  68. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  69. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  70. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  71. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  72. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  73. package/plugins/opencode/index.ts +337 -123
  74. package/plugins/opencode/package.json +1 -1
  75. package/plugins/opencode/scripts/prepack.cjs +41 -16
  76. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  79. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  80. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  81. package/plugins/qoder/plugin.json +1 -1
  82. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  83. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/shared/README.md +3 -0
  87. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  88. package/principles/adapters/control-nesting.ts +481 -168
  89. package/principles/adapters/cpp.ts +61 -22
  90. package/principles/adapters/csharp.ts +183 -66
  91. package/principles/adapters/dart.ts +11 -1
  92. package/principles/adapters/duplication.ts +49 -16
  93. package/principles/adapters/import-clause.ts +62 -15
  94. package/principles/adapters/java.ts +199 -70
  95. package/principles/adapters/line-comment.ts +18 -0
  96. package/principles/adapters/member-scan.ts +50 -8
  97. package/principles/adapters/php.ts +232 -103
  98. package/principles/adapters/python.ts +25 -18
  99. package/principles/adapters/quote-state.ts +21 -8
  100. package/principles/adapters/typescript-mask.ts +276 -0
  101. package/principles/adapters/typescript.ts +206 -200
  102. package/principles/analyzer.ts +16 -6
  103. package/principles/baseline-prune.ts +18 -8
  104. package/principles/baseline.ts +28 -11
  105. package/principles/boy-scout-usage.ts +26 -0
  106. package/principles/boy-scout.ts +261 -180
  107. package/principles/config.ts +183 -57
  108. package/principles/direct-execution.ts +24 -12
  109. package/principles/lint-baseline.ts +235 -122
  110. package/principles/rules/arch/dependency.ts +34 -25
  111. package/principles/rules/arch/shared.ts +24 -20
  112. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  113. package/principles/rules/clean-code/god-class.ts +67 -41
  114. package/principles/rules/clean-code/large-file.ts +30 -23
  115. package/principles/rules/clean-code/long-function.ts +51 -37
  116. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  117. package/principles/rules/clean-code/many-exports.ts +46 -29
  118. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  119. package/principles/rules/clean-code/too-many-params.ts +41 -22
  120. package/principles/rules/function-source.ts +62 -0
  121. package/principles/rules/solid/dip.ts +10 -6
  122. package/principles/rules/solid/isp.ts +64 -24
  123. package/principles/rules/solid/lsp.ts +66 -18
  124. package/principles/rules/solid/ocp.ts +29 -13
  125. package/principles/rules/solid/srp.ts +34 -18
  126. package/principles/warnings-count.ts +43 -0
  127. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  128. package/scripts/delphi-config-read.cjs +245 -0
  129. package/scripts/delphi-external-review.cjs +410 -585
  130. package/scripts/delphi-json-extract.cjs +108 -0
  131. package/scripts/delphi-model-validation.cjs +297 -0
  132. package/scripts/delphi-prompts.cjs +55 -0
  133. package/scripts/delphi-repo-tools.cjs +273 -0
  134. package/scripts/delphi-seat-calibration.cjs +204 -0
  135. package/scripts/run-bats-ci.cjs +240 -97
  136. package/scripts/sync-package-content.js +18 -2
  137. package/skills/delphi-review/.delphi-config.json.example +6 -11
  138. package/skills/delphi-review/AGENTS.md +1 -1
  139. package/skills/sprint-flow/AGENTS.md +1 -1
  140. package/skills/test-specification-alignment/AGENTS.md +1 -1
  141. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  142. package/lib/__tests__/arch-config-template.test.js +0 -190
  143. package/lib/__tests__/arch.test.js +0 -430
  144. package/lib/__tests__/assertion-debt.test.js +0 -99
  145. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  146. package/lib/__tests__/audit-log.test.ts +0 -107
  147. package/lib/__tests__/audit-skip-reasons.test.ts +0 -143
  148. package/lib/__tests__/baseline-completeness.test.js +0 -264
  149. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  150. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  151. package/lib/__tests__/baseline.test.js +0 -212
  152. package/lib/__tests__/bootstrap.test.js +0 -60
  153. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  154. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  155. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  156. package/lib/__tests__/check-changed-brief.test.js +0 -63
  157. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  158. package/lib/__tests__/check-single-file.test.js +0 -114
  159. package/lib/__tests__/check-tools-list.test.js +0 -155
  160. package/lib/__tests__/check-version.test.js +0 -463
  161. package/lib/__tests__/coverage-scope.test.js +0 -140
  162. package/lib/__tests__/coverage-threshold.test.js +0 -80
  163. package/lib/__tests__/crap-cli.test.js +0 -87
  164. package/lib/__tests__/crap.test.js +0 -494
  165. package/lib/__tests__/debt-classify.test.js +0 -78
  166. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  167. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  168. package/lib/__tests__/delphi-channel.test.js +0 -109
  169. package/lib/__tests__/delphi-setup.test.js +0 -203
  170. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  171. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  172. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  173. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  174. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  175. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  176. package/lib/__tests__/deploy-manifest.test.js +0 -97
  177. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  178. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  179. package/lib/__tests__/detect-deps.test.js +0 -655
  180. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  181. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  182. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  183. package/lib/__tests__/doctor-brief.test.js +0 -59
  184. package/lib/__tests__/doctor-delphi.test.js +0 -628
  185. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  186. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  187. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  188. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  189. package/lib/__tests__/doctor-helpers.test.js +0 -139
  190. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  191. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  192. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  193. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  194. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  195. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  196. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  197. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  198. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  199. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  200. package/lib/__tests__/doctor-tool-delegation.test.js +0 -156
  201. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  202. package/lib/__tests__/doctor.test.js +0 -1320
  203. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  204. package/lib/__tests__/flaky.test.js +0 -128
  205. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  206. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  207. package/lib/__tests__/gate-audit.test.ts +0 -440
  208. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  209. package/lib/__tests__/gate-coverage.test.js +0 -204
  210. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  211. package/lib/__tests__/gate-numbering.test.js +0 -79
  212. package/lib/__tests__/gate-rules.test.js +0 -58
  213. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  214. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  215. package/lib/__tests__/gate-runner.test.js +0 -371
  216. package/lib/__tests__/gate2-verdict.test.js +0 -183
  217. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  218. package/lib/__tests__/hook-health-path.test.js +0 -109
  219. package/lib/__tests__/hook-health.test.js +0 -85
  220. package/lib/__tests__/init-gitignore.test.js +0 -204
  221. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  222. package/lib/__tests__/init.test.js +0 -530
  223. package/lib/__tests__/install-cmd.test.js +0 -6
  224. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  225. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  226. package/lib/__tests__/install-skill.test.js +0 -416
  227. package/lib/__tests__/install-tools-repair.test.js +0 -263
  228. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  229. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  230. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  231. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  232. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  233. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  234. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  235. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  236. package/lib/__tests__/language-capability.test.js +0 -318
  237. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  238. package/lib/__tests__/language-tools-detect.test.js +0 -301
  239. package/lib/__tests__/migrate.test.js +0 -232
  240. package/lib/__tests__/mirror-manifest.test.js +0 -64
  241. package/lib/__tests__/mirror-sync.test.js +0 -803
  242. package/lib/__tests__/next-sprint.test.js +0 -231
  243. package/lib/__tests__/npm-package.test.js +0 -140
  244. package/lib/__tests__/phase-transition.test.js +0 -1136
  245. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  246. package/lib/__tests__/principles-directory.test.js +0 -87
  247. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  248. package/lib/__tests__/retro-gate-m.test.js +0 -144
  249. package/lib/__tests__/retro.test.js +0 -131
  250. package/lib/__tests__/rework.test.js +0 -127
  251. package/lib/__tests__/rollback.test.js +0 -183
  252. package/lib/__tests__/runtime-journal.test.js +0 -164
  253. package/lib/__tests__/sastd-client.test.js +0 -514
  254. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  255. package/lib/__tests__/shared-paths.test.js +0 -130
  256. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  257. package/lib/__tests__/shared-utils.test.js +0 -180
  258. package/lib/__tests__/skill-flags.test.js +0 -48
  259. package/lib/__tests__/slo.test.js +0 -89
  260. package/lib/__tests__/sprint-audit.test.js +0 -207
  261. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  262. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  263. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  264. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  265. package/lib/__tests__/sprint-status.test.js +0 -193
  266. package/lib/__tests__/sprint-status.test.ts +0 -213
  267. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  268. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  269. package/lib/__tests__/test-alignment.test.ts +0 -853
  270. package/lib/__tests__/tool-audit-collect.test.js +0 -184
  271. package/lib/__tests__/tool-audit-fixtures.js +0 -87
  272. package/lib/__tests__/tool-audit-latest.test.js +0 -84
  273. package/lib/__tests__/tool-audit.test.js +0 -428
  274. package/lib/__tests__/tsconfig.json +0 -8
  275. package/lib/__tests__/tsx-resolution.test.js +0 -89
  276. package/lib/__tests__/ui-detector.test.ts +0 -459
  277. package/lib/__tests__/ui-review.test.ts +0 -132
  278. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  279. package/lib/__tests__/uninstall-skill.test.js +0 -189
  280. package/lib/__tests__/uninstall.test.js +0 -717
  281. package/lib/__tests__/update-hooks.test.js +0 -737
  282. package/lib/__tests__/update-skill-flags.test.js +0 -78
  283. package/lib/__tests__/update-skill.test.js +0 -644
  284. package/lib/__tests__/upgrade-exec.test.js +0 -273
  285. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  286. package/lib/__tests__/upgrade.test.js +0 -78
  287. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  288. package/lib/check-alignment-runner.cjs +0 -97
  289. package/lib/coverage-total.sh +0 -92
  290. package/lib/layer-baseline.cjs +0 -94
  291. package/lib/mattpocock-license-verdict.json +0 -7
@@ -50,10 +50,15 @@ function detectBranch(cwd) {
50
50
  function generateSprintId() {
51
51
  const now = new Date();
52
52
  const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
53
- const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
53
+ const seq = String(Math.floor(Math.random() * MAX_SPRINT_SEQUENCE) + 1).padStart(2, '0');
54
54
  return `sprint-${dateStr}-${seq}`;
55
55
  }
56
56
 
57
+ /** Sprint ids are `sprint-YYYYMMDD-NN`; the sequence is 1-99. */
58
+ const MAX_SPRINT_SEQUENCE = 99;
59
+ /** `YYYY-MM-DDTHH:MM:SS` is 19 characters once the separators are normalised. */
60
+ const TIMESTAMP_SECONDS_LENGTH = 19;
61
+
57
62
  /**
58
63
  * Backup existing sprint state to .sprint-history/.
59
64
  * @param {string} projectRoot - Project root directory
@@ -61,12 +66,18 @@ function generateSprintId() {
61
66
  */
62
67
  function backupSprintState(projectRoot, state) {
63
68
  const historyDir = path.join(projectRoot, '.sprint-history');
64
- if (!fs.existsSync(historyDir)) {
65
- fs.mkdirSync(historyDir, { recursive: true });
66
- }
67
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
69
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, TIMESTAMP_SECONDS_LENGTH);
68
70
  const backupFile = path.join(historyDir, `sprint-state-${state.id || 'unknown'}-${timestamp}.json`);
69
- fs.writeFileSync(backupFile, JSON.stringify(state, null, 2), 'utf8');
71
+ try {
72
+ if (!fs.existsSync(historyDir)) {
73
+ fs.mkdirSync(historyDir, { recursive: true });
74
+ }
75
+ fs.writeFileSync(backupFile, JSON.stringify(state, null, 2), 'utf8');
76
+ } catch (err) {
77
+ // A backup that silently fails is worse than none: `--force` then overwrites
78
+ // state the operator believed was preserved.
79
+ throw new Error(`cannot back up sprint state to ${backupFile}: ${err.message}`);
80
+ }
70
81
  return backupFile;
71
82
  }
72
83
 
@@ -75,134 +86,269 @@ function backupSprintState(projectRoot, state) {
75
86
  * @param {string[]} args - CLI arguments
76
87
  * @returns {Promise<number>} Exit code
77
88
  */
78
- async function handleSprintInit(args = []) {
79
- if (args.includes('--help')) {
80
- console.log('Usage: xp-gate sprint-init "<task_description>" [options]');
81
- console.log('');
82
- console.log('Arguments:');
83
- console.log(' task_description Sprint task description (required)');
84
- console.log('');
85
- console.log('Options:');
86
- console.log(' --issues <list> Comma-separated issue numbers (e.g. "#123,#456")');
87
- console.log(' --force Override existing active sprint (backs up old state)');
88
- console.log(' --dry-run Pre-check conflicts without writing');
89
- console.log(' --dir <path> Project directory (default: cwd)');
90
- console.log('');
91
- console.log('Examples:');
92
- console.log(' xp-gate sprint-init "Implement user auth"');
93
- console.log(' xp-gate sprint-init "Fix #366" --issues "#366" --force');
89
+ /**
90
+ * Parse `sprint-init` arguments.
91
+ *
92
+ * Extracted from `handleSprintInit` (CCN 31), and it fixes a latent defect while
93
+ * doing so. The task description used to be "the first argument that is not a
94
+ * flag and is not equal to the --dir/--issues VALUES". That comparison is by
95
+ * value, so a task describing the very directory it targets --
96
+ *
97
+ * xp-gate sprint-init "./src" --dir ./src
98
+ *
99
+ * -- found no task at all and failed with "Missing task_description". The flags
100
+ * are now consumed positionally: a flag takes the next token as its value, and
101
+ * the first token NOT consumed that way is the description.
102
+ *
103
+ * @param {string[]} args
104
+ * @returns {{forceFlag?: boolean, dryRunFlag?: boolean, projectDir?: string,
105
+ * issues?: string, taskDescription?: string, error?: string}}
106
+ */
107
+ /**
108
+ * The first argument that is neither a flag nor a value consumed by one.
109
+ *
110
+ * A value is skipped via `consumed` rather than by inspecting its shape: `--issues
111
+ * "#1,#2"` looks nothing like a flag, and treating it as the task description would
112
+ * silently swap the two.
113
+ *
114
+ * @param {string[]} args
115
+ * @param {Set<number>} consumed indices already claimed by a flag
116
+ * @returns {string|undefined}
117
+ */
118
+ function firstPositional(args, consumed) {
119
+ const index = args.findIndex((arg, i) => !consumed.has(i) && !arg.startsWith('--'));
120
+ return index >= 0 ? args[index] : undefined;
121
+ }
122
+
123
+ /**
124
+ * The exit code for a request that never reaches sprint creation: `--help`, or a
125
+ * missing task description.
126
+ *
127
+ * @param {object} parsed
128
+ * @returns {number|null} null when the caller should continue
129
+ */
130
+ function earlyExitFor(parsed) {
131
+ if (parsed.helpFlag) {
132
+ printSprintInitUsage();
94
133
  return 0;
95
134
  }
135
+ if (parsed.error) {
136
+ console.error(`Error: ${parsed.error}`);
137
+ return 1;
138
+ }
139
+ return null;
140
+ }
96
141
 
97
- // Parse arguments
142
+ function parseSprintInitArgs(args) {
143
+ const helpFlag = args.includes('--help');
98
144
  const forceFlag = args.includes('--force');
99
145
  const dryRunFlag = args.includes('--dry-run');
100
- const dirIdx = args.indexOf('--dir');
101
- const projectDir = dirIdx >= 0 ? args[dirIdx + 1] : process.cwd();
102
- const issuesIdx = args.indexOf('--issues');
103
- const issues = issuesIdx >= 0 ? args[issuesIdx + 1] : '';
104
146
 
105
- // First non-flag argument is task_description
106
- const taskDescription = args.find(a => !a.startsWith('--') && a !== projectDir && a !== issues);
147
+ const consumed = new Set();
148
+ const takeValue = (flag) => {
149
+ const i = args.indexOf(flag);
150
+ if (i < 0 || i + 1 >= args.length) return null;
151
+ consumed.add(i + 1);
152
+ return args[i + 1];
153
+ };
154
+
155
+ const dirValue = takeValue('--dir');
156
+ const issuesValue = takeValue('--issues');
157
+ const projectDir = dirValue === null ? process.cwd() : dirValue;
158
+ const issues = issuesValue === null ? '' : issuesValue;
159
+
160
+ const taskDescription = firstPositional(args, consumed);
107
161
  if (!taskDescription) {
108
- console.error('Error: Missing task_description. Usage: xp-gate sprint-init "<task_description>"');
109
- return 1;
162
+ return { helpFlag, error: 'Missing task_description. Usage: xp-gate sprint-init "<task_description>"' };
110
163
  }
164
+ return { helpFlag, forceFlag, dryRunFlag, projectDir, issues, taskDescription };
165
+ }
111
166
 
112
- const manager = new SprintStateManager(projectDir);
113
- const branch = detectBranch(projectDir);
167
+ /**
168
+ * Deal with a sprint that is already on disk: idempotent call, conflict, or
169
+ * forced override.
170
+ *
171
+ * The three outcomes are one decision because they share a single precondition
172
+ * (there IS existing state) and differ only in what the caller asked for. Split
173
+ * out of `handleSprintInit` (162 lines), which read as a sequence of unrelated
174
+ * blocks.
175
+ *
176
+ * The idempotent case is deliberately narrow: same task AND same branch AND not
177
+ * detached. A detached HEAD has no branch identity to compare, so treating it as
178
+ * a match would silently accept a second sprint on the same task.
179
+ *
180
+ * @param {object} manager SprintStateManager
181
+ * @param {string} projectDir
182
+ * @param {{taskDescription: string, branch: string, forceFlag: boolean, dryRunFlag: boolean}} opts
183
+ * @returns {{exitCode?: number, existingState: object|null}}
184
+ */
185
+ function handleExistingSprint(manager, projectDir, opts) {
186
+ const existingState = readExistingState(manager);
187
+ if (!existingState) return { existingState: null };
188
+
189
+ const same = identityOf(existingState, opts);
190
+ if (isIdempotentCall(same, opts.branch)) return reportIdempotent(existingState);
114
191
 
115
- // Check existing sprint state
116
- let existingState = null;
192
+ if (!opts.forceFlag) return refuseOverride(existingState, same, opts.dryRunFlag);
193
+
194
+ return forceOverride(projectDir, existingState);
195
+ }
196
+
197
+ /**
198
+ * Read the current state, treating a corrupted file as absent.
199
+ *
200
+ * Overwriting a corrupt state is the only way out of it, so "unreadable" must mean
201
+ * the same thing here as "not there".
202
+ *
203
+ * @param {object} manager SprintStateManager
204
+ * @returns {object|null}
205
+ */
206
+ function readExistingState(manager) {
117
207
  try {
118
- existingState = manager.read();
208
+ return manager.read();
119
209
  } catch {
120
- // Corrupted state — treat as no state (will be overwritten)
121
- existingState = null;
210
+ return null;
122
211
  }
212
+ }
123
213
 
124
- if (existingState) {
125
- // Idempotent check: same task_description + branch → output dashboard, exit 0
126
- const normalizedExisting = (existingState.task_description || '').trim();
127
- const normalizedNew = taskDescription.trim();
128
- const existingBranch = existingState.isolation?.branch || '';
129
-
130
- if (normalizedExisting === normalizedNew && existingBranch === branch && branch !== 'detached') {
131
- console.log('ℹ️ Sprint already initialized (idempotent call). Current state:');
132
- console.log('');
133
- console.log(renderDashboard(existingState));
134
- return 0;
135
- }
214
+ /**
215
+ * The normalised facts that decide whether this is the same sprint.
216
+ *
217
+ * @param {object} state
218
+ * @param {{taskDescription: string}} opts
219
+ * @returns {{task: string, branch: string}}
220
+ */
221
+ function identityOf(state, opts) {
222
+ return {
223
+ task: (state.task_description || '').trim(),
224
+ branch: state.isolation?.branch || '',
225
+ newTask: opts.taskDescription.trim(),
226
+ };
227
+ }
136
228
 
137
- // Conflict: existing active sprint
138
- if (!forceFlag) {
139
- if (dryRunFlag) {
140
- console.log(JSON.stringify({
141
- decision: 'deny',
142
- reason: `Active sprint "${existingState.id}" exists (task: "${normalizedExisting}")`,
143
- hint: 'Use --force to override (backs up old state)',
144
- }));
145
- return 0;
146
- }
147
- console.error(`Error: Active sprint "${existingState.id}" already exists.`);
148
- console.error(` Task: "${normalizedExisting}"`);
149
- console.error(` Branch: ${existingBranch}`);
150
- console.error(' Use --force to override (backs up old state to .sprint-history/)');
151
- return 1;
152
- }
229
+ /**
230
+ * Whether the call is a repeat of the sprint already on disk.
231
+ *
232
+ * `detached` is excluded on purpose: a detached HEAD has no branch identity to
233
+ * compare, so treating it as a match would silently accept a second sprint on the
234
+ * same task.
235
+ *
236
+ * @param {{task: string, branch: string, newTask: string}} same
237
+ * @param {string} branch
238
+ * @returns {boolean}
239
+ */
240
+ function isIdempotentCall(same, branch) {
241
+ return same.task === same.newTask && same.branch === branch && branch !== 'detached';
242
+ }
153
243
 
154
- // --force: backup and override
155
- const backupPath = backupSprintState(projectDir, existingState);
156
- console.log(`📦 Backed up existing sprint to: ${backupPath}`);
157
- }
244
+ /** Report that the sprint is already initialised and show it. */
245
+ function reportIdempotent(existingState) {
246
+ console.log('ℹ️ Sprint already initialized (idempotent call). Current state:');
247
+ console.log('');
248
+ console.log(renderDashboard(existingState));
249
+ return { exitCode: 0, existingState };
250
+ }
158
251
 
252
+ /**
253
+ * Refuse to replace an active sprint without `--force`.
254
+ *
255
+ * A dry run reports the same decision as JSON instead of failing, so a caller can
256
+ * check for a conflict without handling a non-zero exit.
257
+ */
258
+ function refuseOverride(existingState, same, dryRunFlag) {
159
259
  if (dryRunFlag) {
160
260
  console.log(JSON.stringify({
161
- decision: 'allow',
162
- reason: existingState ? 'Would override existing sprint (--force)' : 'No existing sprint',
163
- branch,
164
- task_description: taskDescription.trim(),
261
+ decision: 'deny',
262
+ reason: `Active sprint "${existingState.id}" exists (task: "${same.task}")`,
263
+ hint: 'Use --force to override (backs up old state)',
165
264
  }));
166
- return 0;
265
+ return { exitCode: 0, existingState };
167
266
  }
267
+ console.error(`Error: Active sprint "${existingState.id}" already exists.`);
268
+ console.error(` Task: "${same.task}"`);
269
+ console.error(` Branch: ${same.branch}`);
270
+ console.error(' Use --force to override (backs up old state to .sprint-history/)');
271
+ return { exitCode: 1, existingState };
272
+ }
273
+
274
+ /** Replace the existing sprint, after taking a backup. */
275
+ function forceOverride(projectDir, existingState) {
276
+ const backupPath = backupSprintState(projectDir, existingState);
277
+ console.log(`📦 Backed up existing sprint to: ${backupPath}`);
278
+ return { existingState };
279
+ }
168
280
 
169
- // Read previous sprint retro data for auto-population (Phase 6 / D7)
281
+ /**
282
+ * The most recent sprint's retro data, or null.
283
+ *
284
+ * Best effort by design: retro data only pre-populates fields, so a missing or
285
+ * unparseable file must not stop a sprint from starting. Only the newest
286
+ * `.sprint-history` entry is consulted -- carrying forward a retro from three
287
+ * sprints ago would be worse than carrying none.
288
+ *
289
+ * @param {string} projectDir
290
+ * @returns {object|null}
291
+ */
292
+ /** Whether a history entry is a RETRO rather than a state snapshot. */
293
+ function isRetroFile(name) {
294
+ // `sprint-state-*.json` is a state snapshot, not a retro; only a retro file carries
295
+ // the fields this feeds.
296
+ return !name.endsWith('.json') || name.includes('retro');
297
+ }
298
+
299
+ /** The newest `sprint-*` entry in the history directory, or null. */
300
+ function newestHistoryEntry(historyDir) {
301
+ const entries = fs.readdirSync(historyDir).filter((f) => f.startsWith('sprint-')).sort().reverse();
302
+ return entries[0] || null;
303
+ }
304
+
305
+ function readPreviousRetro(projectDir) {
170
306
  const historyDir = path.join(projectDir, '.sprint-history');
171
- let previousRetro = null;
172
- if (fs.existsSync(historyDir)) {
173
- const entries = fs.readdirSync(historyDir).filter(f => f.startsWith('sprint-')).sort().reverse();
174
- for (const entry of entries) {
175
- if (entry.endsWith('.json') && !entry.includes('retro')) continue;
176
- const retroPath = path.join(historyDir, entry);
177
- if (fs.existsSync(retroPath)) {
178
- try {
179
- const raw = fs.readFileSync(retroPath, 'utf8');
180
- previousRetro = JSON.parse(raw);
181
- break;
182
- } catch {
183
- // Skip unparseable files
184
- }
185
- }
186
- break; // Only check the most recent sprint
187
- }
307
+ if (!fs.existsSync(historyDir)) return null;
308
+
309
+ const newest = newestHistoryEntry(historyDir);
310
+ if (!newest || !isRetroFile(newest)) return null;
311
+
312
+ try {
313
+ return JSON.parse(fs.readFileSync(path.join(historyDir, newest), 'utf8'));
314
+ } catch {
315
+ // An unparseable retro carries nothing worth failing a sprint start over.
316
+ return null;
188
317
  }
318
+ }
189
319
 
190
- // Create new sprint state
320
+ /**
321
+ * The initial state for a new sprint.
322
+ *
323
+ * `evidence_schema_version: 2` is what turns Gate 5c's warnings into BLOCKs for
324
+ * this sprint: a sprint created under the new rules is held to them. That is why
325
+ * it is set here rather than inherited -- an old sprint keeps its leniency, a new
326
+ * one gets none.
327
+ *
328
+ * Phase 6 / D7: the previous sprint's retro values are carried into `metrics`
329
+ * so the new sprint starts with last sprint's rework rate and duration visible.
330
+ *
331
+ * @param {{projectDir: string, branch: string, taskDescription: string, issues: string, previousRetro: object|null}} opts
332
+ * @returns {{sprintId: string, newState: object}}
333
+ */
334
+ function buildSprintState(opts) {
335
+ const { projectDir, branch, taskDescription, issues, previousRetro } = opts;
191
336
  const sprintId = generateSprintId();
337
+ const startedAt = new Date().toISOString();
192
338
  const newState = {
193
339
  _schema_version: 1,
194
- evidence_schema_version: 2, // Phase 5: new sprints default to full BLOCK enforcement
340
+ evidence_schema_version: 2,
195
341
  id: sprintId,
196
342
  task_description: taskDescription.trim(),
197
343
  phase: 1,
198
344
  status: 'in_progress',
199
- started_at: new Date().toISOString(),
345
+ started_at: startedAt,
200
346
  phase_history: [
201
347
  {
202
348
  phase: 1,
203
349
  name: 'PREP',
204
350
  status: 'in_progress',
205
- started_at: new Date().toISOString(),
351
+ started_at: startedAt,
206
352
  },
207
353
  ],
208
354
  isolation: {
@@ -213,26 +359,136 @@ async function handleSprintInit(args = []) {
213
359
  metrics: {},
214
360
  };
215
361
 
216
- // Phase 6 / D7: Auto-populate from previous sprint retro data
217
- if (previousRetro) {
218
- if (previousRetro.rework_rate != null) {
219
- newState.metrics.previous_rework_rate = previousRetro.rework_rate;
220
- }
221
- if (previousRetro.evidence_skips != null) {
222
- newState.metrics.previous_evidence_skips = previousRetro.evidence_skips;
223
- }
224
- if (previousRetro.duration_seconds != null) {
225
- newState.metrics.previous_duration_seconds = previousRetro.duration_seconds;
226
- }
227
- if (Object.keys(newState.metrics).length > 0) {
228
- console.log('📊 Auto-populated from previous sprint retro data:');
229
- for (const [key, value] of Object.entries(newState.metrics)) {
230
- console.log(` ${key}: ${value}`);
231
- }
232
- }
362
+ applyPreviousRetro(newState, previousRetro);
363
+ return { sprintId, newState };
364
+ }
365
+
366
+ /**
367
+ * Copy the previous sprint's headline metrics into the new sprint.
368
+ *
369
+ * Only the three values that describe how the last sprint WENT -- not its task,
370
+ * branch or phase. Each is copied only when present, so a retro that predates a
371
+ * field does not write a null.
372
+ *
373
+ * @param {object} newState mutated in place
374
+ * @param {object|null} retro
375
+ */
376
+ /** The retro fields carried into the next sprint's metrics, and their source names. */
377
+ const CARRIED_RETRO_FIELDS = {
378
+ previous_rework_rate: 'rework_rate',
379
+ previous_evidence_skips: 'evidence_skips',
380
+ previous_duration_seconds: 'duration_seconds',
381
+ };
382
+
383
+ /**
384
+ * Copy the previous sprint's headline metrics into the new one.
385
+ *
386
+ * Only values that are PRESENT are copied: a retro written before a field existed
387
+ * must not write `null` into the new sprint's metrics, because a null reads as
388
+ * "measured at nothing".
389
+ *
390
+ * @param {object} newState mutated in place
391
+ * @param {object|null} retro
392
+ */
393
+ function applyPreviousRetro(newState, retro) {
394
+ if (!retro) return;
395
+ for (const [target, source] of Object.entries(CARRIED_RETRO_FIELDS)) {
396
+ if (retro[source] != null) newState.metrics[target] = retro[source];
233
397
  }
398
+ announceCarriedMetrics(newState.metrics);
399
+ }
400
+
401
+ /**
402
+ * Print the metrics just carried forward, if any.
403
+ *
404
+ * @param {object} metrics
405
+ */
406
+ function announceCarriedMetrics(metrics) {
407
+ const entries = Object.entries(metrics);
408
+ if (entries.length === 0) return;
409
+ console.log('📊 Auto-populated from previous sprint retro data:');
410
+ for (const [key, value] of entries) console.log(` ${key}: ${value}`);
411
+ }
412
+
413
+ /** Print the sprint-init usage text. */
414
+ function printSprintInitUsage() {
415
+ console.log('Usage: xp-gate sprint-init "<task_description>" [options]');
416
+ console.log('');
417
+ console.log('Arguments:');
418
+ console.log(' task_description Sprint task description (required)');
419
+ console.log('');
420
+ console.log('Options:');
421
+ console.log(' --issues <list> Comma-separated issue numbers (e.g. "#123,#456")');
422
+ console.log(' --force Override existing active sprint (backs up old state)');
423
+ console.log(' --dry-run Pre-check conflicts without writing');
424
+ console.log(' --dir <path> Project directory (default: cwd)');
425
+ console.log('');
426
+ console.log('Examples:');
427
+ console.log(' xp-gate sprint-init "Implement user auth"');
428
+ console.log(' xp-gate sprint-init "Fix #366" --issues "#366" --force');
429
+ return 0;
430
+ }
431
+
432
+ async function handleSprintInit(args = []) {
433
+ const parsed = parseSprintInitArgs(args);
434
+ const early = earlyExitFor(parsed);
435
+ if (early !== null) return early;
436
+
437
+ const { forceFlag, dryRunFlag, projectDir, issues, taskDescription } = parsed;
438
+
439
+ const manager = new SprintStateManager(projectDir);
440
+ const branch = detectBranch(projectDir);
441
+
442
+ const existing = handleExistingSprint(manager, projectDir, {
443
+ taskDescription, branch, forceFlag, dryRunFlag,
444
+ });
445
+ // An exitCode means the existing-sprint handler already decided the outcome.
446
+ if (existing.exitCode !== undefined) return existing.exitCode;
447
+
448
+ if (dryRunFlag) {
449
+ reportDryRunAllow(existing.existingState, branch, taskDescription);
450
+ return 0;
451
+ }
452
+
453
+ createAndAnnounce(manager, { projectDir, branch, taskDescription, issues });
454
+ return 0;
455
+ }
456
+
457
+ /**
458
+ * A dry run's "would proceed" answer, as JSON.
459
+ *
460
+ * It says WHY it would proceed -- overriding an existing sprint is a different
461
+ * situation from starting a fresh one, and a caller checking the answer needs that.
462
+ *
463
+ * @param {object|null} existingState
464
+ * @param {string} branch
465
+ * @param {string} taskDescription
466
+ */
467
+ function reportDryRunAllow(existingState, branch, taskDescription) {
468
+ console.log(JSON.stringify({
469
+ decision: 'allow',
470
+ reason: existingState ? 'Would override existing sprint (--force)' : 'No existing sprint',
471
+ branch,
472
+ task_description: taskDescription.trim(),
473
+ }));
474
+ }
475
+
476
+ /**
477
+ * Build the state, write it, and show it.
478
+ *
479
+ * The dashboard is printed from the object that was WRITTEN, not from a re-read:
480
+ * re-reading would show what the filesystem kept, which is a different claim from
481
+ * what this command decided.
482
+ *
483
+ * @param {object} manager SprintStateManager
484
+ * @param {{projectDir: string, branch: string, taskDescription: string, issues: string}} ctx
485
+ */
486
+ function createAndAnnounce(manager, ctx) {
487
+ const { projectDir, branch, taskDescription, issues } = ctx;
488
+ const { sprintId, newState } = buildSprintState({
489
+ projectDir, branch, taskDescription, issues, previousRetro: readPreviousRetro(projectDir),
490
+ });
234
491
 
235
- // Write state atomically
236
492
  manager.write(newState);
237
493
 
238
494
  console.log(`✅ Sprint initialized: ${sprintId}`);
@@ -241,8 +497,6 @@ async function handleSprintInit(args = []) {
241
497
  if (issues) console.log(` Issues: ${issues}`);
242
498
  console.log('');
243
499
  console.log(renderDashboard(newState));
244
-
245
- return 0;
246
500
  }
247
501
 
248
- module.exports = { handleSprintInit, detectBranch, generateSprintId, backupSprintState };
502
+ module.exports = { handleSprintInit, detectBranch, generateSprintId, backupSprintState, parseSprintInitArgs };